babylon.viewer.max.js 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105
  1. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  2. var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || (typeof require !== 'undefined' && require("babylonjs"));
  3. var BABYLON = babylonDependency;
  4. var BabylonViewer =
  5. /******/ (function(modules) { // webpackBootstrap
  6. /******/ // The module cache
  7. /******/ var installedModules = {};
  8. /******/
  9. /******/ // The require function
  10. /******/ function __webpack_require__(moduleId) {
  11. /******/
  12. /******/ // Check if module is in cache
  13. /******/ if(installedModules[moduleId]) {
  14. /******/ return installedModules[moduleId].exports;
  15. /******/ }
  16. /******/ // Create a new module (and put it into the cache)
  17. /******/ var module = installedModules[moduleId] = {
  18. /******/ i: moduleId,
  19. /******/ l: false,
  20. /******/ exports: {}
  21. /******/ };
  22. /******/
  23. /******/ // Execute the module function
  24. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  25. /******/
  26. /******/ // Flag the module as loaded
  27. /******/ module.l = true;
  28. /******/
  29. /******/ // Return the exports of the module
  30. /******/ return module.exports;
  31. /******/ }
  32. /******/
  33. /******/
  34. /******/ // expose the modules object (__webpack_modules__)
  35. /******/ __webpack_require__.m = modules;
  36. /******/
  37. /******/ // expose the module cache
  38. /******/ __webpack_require__.c = installedModules;
  39. /******/
  40. /******/ // define getter function for harmony exports
  41. /******/ __webpack_require__.d = function(exports, name, getter) {
  42. /******/ if(!__webpack_require__.o(exports, name)) {
  43. /******/ Object.defineProperty(exports, name, {
  44. /******/ configurable: false,
  45. /******/ enumerable: true,
  46. /******/ get: getter
  47. /******/ });
  48. /******/ }
  49. /******/ };
  50. /******/
  51. /******/ // getDefaultExport function for compatibility with non-harmony modules
  52. /******/ __webpack_require__.n = function(module) {
  53. /******/ var getter = module && module.__esModule ?
  54. /******/ function getDefault() { return module['default']; } :
  55. /******/ function getModuleExports() { return module; };
  56. /******/ __webpack_require__.d(getter, 'a', getter);
  57. /******/ return getter;
  58. /******/ };
  59. /******/
  60. /******/ // Object.prototype.hasOwnProperty.call
  61. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  62. /******/
  63. /******/ // __webpack_public_path__
  64. /******/ __webpack_require__.p = "";
  65. /******/
  66. /******/ // Load entry module and return exports
  67. /******/ return __webpack_require__(__webpack_require__.s = 15);
  68. /******/ })
  69. /************************************************************************/
  70. /******/ ([
  71. /* 0 */
  72. /***/ (function(module, exports, __webpack_require__) {
  73. /* WEBPACK VAR INJECTION */(function(global) {var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  74. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  75. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  76. 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;
  77. return c > 3 && r && Object.defineProperty(target, key, r), r;
  78. };
  79. var __extends = (this && this.__extends) || (function () {
  80. var extendStatics = Object.setPrototypeOf ||
  81. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  82. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  83. return function (d, b) {
  84. extendStatics(d, b);
  85. function __() { this.constructor = d; }
  86. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  87. };
  88. })();
  89. var BABYLON;
  90. (function (BABYLON) {
  91. /**
  92. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  93. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  94. */
  95. var EffectFallbacks = /** @class */ (function () {
  96. function EffectFallbacks() {
  97. this._defines = {};
  98. this._currentRank = 32;
  99. this._maxRank = -1;
  100. }
  101. /**
  102. * Removes the fallback from the bound mesh.
  103. */
  104. EffectFallbacks.prototype.unBindMesh = function () {
  105. this._mesh = null;
  106. };
  107. /**
  108. * Adds a fallback on the specified property.
  109. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  110. * @param define The name of the define in the shader
  111. */
  112. EffectFallbacks.prototype.addFallback = function (rank, define) {
  113. if (!this._defines[rank]) {
  114. if (rank < this._currentRank) {
  115. this._currentRank = rank;
  116. }
  117. if (rank > this._maxRank) {
  118. this._maxRank = rank;
  119. }
  120. this._defines[rank] = new Array();
  121. }
  122. this._defines[rank].push(define);
  123. };
  124. /**
  125. * Sets the mesh to use CPU skinning when needing to fallback.
  126. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  127. * @param mesh The mesh to use the fallbacks.
  128. */
  129. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  130. this._mesh = mesh;
  131. if (rank < this._currentRank) {
  132. this._currentRank = rank;
  133. }
  134. if (rank > this._maxRank) {
  135. this._maxRank = rank;
  136. }
  137. };
  138. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  139. /**
  140. * Checks to see if more fallbacks are still availible.
  141. */
  142. get: function () {
  143. return this._currentRank <= this._maxRank;
  144. },
  145. enumerable: true,
  146. configurable: true
  147. });
  148. /**
  149. * Removes the defines that shoould be removed when falling back.
  150. * @param currentDefines defines the current define statements for the shader.
  151. * @param effect defines the current effect we try to compile
  152. * @returns The resulting defines with defines of the current rank removed.
  153. */
  154. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  155. // First we try to switch to CPU skinning
  156. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  157. this._mesh.computeBonesUsingShaders = false;
  158. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  159. var scene = this._mesh.getScene();
  160. for (var index = 0; index < scene.meshes.length; index++) {
  161. var otherMesh = scene.meshes[index];
  162. if (!otherMesh.material) {
  163. continue;
  164. }
  165. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  166. continue;
  167. }
  168. if (otherMesh.material.getEffect() === effect) {
  169. otherMesh.computeBonesUsingShaders = false;
  170. }
  171. else {
  172. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  173. var subMesh = _a[_i];
  174. var subMeshEffect = subMesh.effect;
  175. if (subMeshEffect === effect) {
  176. otherMesh.computeBonesUsingShaders = false;
  177. break;
  178. }
  179. }
  180. }
  181. }
  182. }
  183. else {
  184. var currentFallbacks = this._defines[this._currentRank];
  185. if (currentFallbacks) {
  186. for (var index = 0; index < currentFallbacks.length; index++) {
  187. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  188. }
  189. }
  190. this._currentRank++;
  191. }
  192. return currentDefines;
  193. };
  194. return EffectFallbacks;
  195. }());
  196. BABYLON.EffectFallbacks = EffectFallbacks;
  197. /**
  198. * Options to be used when creating an effect.
  199. */
  200. var EffectCreationOptions = /** @class */ (function () {
  201. function EffectCreationOptions() {
  202. }
  203. return EffectCreationOptions;
  204. }());
  205. BABYLON.EffectCreationOptions = EffectCreationOptions;
  206. /**
  207. * Effect containing vertex and fragment shader that can be executed on an object.
  208. */
  209. var Effect = /** @class */ (function () {
  210. /**
  211. * Instantiates an effect.
  212. * An effect can be used to create/manage/execute vertex and fragment shaders.
  213. * @param baseName Name of the effect.
  214. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  215. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  216. * @param samplers List of sampler variables that will be passed to the shader.
  217. * @param engine Engine to be used to render the effect
  218. * @param defines Define statements to be added to the shader.
  219. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  220. * @param onCompiled Callback that will be called when the shader is compiled.
  221. * @param onError Callback that will be called if an error occurs during shader compilation.
  222. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  223. */
  224. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  225. if (samplers === void 0) { samplers = null; }
  226. if (defines === void 0) { defines = null; }
  227. if (fallbacks === void 0) { fallbacks = null; }
  228. if (onCompiled === void 0) { onCompiled = null; }
  229. if (onError === void 0) { onError = null; }
  230. var _this = this;
  231. /**
  232. * Unique ID of the effect.
  233. */
  234. this.uniqueId = 0;
  235. /**
  236. * Observable that will be called when the shader is compiled.
  237. */
  238. this.onCompileObservable = new BABYLON.Observable();
  239. /**
  240. * Observable that will be called if an error occurs during shader compilation.
  241. */
  242. this.onErrorObservable = new BABYLON.Observable();
  243. /**
  244. * Observable that will be called when effect is bound.
  245. */
  246. this.onBindObservable = new BABYLON.Observable();
  247. this._uniformBuffersNames = {};
  248. this._isReady = false;
  249. this._compilationError = "";
  250. this.name = baseName;
  251. if (attributesNamesOrOptions.attributes) {
  252. var options = attributesNamesOrOptions;
  253. this._engine = uniformsNamesOrEngine;
  254. this._attributesNames = options.attributes;
  255. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  256. this._samplers = options.samplers;
  257. this.defines = options.defines;
  258. this.onError = options.onError;
  259. this.onCompiled = options.onCompiled;
  260. this._fallbacks = options.fallbacks;
  261. this._indexParameters = options.indexParameters;
  262. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  263. if (options.uniformBuffersNames) {
  264. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  265. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  266. }
  267. }
  268. }
  269. else {
  270. this._engine = engine;
  271. this.defines = defines;
  272. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  273. this._samplers = samplers;
  274. this._attributesNames = attributesNamesOrOptions;
  275. this.onError = onError;
  276. this.onCompiled = onCompiled;
  277. this._indexParameters = indexParameters;
  278. this._fallbacks = fallbacks;
  279. }
  280. this.uniqueId = Effect._uniqueIdSeed++;
  281. var vertexSource;
  282. var fragmentSource;
  283. if (baseName.vertexElement) {
  284. vertexSource = document.getElementById(baseName.vertexElement);
  285. if (!vertexSource) {
  286. vertexSource = baseName.vertexElement;
  287. }
  288. }
  289. else {
  290. vertexSource = baseName.vertex || baseName;
  291. }
  292. if (baseName.fragmentElement) {
  293. fragmentSource = document.getElementById(baseName.fragmentElement);
  294. if (!fragmentSource) {
  295. fragmentSource = baseName.fragmentElement;
  296. }
  297. }
  298. else {
  299. fragmentSource = baseName.fragment || baseName;
  300. }
  301. var finalVertexCode;
  302. this._loadVertexShaderAsync(vertexSource)
  303. .then(function (vertexCode) {
  304. return _this._processIncludesAsync(vertexCode);
  305. })
  306. .then(function (vertexCodeWithIncludes) {
  307. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  308. return _this._loadFragmentShaderAsync(fragmentSource);
  309. })
  310. .then(function (fragmentCode) {
  311. return _this._processIncludesAsync(fragmentCode);
  312. })
  313. .then(function (fragmentCodeWithIncludes) {
  314. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  315. if (baseName) {
  316. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  317. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  318. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  319. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  320. }
  321. else {
  322. _this._vertexSourceCode = finalVertexCode;
  323. _this._fragmentSourceCode = migratedFragmentCode;
  324. }
  325. _this._prepareEffect();
  326. });
  327. }
  328. Object.defineProperty(Effect.prototype, "key", {
  329. /**
  330. * Unique key for this effect
  331. */
  332. get: function () {
  333. return this._key;
  334. },
  335. enumerable: true,
  336. configurable: true
  337. });
  338. /**
  339. * If the effect has been compiled and prepared.
  340. * @returns if the effect is compiled and prepared.
  341. */
  342. Effect.prototype.isReady = function () {
  343. return this._isReady;
  344. };
  345. /**
  346. * The engine the effect was initialized with.
  347. * @returns the engine.
  348. */
  349. Effect.prototype.getEngine = function () {
  350. return this._engine;
  351. };
  352. /**
  353. * The compiled webGL program for the effect
  354. * @returns the webGL program.
  355. */
  356. Effect.prototype.getProgram = function () {
  357. return this._program;
  358. };
  359. /**
  360. * The set of names of attribute variables for the shader.
  361. * @returns An array of attribute names.
  362. */
  363. Effect.prototype.getAttributesNames = function () {
  364. return this._attributesNames;
  365. };
  366. /**
  367. * Returns the attribute at the given index.
  368. * @param index The index of the attribute.
  369. * @returns The location of the attribute.
  370. */
  371. Effect.prototype.getAttributeLocation = function (index) {
  372. return this._attributes[index];
  373. };
  374. /**
  375. * Returns the attribute based on the name of the variable.
  376. * @param name of the attribute to look up.
  377. * @returns the attribute location.
  378. */
  379. Effect.prototype.getAttributeLocationByName = function (name) {
  380. var index = this._attributesNames.indexOf(name);
  381. return this._attributes[index];
  382. };
  383. /**
  384. * The number of attributes.
  385. * @returns the numnber of attributes.
  386. */
  387. Effect.prototype.getAttributesCount = function () {
  388. return this._attributes.length;
  389. };
  390. /**
  391. * Gets the index of a uniform variable.
  392. * @param uniformName of the uniform to look up.
  393. * @returns the index.
  394. */
  395. Effect.prototype.getUniformIndex = function (uniformName) {
  396. return this._uniformsNames.indexOf(uniformName);
  397. };
  398. /**
  399. * Returns the attribute based on the name of the variable.
  400. * @param uniformName of the uniform to look up.
  401. * @returns the location of the uniform.
  402. */
  403. Effect.prototype.getUniform = function (uniformName) {
  404. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  405. };
  406. /**
  407. * Returns an array of sampler variable names
  408. * @returns The array of sampler variable neames.
  409. */
  410. Effect.prototype.getSamplers = function () {
  411. return this._samplers;
  412. };
  413. /**
  414. * The error from the last compilation.
  415. * @returns the error string.
  416. */
  417. Effect.prototype.getCompilationError = function () {
  418. return this._compilationError;
  419. };
  420. /**
  421. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  422. * @param func The callback to be used.
  423. */
  424. Effect.prototype.executeWhenCompiled = function (func) {
  425. if (this.isReady()) {
  426. func(this);
  427. return;
  428. }
  429. this.onCompileObservable.add(function (effect) {
  430. func(effect);
  431. });
  432. };
  433. /** @ignore */
  434. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  435. if (BABYLON.Tools.IsWindowObjectExist()) {
  436. // DOM element ?
  437. if (vertex instanceof HTMLElement) {
  438. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  439. return Promise.resolve(vertexCode);
  440. }
  441. }
  442. // Base64 encoded ?
  443. if (vertex.substr(0, 7) === "base64:") {
  444. var vertexBinary = window.atob(vertex.substr(7));
  445. return Promise.resolve(vertexBinary);
  446. }
  447. // Is in local store ?
  448. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  449. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  450. }
  451. var vertexShaderUrl;
  452. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  453. vertexShaderUrl = vertex;
  454. }
  455. else {
  456. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  457. }
  458. // Vertex shader
  459. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  460. };
  461. /** @ignore */
  462. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  463. if (BABYLON.Tools.IsWindowObjectExist()) {
  464. // DOM element ?
  465. if (fragment instanceof HTMLElement) {
  466. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  467. return Promise.resolve(fragmentCode);
  468. }
  469. }
  470. // Base64 encoded ?
  471. if (fragment.substr(0, 7) === "base64:") {
  472. var fragmentBinary = window.atob(fragment.substr(7));
  473. return Promise.resolve(fragmentBinary);
  474. }
  475. // Is in local store ?
  476. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  477. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  478. }
  479. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  480. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  481. }
  482. var fragmentShaderUrl;
  483. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  484. fragmentShaderUrl = fragment;
  485. }
  486. else {
  487. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  488. }
  489. // Fragment shader
  490. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  491. };
  492. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  493. // Rebuild shaders source code
  494. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  495. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  496. vertexCode = prefix + vertexCode;
  497. fragmentCode = prefix + fragmentCode;
  498. // Number lines of shaders source code
  499. var i = 2;
  500. var regex = /\n/gm;
  501. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  502. i = 2;
  503. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  504. // Dump shaders name and formatted source code
  505. if (this.name.vertexElement) {
  506. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  507. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  508. }
  509. else if (this.name.vertex) {
  510. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  511. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  512. }
  513. else {
  514. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  515. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  516. }
  517. };
  518. ;
  519. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  520. var preparedSourceCode = this._processPrecision(sourceCode);
  521. if (this._engine.webGLVersion == 1) {
  522. return preparedSourceCode;
  523. }
  524. // Already converted
  525. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  526. return preparedSourceCode.replace("#version 300 es", "");
  527. }
  528. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  529. // Remove extensions
  530. // #extension GL_OES_standard_derivatives : enable
  531. // #extension GL_EXT_shader_texture_lod : enable
  532. // #extension GL_EXT_frag_depth : enable
  533. // #extension GL_EXT_draw_buffers : require
  534. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  535. var result = preparedSourceCode.replace(regex, "");
  536. // Migrate to GLSL v300
  537. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  538. result = result.replace(/attribute[ \t]/g, "in ");
  539. result = result.replace(/[ \t]attribute/g, " in");
  540. if (isFragment) {
  541. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  542. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  543. result = result.replace(/texture2D\s*\(/g, "texture(");
  544. result = result.replace(/textureCube\s*\(/g, "texture(");
  545. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  546. result = result.replace(/gl_FragColor/g, "glFragColor");
  547. result = result.replace(/gl_FragData/g, "glFragData");
  548. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  549. }
  550. return result;
  551. };
  552. Effect.prototype._processIncludesAsync = function (sourceCode) {
  553. var _this = this;
  554. return new Promise(function (resolve, reject) {
  555. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  556. var match = regex.exec(sourceCode);
  557. var returnValue = sourceCode;
  558. while (match != null) {
  559. var includeFile = match[1];
  560. // Uniform declaration
  561. if (includeFile.indexOf("__decl__") !== -1) {
  562. includeFile = includeFile.replace(/__decl__/, "");
  563. if (_this._engine.supportsUniformBuffers) {
  564. includeFile = includeFile.replace(/Vertex/, "Ubo");
  565. includeFile = includeFile.replace(/Fragment/, "Ubo");
  566. }
  567. includeFile = includeFile + "Declaration";
  568. }
  569. if (Effect.IncludesShadersStore[includeFile]) {
  570. // Substitution
  571. var includeContent = Effect.IncludesShadersStore[includeFile];
  572. if (match[2]) {
  573. var splits = match[3].split(",");
  574. for (var index = 0; index < splits.length; index += 2) {
  575. var source = new RegExp(splits[index], "g");
  576. var dest = splits[index + 1];
  577. includeContent = includeContent.replace(source, dest);
  578. }
  579. }
  580. if (match[4]) {
  581. var indexString = match[5];
  582. if (indexString.indexOf("..") !== -1) {
  583. var indexSplits = indexString.split("..");
  584. var minIndex = parseInt(indexSplits[0]);
  585. var maxIndex = parseInt(indexSplits[1]);
  586. var sourceIncludeContent = includeContent.slice(0);
  587. includeContent = "";
  588. if (isNaN(maxIndex)) {
  589. maxIndex = _this._indexParameters[indexSplits[1]];
  590. }
  591. for (var i = minIndex; i < maxIndex; i++) {
  592. if (!_this._engine.supportsUniformBuffers) {
  593. // Ubo replacement
  594. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  595. return p1 + "{X}";
  596. });
  597. }
  598. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  599. }
  600. }
  601. else {
  602. if (!_this._engine.supportsUniformBuffers) {
  603. // Ubo replacement
  604. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  605. return p1 + "{X}";
  606. });
  607. }
  608. includeContent = includeContent.replace(/\{X\}/g, indexString);
  609. }
  610. }
  611. // Replace
  612. returnValue = returnValue.replace(match[0], includeContent);
  613. }
  614. else {
  615. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  616. _this._engine._loadFileAsync(includeShaderUrl)
  617. .then(function (fileContent) {
  618. Effect.IncludesShadersStore[includeFile] = fileContent;
  619. return _this._processIncludesAsync(returnValue);
  620. })
  621. .then(function (returnValue) {
  622. resolve(returnValue);
  623. });
  624. return;
  625. }
  626. match = regex.exec(sourceCode);
  627. }
  628. resolve(returnValue);
  629. });
  630. };
  631. Effect.prototype._processPrecision = function (source) {
  632. if (source.indexOf("precision highp float") === -1) {
  633. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  634. source = "precision mediump float;\n" + source;
  635. }
  636. else {
  637. source = "precision highp float;\n" + source;
  638. }
  639. }
  640. else {
  641. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  642. source = source.replace("precision highp float", "precision mediump float");
  643. }
  644. }
  645. return source;
  646. };
  647. /**
  648. * Recompiles the webGL program
  649. * @param vertexSourceCode The source code for the vertex shader.
  650. * @param fragmentSourceCode The source code for the fragment shader.
  651. * @param onCompiled Callback called when completed.
  652. * @param onError Callback called on error.
  653. */
  654. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  655. var _this = this;
  656. this._isReady = false;
  657. this._vertexSourceCodeOverride = vertexSourceCode;
  658. this._fragmentSourceCodeOverride = fragmentSourceCode;
  659. this.onError = function (effect, error) {
  660. if (onError) {
  661. onError(error);
  662. }
  663. };
  664. this.onCompiled = function () {
  665. var scenes = _this.getEngine().scenes;
  666. for (var i = 0; i < scenes.length; i++) {
  667. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  668. }
  669. if (onCompiled) {
  670. onCompiled(_this._program);
  671. }
  672. };
  673. this._fallbacks = null;
  674. this._prepareEffect();
  675. };
  676. /**
  677. * Gets the uniform locations of the the specified variable names
  678. * @param names THe names of the variables to lookup.
  679. * @returns Array of locations in the same order as variable names.
  680. */
  681. Effect.prototype.getSpecificUniformLocations = function (names) {
  682. var engine = this._engine;
  683. return engine.getUniforms(this._program, names);
  684. };
  685. /**
  686. * Prepares the effect
  687. */
  688. Effect.prototype._prepareEffect = function () {
  689. var attributesNames = this._attributesNames;
  690. var defines = this.defines;
  691. var fallbacks = this._fallbacks;
  692. this._valueCache = {};
  693. var previousProgram = this._program;
  694. try {
  695. var engine = this._engine;
  696. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  697. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  698. }
  699. else {
  700. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  701. }
  702. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  703. if (engine.supportsUniformBuffers) {
  704. for (var name in this._uniformBuffersNames) {
  705. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  706. }
  707. }
  708. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  709. this._attributes = engine.getAttributes(this._program, attributesNames);
  710. var index;
  711. for (index = 0; index < this._samplers.length; index++) {
  712. var sampler = this.getUniform(this._samplers[index]);
  713. if (sampler == null) {
  714. this._samplers.splice(index, 1);
  715. index--;
  716. }
  717. }
  718. engine.bindSamplers(this);
  719. this._compilationError = "";
  720. this._isReady = true;
  721. if (this.onCompiled) {
  722. this.onCompiled(this);
  723. }
  724. this.onCompileObservable.notifyObservers(this);
  725. this.onCompileObservable.clear();
  726. // Unbind mesh reference in fallbacks
  727. if (this._fallbacks) {
  728. this._fallbacks.unBindMesh();
  729. }
  730. if (previousProgram) {
  731. this.getEngine()._deleteProgram(previousProgram);
  732. }
  733. }
  734. catch (e) {
  735. this._compilationError = e.message;
  736. // Let's go through fallbacks then
  737. BABYLON.Tools.Error("Unable to compile effect:");
  738. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  739. return " " + uniform;
  740. }));
  741. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  742. return " " + attribute;
  743. }));
  744. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  745. BABYLON.Tools.Error("Error: " + this._compilationError);
  746. if (previousProgram) {
  747. this._program = previousProgram;
  748. this._isReady = true;
  749. if (this.onError) {
  750. this.onError(this, this._compilationError);
  751. }
  752. this.onErrorObservable.notifyObservers(this);
  753. }
  754. if (fallbacks && fallbacks.isMoreFallbacks) {
  755. BABYLON.Tools.Error("Trying next fallback.");
  756. this.defines = fallbacks.reduce(this.defines, this);
  757. this._prepareEffect();
  758. }
  759. else {
  760. if (this.onError) {
  761. this.onError(this, this._compilationError);
  762. }
  763. this.onErrorObservable.notifyObservers(this);
  764. this.onErrorObservable.clear();
  765. // Unbind mesh reference in fallbacks
  766. if (this._fallbacks) {
  767. this._fallbacks.unBindMesh();
  768. }
  769. }
  770. }
  771. };
  772. Object.defineProperty(Effect.prototype, "isSupported", {
  773. /**
  774. * Checks if the effect is supported. (Must be called after compilation)
  775. */
  776. get: function () {
  777. return this._compilationError === "";
  778. },
  779. enumerable: true,
  780. configurable: true
  781. });
  782. /**
  783. * Binds a texture to the engine to be used as output of the shader.
  784. * @param channel Name of the output variable.
  785. * @param texture Texture to bind.
  786. */
  787. Effect.prototype._bindTexture = function (channel, texture) {
  788. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  789. };
  790. /**
  791. * Sets a texture on the engine to be used in the shader.
  792. * @param channel Name of the sampler variable.
  793. * @param texture Texture to set.
  794. */
  795. Effect.prototype.setTexture = function (channel, texture) {
  796. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  797. };
  798. /**
  799. * Sets an array of textures on the engine to be used in the shader.
  800. * @param channel Name of the variable.
  801. * @param textures Textures to set.
  802. */
  803. Effect.prototype.setTextureArray = function (channel, textures) {
  804. if (this._samplers.indexOf(channel + "Ex") === -1) {
  805. var initialPos = this._samplers.indexOf(channel);
  806. for (var index = 1; index < textures.length; index++) {
  807. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  808. }
  809. }
  810. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  811. };
  812. /**
  813. * 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)
  814. * @param channel Name of the sampler variable.
  815. * @param postProcess Post process to get the input texture from.
  816. */
  817. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  818. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  819. };
  820. /** @ignore */
  821. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  822. var cache = this._valueCache[uniformName];
  823. var flag = matrix.updateFlag;
  824. if (cache !== undefined && cache === flag) {
  825. return false;
  826. }
  827. this._valueCache[uniformName] = flag;
  828. return true;
  829. };
  830. /** @ignore */
  831. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  832. var cache = this._valueCache[uniformName];
  833. if (!cache) {
  834. cache = [x, y];
  835. this._valueCache[uniformName] = cache;
  836. return true;
  837. }
  838. var changed = false;
  839. if (cache[0] !== x) {
  840. cache[0] = x;
  841. changed = true;
  842. }
  843. if (cache[1] !== y) {
  844. cache[1] = y;
  845. changed = true;
  846. }
  847. return changed;
  848. };
  849. /** @ignore */
  850. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  851. var cache = this._valueCache[uniformName];
  852. if (!cache) {
  853. cache = [x, y, z];
  854. this._valueCache[uniformName] = cache;
  855. return true;
  856. }
  857. var changed = false;
  858. if (cache[0] !== x) {
  859. cache[0] = x;
  860. changed = true;
  861. }
  862. if (cache[1] !== y) {
  863. cache[1] = y;
  864. changed = true;
  865. }
  866. if (cache[2] !== z) {
  867. cache[2] = z;
  868. changed = true;
  869. }
  870. return changed;
  871. };
  872. /** @ignore */
  873. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  874. var cache = this._valueCache[uniformName];
  875. if (!cache) {
  876. cache = [x, y, z, w];
  877. this._valueCache[uniformName] = cache;
  878. return true;
  879. }
  880. var changed = false;
  881. if (cache[0] !== x) {
  882. cache[0] = x;
  883. changed = true;
  884. }
  885. if (cache[1] !== y) {
  886. cache[1] = y;
  887. changed = true;
  888. }
  889. if (cache[2] !== z) {
  890. cache[2] = z;
  891. changed = true;
  892. }
  893. if (cache[3] !== w) {
  894. cache[3] = w;
  895. changed = true;
  896. }
  897. return changed;
  898. };
  899. /**
  900. * Binds a buffer to a uniform.
  901. * @param buffer Buffer to bind.
  902. * @param name Name of the uniform variable to bind to.
  903. */
  904. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  905. var bufferName = this._uniformBuffersNames[name];
  906. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  907. return;
  908. }
  909. Effect._baseCache[bufferName] = buffer;
  910. this._engine.bindUniformBufferBase(buffer, bufferName);
  911. };
  912. /**
  913. * Binds block to a uniform.
  914. * @param blockName Name of the block to bind.
  915. * @param index Index to bind.
  916. */
  917. Effect.prototype.bindUniformBlock = function (blockName, index) {
  918. this._engine.bindUniformBlock(this._program, blockName, index);
  919. };
  920. /**
  921. * Sets an interger value on a uniform variable.
  922. * @param uniformName Name of the variable.
  923. * @param value Value to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setInt = function (uniformName, value) {
  927. var cache = this._valueCache[uniformName];
  928. if (cache !== undefined && cache === value)
  929. return this;
  930. this._valueCache[uniformName] = value;
  931. this._engine.setInt(this.getUniform(uniformName), value);
  932. return this;
  933. };
  934. /**
  935. * Sets an int array on a uniform variable.
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setIntArray = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setIntArray(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setIntArray2 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setIntArray2(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * 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)
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setIntArray3 = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setIntArray3(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setIntArray4 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setIntArray4(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * Sets an float array on a uniform variable.
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setFloatArray = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setFloatArray(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * 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)
  1002. * @param uniformName Name of the variable.
  1003. * @param array array to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1009. return this;
  1010. };
  1011. /**
  1012. * 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)
  1013. * @param uniformName Name of the variable.
  1014. * @param array array to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1018. this._valueCache[uniformName] = null;
  1019. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1020. return this;
  1021. };
  1022. /**
  1023. * Sets an array on a uniform variable.
  1024. * @param uniformName Name of the variable.
  1025. * @param array array to be set.
  1026. * @returns this effect.
  1027. */
  1028. Effect.prototype.setArray = function (uniformName, array) {
  1029. this._valueCache[uniformName] = null;
  1030. this._engine.setArray(this.getUniform(uniformName), array);
  1031. return this;
  1032. };
  1033. /**
  1034. * 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)
  1035. * @param uniformName Name of the variable.
  1036. * @param array array to be set.
  1037. * @returns this effect.
  1038. */
  1039. Effect.prototype.setArray2 = function (uniformName, array) {
  1040. this._valueCache[uniformName] = null;
  1041. this._engine.setArray2(this.getUniform(uniformName), array);
  1042. return this;
  1043. };
  1044. /**
  1045. * 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)
  1046. * @param uniformName Name of the variable.
  1047. * @param array array to be set.
  1048. * @returns this effect.
  1049. */
  1050. Effect.prototype.setArray3 = function (uniformName, array) {
  1051. this._valueCache[uniformName] = null;
  1052. this._engine.setArray3(this.getUniform(uniformName), array);
  1053. return this;
  1054. };
  1055. /**
  1056. * 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)
  1057. * @param uniformName Name of the variable.
  1058. * @param array array to be set.
  1059. * @returns this effect.
  1060. */
  1061. Effect.prototype.setArray4 = function (uniformName, array) {
  1062. this._valueCache[uniformName] = null;
  1063. this._engine.setArray4(this.getUniform(uniformName), array);
  1064. return this;
  1065. };
  1066. /**
  1067. * Sets matrices on a uniform variable.
  1068. * @param uniformName Name of the variable.
  1069. * @param matrices matrices to be set.
  1070. * @returns this effect.
  1071. */
  1072. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1073. if (!matrices) {
  1074. return this;
  1075. }
  1076. this._valueCache[uniformName] = null;
  1077. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1078. return this;
  1079. };
  1080. /**
  1081. * Sets matrix on a uniform variable.
  1082. * @param uniformName Name of the variable.
  1083. * @param matrix matrix to be set.
  1084. * @returns this effect.
  1085. */
  1086. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1087. if (this._cacheMatrix(uniformName, matrix)) {
  1088. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1089. }
  1090. return this;
  1091. };
  1092. /**
  1093. * 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)
  1094. * @param uniformName Name of the variable.
  1095. * @param matrix matrix to be set.
  1096. * @returns this effect.
  1097. */
  1098. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1099. this._valueCache[uniformName] = null;
  1100. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1101. return this;
  1102. };
  1103. /**
  1104. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1105. * @param uniformName Name of the variable.
  1106. * @param matrix matrix to be set.
  1107. * @returns this effect.
  1108. */
  1109. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1110. this._valueCache[uniformName] = null;
  1111. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1112. return this;
  1113. };
  1114. /**
  1115. * Sets a float on a uniform variable.
  1116. * @param uniformName Name of the variable.
  1117. * @param value value to be set.
  1118. * @returns this effect.
  1119. */
  1120. Effect.prototype.setFloat = function (uniformName, value) {
  1121. var cache = this._valueCache[uniformName];
  1122. if (cache !== undefined && cache === value)
  1123. return this;
  1124. this._valueCache[uniformName] = value;
  1125. this._engine.setFloat(this.getUniform(uniformName), value);
  1126. return this;
  1127. };
  1128. /**
  1129. * Sets a boolean on a uniform variable.
  1130. * @param uniformName Name of the variable.
  1131. * @param bool value to be set.
  1132. * @returns this effect.
  1133. */
  1134. Effect.prototype.setBool = function (uniformName, bool) {
  1135. var cache = this._valueCache[uniformName];
  1136. if (cache !== undefined && cache === bool)
  1137. return this;
  1138. this._valueCache[uniformName] = bool;
  1139. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1140. return this;
  1141. };
  1142. /**
  1143. * Sets a Vector2 on a uniform variable.
  1144. * @param uniformName Name of the variable.
  1145. * @param vector2 vector2 to be set.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1149. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1150. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a float2 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param x First float in float2.
  1158. * @param y Second float in float2.
  1159. * @returns this effect.
  1160. */
  1161. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1162. if (this._cacheFloat2(uniformName, x, y)) {
  1163. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1164. }
  1165. return this;
  1166. };
  1167. /**
  1168. * Sets a Vector3 on a uniform variable.
  1169. * @param uniformName Name of the variable.
  1170. * @param vector3 Value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1174. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1175. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a float3 on a uniform variable.
  1181. * @param uniformName Name of the variable.
  1182. * @param x First float in float3.
  1183. * @param y Second float in float3.
  1184. * @param z Third float in float3.
  1185. * @returns this effect.
  1186. */
  1187. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1188. if (this._cacheFloat3(uniformName, x, y, z)) {
  1189. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1190. }
  1191. return this;
  1192. };
  1193. /**
  1194. * Sets a Vector4 on a uniform variable.
  1195. * @param uniformName Name of the variable.
  1196. * @param vector4 Value to be set.
  1197. * @returns this effect.
  1198. */
  1199. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1200. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1201. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1202. }
  1203. return this;
  1204. };
  1205. /**
  1206. * Sets a float4 on a uniform variable.
  1207. * @param uniformName Name of the variable.
  1208. * @param x First float in float4.
  1209. * @param y Second float in float4.
  1210. * @param z Third float in float4.
  1211. * @param w Fourth float in float4.
  1212. * @returns this effect.
  1213. */
  1214. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1215. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1216. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1217. }
  1218. return this;
  1219. };
  1220. /**
  1221. * Sets a Color3 on a uniform variable.
  1222. * @param uniformName Name of the variable.
  1223. * @param color3 Value to be set.
  1224. * @returns this effect.
  1225. */
  1226. Effect.prototype.setColor3 = function (uniformName, color3) {
  1227. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1228. this._engine.setColor3(this.getUniform(uniformName), color3);
  1229. }
  1230. return this;
  1231. };
  1232. /**
  1233. * Sets a Color4 on a uniform variable.
  1234. * @param uniformName Name of the variable.
  1235. * @param color3 Value to be set.
  1236. * @param alpha Alpha value to be set.
  1237. * @returns this effect.
  1238. */
  1239. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1240. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1241. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1242. }
  1243. return this;
  1244. };
  1245. /**
  1246. * Sets a Color4 on a uniform variable
  1247. * @param uniformName defines the name of the variable
  1248. * @param color4 defines the value to be set
  1249. * @returns this effect.
  1250. */
  1251. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1252. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1253. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1254. }
  1255. return this;
  1256. };
  1257. /**
  1258. * Resets the cache of effects.
  1259. */
  1260. Effect.ResetCache = function () {
  1261. Effect._baseCache = {};
  1262. };
  1263. Effect._uniqueIdSeed = 0;
  1264. Effect._baseCache = {};
  1265. // Statics
  1266. /**
  1267. * Store of each shader (The can be looked up using effect.key)
  1268. */
  1269. Effect.ShadersStore = {};
  1270. /**
  1271. * Store of each included file for a shader (The can be looked up using effect.key)
  1272. */
  1273. Effect.IncludesShadersStore = {};
  1274. return Effect;
  1275. }());
  1276. BABYLON.Effect = Effect;
  1277. })(BABYLON || (BABYLON = {}));
  1278. //# sourceMappingURL=babylon.effect.js.map
  1279. //# sourceMappingURL=babylon.types.js.map
  1280. var BABYLON;
  1281. (function (BABYLON) {
  1282. var KeyboardEventTypes = /** @class */ (function () {
  1283. function KeyboardEventTypes() {
  1284. }
  1285. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1286. get: function () {
  1287. return KeyboardEventTypes._KEYDOWN;
  1288. },
  1289. enumerable: true,
  1290. configurable: true
  1291. });
  1292. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1293. get: function () {
  1294. return KeyboardEventTypes._KEYUP;
  1295. },
  1296. enumerable: true,
  1297. configurable: true
  1298. });
  1299. KeyboardEventTypes._KEYDOWN = 0x01;
  1300. KeyboardEventTypes._KEYUP = 0x02;
  1301. return KeyboardEventTypes;
  1302. }());
  1303. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1304. var KeyboardInfo = /** @class */ (function () {
  1305. function KeyboardInfo(type, event) {
  1306. this.type = type;
  1307. this.event = event;
  1308. }
  1309. return KeyboardInfo;
  1310. }());
  1311. BABYLON.KeyboardInfo = KeyboardInfo;
  1312. /**
  1313. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1314. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1315. */
  1316. var KeyboardInfoPre = /** @class */ (function (_super) {
  1317. __extends(KeyboardInfoPre, _super);
  1318. function KeyboardInfoPre(type, event) {
  1319. var _this = _super.call(this, type, event) || this;
  1320. _this.skipOnPointerObservable = false;
  1321. return _this;
  1322. }
  1323. return KeyboardInfoPre;
  1324. }(KeyboardInfo));
  1325. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1326. })(BABYLON || (BABYLON = {}));
  1327. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1328. var BABYLON;
  1329. (function (BABYLON) {
  1330. var PointerEventTypes = /** @class */ (function () {
  1331. function PointerEventTypes() {
  1332. }
  1333. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1334. get: function () {
  1335. return PointerEventTypes._POINTERDOWN;
  1336. },
  1337. enumerable: true,
  1338. configurable: true
  1339. });
  1340. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1341. get: function () {
  1342. return PointerEventTypes._POINTERUP;
  1343. },
  1344. enumerable: true,
  1345. configurable: true
  1346. });
  1347. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1348. get: function () {
  1349. return PointerEventTypes._POINTERMOVE;
  1350. },
  1351. enumerable: true,
  1352. configurable: true
  1353. });
  1354. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1355. get: function () {
  1356. return PointerEventTypes._POINTERWHEEL;
  1357. },
  1358. enumerable: true,
  1359. configurable: true
  1360. });
  1361. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1362. get: function () {
  1363. return PointerEventTypes._POINTERPICK;
  1364. },
  1365. enumerable: true,
  1366. configurable: true
  1367. });
  1368. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1369. get: function () {
  1370. return PointerEventTypes._POINTERTAP;
  1371. },
  1372. enumerable: true,
  1373. configurable: true
  1374. });
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOUBLETAP;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. PointerEventTypes._POINTERDOWN = 0x01;
  1383. PointerEventTypes._POINTERUP = 0x02;
  1384. PointerEventTypes._POINTERMOVE = 0x04;
  1385. PointerEventTypes._POINTERWHEEL = 0x08;
  1386. PointerEventTypes._POINTERPICK = 0x10;
  1387. PointerEventTypes._POINTERTAP = 0x20;
  1388. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1389. return PointerEventTypes;
  1390. }());
  1391. BABYLON.PointerEventTypes = PointerEventTypes;
  1392. var PointerInfoBase = /** @class */ (function () {
  1393. function PointerInfoBase(type, event) {
  1394. this.type = type;
  1395. this.event = event;
  1396. }
  1397. return PointerInfoBase;
  1398. }());
  1399. BABYLON.PointerInfoBase = PointerInfoBase;
  1400. /**
  1401. * This class is used to store pointer related info for the onPrePointerObservable event.
  1402. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1403. */
  1404. var PointerInfoPre = /** @class */ (function (_super) {
  1405. __extends(PointerInfoPre, _super);
  1406. function PointerInfoPre(type, event, localX, localY) {
  1407. var _this = _super.call(this, type, event) || this;
  1408. _this.skipOnPointerObservable = false;
  1409. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1410. return _this;
  1411. }
  1412. return PointerInfoPre;
  1413. }(PointerInfoBase));
  1414. BABYLON.PointerInfoPre = PointerInfoPre;
  1415. /**
  1416. * This type contains all the data related to a pointer event in Babylon.js.
  1417. * 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.
  1418. */
  1419. var PointerInfo = /** @class */ (function (_super) {
  1420. __extends(PointerInfo, _super);
  1421. function PointerInfo(type, event, pickInfo) {
  1422. var _this = _super.call(this, type, event) || this;
  1423. _this.pickInfo = pickInfo;
  1424. return _this;
  1425. }
  1426. return PointerInfo;
  1427. }(PointerInfoBase));
  1428. BABYLON.PointerInfo = PointerInfo;
  1429. })(BABYLON || (BABYLON = {}));
  1430. //# sourceMappingURL=babylon.pointerEvents.js.map
  1431. var BABYLON;
  1432. (function (BABYLON) {
  1433. BABYLON.ToGammaSpace = 1 / 2.2;
  1434. BABYLON.ToLinearSpace = 2.2;
  1435. BABYLON.Epsilon = 0.001;
  1436. /**
  1437. * Class used to hold a RBG color
  1438. */
  1439. var Color3 = /** @class */ (function () {
  1440. /**
  1441. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1442. * @param r defines the red component (between 0 and 1, default is 0)
  1443. * @param g defines the green component (between 0 and 1, default is 0)
  1444. * @param b defines the blue component (between 0 and 1, default is 0)
  1445. */
  1446. function Color3(
  1447. /**
  1448. * Defines the red component (between 0 and 1, default is 0)
  1449. */
  1450. r,
  1451. /**
  1452. * Defines the green component (between 0 and 1, default is 0)
  1453. */
  1454. g,
  1455. /**
  1456. * Defines the blue component (between 0 and 1, default is 0)
  1457. */
  1458. b) {
  1459. if (r === void 0) { r = 0; }
  1460. if (g === void 0) { g = 0; }
  1461. if (b === void 0) { b = 0; }
  1462. this.r = r;
  1463. this.g = g;
  1464. this.b = b;
  1465. }
  1466. /**
  1467. * Creates a string with the Color3 current values
  1468. * @returns the string representation of the Color3 object
  1469. */
  1470. Color3.prototype.toString = function () {
  1471. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1472. };
  1473. /**
  1474. * Returns the string "Color3"
  1475. * @returns "Color3"
  1476. */
  1477. Color3.prototype.getClassName = function () {
  1478. return "Color3";
  1479. };
  1480. /**
  1481. * Compute the Color3 hash code
  1482. * @returns an unique number that can be used to hash Color3 objects
  1483. */
  1484. Color3.prototype.getHashCode = function () {
  1485. var hash = this.r || 0;
  1486. hash = (hash * 397) ^ (this.g || 0);
  1487. hash = (hash * 397) ^ (this.b || 0);
  1488. return hash;
  1489. };
  1490. // Operators
  1491. /**
  1492. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1493. * @param array defines the array where to store the r,g,b components
  1494. * @param index defines an optional index in the target array to define where to start storing values
  1495. * @returns the current Color3 object
  1496. */
  1497. Color3.prototype.toArray = function (array, index) {
  1498. if (index === undefined) {
  1499. index = 0;
  1500. }
  1501. array[index] = this.r;
  1502. array[index + 1] = this.g;
  1503. array[index + 2] = this.b;
  1504. return this;
  1505. };
  1506. /**
  1507. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1508. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1509. * @returns a new {BABYLON.Color4} object
  1510. */
  1511. Color3.prototype.toColor4 = function (alpha) {
  1512. if (alpha === void 0) { alpha = 1; }
  1513. return new Color4(this.r, this.g, this.b, alpha);
  1514. };
  1515. /**
  1516. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1517. * @returns the new array
  1518. */
  1519. Color3.prototype.asArray = function () {
  1520. var result = new Array();
  1521. this.toArray(result, 0);
  1522. return result;
  1523. };
  1524. /**
  1525. * Returns the luminance value
  1526. * @returns a float value
  1527. */
  1528. Color3.prototype.toLuminance = function () {
  1529. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1530. };
  1531. /**
  1532. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1533. * @param otherColor defines the second operand
  1534. * @returns the new Color3 object
  1535. */
  1536. Color3.prototype.multiply = function (otherColor) {
  1537. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1538. };
  1539. /**
  1540. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1541. * @param otherColor defines the second operand
  1542. * @param result defines the Color3 object where to store the result
  1543. * @returns the current Color3
  1544. */
  1545. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1546. result.r = this.r * otherColor.r;
  1547. result.g = this.g * otherColor.g;
  1548. result.b = this.b * otherColor.b;
  1549. return this;
  1550. };
  1551. /**
  1552. * Determines equality between Color3 objects
  1553. * @param otherColor defines the second operand
  1554. * @returns true if the rgb values are equal to the passed ones
  1555. */
  1556. Color3.prototype.equals = function (otherColor) {
  1557. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1558. };
  1559. /**
  1560. * Determines equality between the current Color3 object and a set of r,b,g values
  1561. * @param r defines the red component to check
  1562. * @param g defines the green component to check
  1563. * @param b defines the blue component to check
  1564. * @returns true if the rgb values are equal to the passed ones
  1565. */
  1566. Color3.prototype.equalsFloats = function (r, g, b) {
  1567. return this.r === r && this.g === g && this.b === b;
  1568. };
  1569. /**
  1570. * Multiplies in place each rgb value by scale
  1571. * @param scale defines the scaling factor
  1572. * @returns the updated Color3.
  1573. */
  1574. Color3.prototype.scale = function (scale) {
  1575. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1576. };
  1577. /**
  1578. * Multiplies the rgb values by scale and stores the result into "result"
  1579. * @param scale defines the scaling factor
  1580. * @param result defines the Color3 object where to store the result
  1581. * @returns the unmodified current Color3.
  1582. */
  1583. Color3.prototype.scaleToRef = function (scale, result) {
  1584. result.r = this.r * scale;
  1585. result.g = this.g * scale;
  1586. result.b = this.b * scale;
  1587. return this;
  1588. };
  1589. /**
  1590. * Clamps the rgb values by the min and max values and stores the result into "result"
  1591. * @param min defines minimum clamping value (default is 0)
  1592. * @param max defines maximum clamping value (default is 1)
  1593. * @param result defines color to store the result into
  1594. * @returns the original Color3
  1595. */
  1596. Color3.prototype.clampToRef = function (min, max, result) {
  1597. if (min === void 0) { min = 0; }
  1598. if (max === void 0) { max = 1; }
  1599. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1600. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1601. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1602. return this;
  1603. };
  1604. /**
  1605. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1606. * @param otherColor defines the second operand
  1607. * @returns the new Color3
  1608. */
  1609. Color3.prototype.add = function (otherColor) {
  1610. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1611. };
  1612. /**
  1613. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1614. * @param otherColor defines the second operand
  1615. * @param result defines Color3 object to store the result into
  1616. * @returns the unmodified current Color3
  1617. */
  1618. Color3.prototype.addToRef = function (otherColor, result) {
  1619. result.r = this.r + otherColor.r;
  1620. result.g = this.g + otherColor.g;
  1621. result.b = this.b + otherColor.b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1626. * @param otherColor defines the second operand
  1627. * @returns the new Color3
  1628. */
  1629. Color3.prototype.subtract = function (otherColor) {
  1630. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1631. };
  1632. /**
  1633. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1634. * @param otherColor defines the second operand
  1635. * @param result defines Color3 object to store the result into
  1636. * @returns the unmodified current Color3
  1637. */
  1638. Color3.prototype.subtractToRef = function (otherColor, result) {
  1639. result.r = this.r - otherColor.r;
  1640. result.g = this.g - otherColor.g;
  1641. result.b = this.b - otherColor.b;
  1642. return this;
  1643. };
  1644. /**
  1645. * Copy the current object
  1646. * @returns a new Color3 copied the current one
  1647. */
  1648. Color3.prototype.clone = function () {
  1649. return new Color3(this.r, this.g, this.b);
  1650. };
  1651. /**
  1652. * Copies the rgb values from the source in the current Color3
  1653. * @param source defines the source Color3 object
  1654. * @returns the updated Color3 object
  1655. */
  1656. Color3.prototype.copyFrom = function (source) {
  1657. this.r = source.r;
  1658. this.g = source.g;
  1659. this.b = source.b;
  1660. return this;
  1661. };
  1662. /**
  1663. * Updates the Color3 rgb values from the passed floats
  1664. * @param r defines the red component to read from
  1665. * @param g defines the green component to read from
  1666. * @param b defines the blue component to read from
  1667. * @returns the current Color3 object
  1668. */
  1669. Color3.prototype.copyFromFloats = function (r, g, b) {
  1670. this.r = r;
  1671. this.g = g;
  1672. this.b = b;
  1673. return this;
  1674. };
  1675. /**
  1676. * Updates the Color3 rgb values from the passed floats
  1677. * @param r defines the red component to read from
  1678. * @param g defines the green component to read from
  1679. * @param b defines the blue component to read from
  1680. * @returns the current Color3 object
  1681. */
  1682. Color3.prototype.set = function (r, g, b) {
  1683. return this.copyFromFloats(r, g, b);
  1684. };
  1685. /**
  1686. * Compute the Color3 hexadecimal code as a string
  1687. * @returns a string containing the hexadecimal representation of the Color3 object
  1688. */
  1689. Color3.prototype.toHexString = function () {
  1690. var intR = (this.r * 255) | 0;
  1691. var intG = (this.g * 255) | 0;
  1692. var intB = (this.b * 255) | 0;
  1693. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1694. };
  1695. /**
  1696. * Computes a new Color3 converted from the current one to linear space
  1697. * @returns a new Color3 object
  1698. */
  1699. Color3.prototype.toLinearSpace = function () {
  1700. var convertedColor = new Color3();
  1701. this.toLinearSpaceToRef(convertedColor);
  1702. return convertedColor;
  1703. };
  1704. /**
  1705. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1706. * @param convertedColor defines the Color3 object where to store the linear space version
  1707. * @returns the unmodified Color3
  1708. */
  1709. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1710. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1711. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1712. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1713. return this;
  1714. };
  1715. /**
  1716. * Computes a new Color3 converted from the current one to gamma space
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.prototype.toGammaSpace = function () {
  1720. var convertedColor = new Color3();
  1721. this.toGammaSpaceToRef(convertedColor);
  1722. return convertedColor;
  1723. };
  1724. /**
  1725. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1726. * @param convertedColor defines the Color3 object where to store the gamma space version
  1727. * @returns the unmodified Color3
  1728. */
  1729. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1730. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1731. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1732. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1733. return this;
  1734. };
  1735. // Statics
  1736. /**
  1737. * Creates a new Color3 from the string containing valid hexadecimal values
  1738. * @param hex defines a string containing valid hexadecimal values
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.FromHexString = function (hex) {
  1742. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1743. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  1744. return new Color3(0, 0, 0);
  1745. }
  1746. var r = parseInt(hex.substring(1, 3), 16);
  1747. var g = parseInt(hex.substring(3, 5), 16);
  1748. var b = parseInt(hex.substring(5, 7), 16);
  1749. return Color3.FromInts(r, g, b);
  1750. };
  1751. /**
  1752. * Creates a new Vector3 from the starting index of the passed array
  1753. * @param array defines the source array
  1754. * @param offset defines an offset in the source array
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.FromArray = function (array, offset) {
  1758. if (offset === void 0) { offset = 0; }
  1759. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1760. };
  1761. /**
  1762. * Creates a new Color3 from integer values (< 256)
  1763. * @param r defines the red component to read from (value between 0 and 255)
  1764. * @param g defines the green component to read from (value between 0 and 255)
  1765. * @param b defines the blue component to read from (value between 0 and 255)
  1766. * @returns a new Color3 object
  1767. */
  1768. Color3.FromInts = function (r, g, b) {
  1769. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1770. };
  1771. /**
  1772. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1773. * @param start defines the start Color3 value
  1774. * @param end defines the end Color3 value
  1775. * @param amount defines the gradient value between start and end
  1776. * @returns a new Color3 object
  1777. */
  1778. Color3.Lerp = function (start, end, amount) {
  1779. var r = start.r + ((end.r - start.r) * amount);
  1780. var g = start.g + ((end.g - start.g) * amount);
  1781. var b = start.b + ((end.b - start.b) * amount);
  1782. return new Color3(r, g, b);
  1783. };
  1784. /**
  1785. * Returns a Color3 value containing a red color
  1786. * @returns a new Color3 object
  1787. */
  1788. Color3.Red = function () { return new Color3(1, 0, 0); };
  1789. /**
  1790. * Returns a Color3 value containing a green color
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Green = function () { return new Color3(0, 1, 0); };
  1794. /**
  1795. * Returns a Color3 value containing a blue color
  1796. * @returns a new Color3 object
  1797. */
  1798. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1799. /**
  1800. * Returns a Color3 value containing a black color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Black = function () { return new Color3(0, 0, 0); };
  1804. /**
  1805. * Returns a Color3 value containing a white color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.White = function () { return new Color3(1, 1, 1); };
  1809. /**
  1810. * Returns a Color3 value containing a purple color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1814. /**
  1815. * Returns a Color3 value containing a magenta color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1819. /**
  1820. * Returns a Color3 value containing a yellow color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1824. /**
  1825. * Returns a Color3 value containing a gray color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1829. /**
  1830. * Returns a Color3 value containing a teal color
  1831. * @returns a new Color3 object
  1832. */
  1833. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1834. /**
  1835. * Returns a Color3 value containing a random color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1839. return Color3;
  1840. }());
  1841. BABYLON.Color3 = Color3;
  1842. /**
  1843. * Class used to hold a RBGA color
  1844. */
  1845. var Color4 = /** @class */ (function () {
  1846. /**
  1847. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1848. * @param r defines the red component (between 0 and 1, default is 0)
  1849. * @param g defines the green component (between 0 and 1, default is 0)
  1850. * @param b defines the blue component (between 0 and 1, default is 0)
  1851. * @param a defines the alpha component (between 0 and 1, default is 1)
  1852. */
  1853. function Color4(
  1854. /**
  1855. * Defines the red component (between 0 and 1, default is 0)
  1856. */
  1857. r,
  1858. /**
  1859. * Defines the green component (between 0 and 1, default is 0)
  1860. */
  1861. g,
  1862. /**
  1863. * Defines the blue component (between 0 and 1, default is 0)
  1864. */
  1865. b,
  1866. /**
  1867. * Defines the alpha component (between 0 and 1, default is 1)
  1868. */
  1869. a) {
  1870. if (r === void 0) { r = 0; }
  1871. if (g === void 0) { g = 0; }
  1872. if (b === void 0) { b = 0; }
  1873. if (a === void 0) { a = 1; }
  1874. this.r = r;
  1875. this.g = g;
  1876. this.b = b;
  1877. this.a = a;
  1878. }
  1879. // Operators
  1880. /**
  1881. * Adds in place the passed Color4 values to the current Color4 object
  1882. * @param right defines the second operand
  1883. * @returns the current updated Color4 object
  1884. */
  1885. Color4.prototype.addInPlace = function (right) {
  1886. this.r += right.r;
  1887. this.g += right.g;
  1888. this.b += right.b;
  1889. this.a += right.a;
  1890. return this;
  1891. };
  1892. /**
  1893. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1894. * @returns the new array
  1895. */
  1896. Color4.prototype.asArray = function () {
  1897. var result = new Array();
  1898. this.toArray(result, 0);
  1899. return result;
  1900. };
  1901. /**
  1902. * Stores from the starting index in the passed array the Color4 successive values
  1903. * @param array defines the array where to store the r,g,b components
  1904. * @param index defines an optional index in the target array to define where to start storing values
  1905. * @returns the current Color4 object
  1906. */
  1907. Color4.prototype.toArray = function (array, index) {
  1908. if (index === undefined) {
  1909. index = 0;
  1910. }
  1911. array[index] = this.r;
  1912. array[index + 1] = this.g;
  1913. array[index + 2] = this.b;
  1914. array[index + 3] = this.a;
  1915. return this;
  1916. };
  1917. /**
  1918. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1919. * @param right defines the second operand
  1920. * @returns a new Color4 object
  1921. */
  1922. Color4.prototype.add = function (right) {
  1923. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1924. };
  1925. /**
  1926. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1927. * @param right defines the second operand
  1928. * @returns a new Color4 object
  1929. */
  1930. Color4.prototype.subtract = function (right) {
  1931. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1932. };
  1933. /**
  1934. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1935. * @param right defines the second operand
  1936. * @param result defines the Color4 object where to store the result
  1937. * @returns the current Color4 object
  1938. */
  1939. Color4.prototype.subtractToRef = function (right, result) {
  1940. result.r = this.r - right.r;
  1941. result.g = this.g - right.g;
  1942. result.b = this.b - right.b;
  1943. result.a = this.a - right.a;
  1944. return this;
  1945. };
  1946. /**
  1947. * Creates a new Color4 with the current Color4 values multiplied by scale
  1948. * @param scale defines the scaling factor to apply
  1949. * @returns a new Color4 object
  1950. */
  1951. Color4.prototype.scale = function (scale) {
  1952. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1953. };
  1954. /**
  1955. * Multiplies the current Color4 values by scale and stores the result in "result"
  1956. * @param scale defines the scaling factor to apply
  1957. * @param result defines the Color4 object where to store the result
  1958. * @returns the current Color4.
  1959. */
  1960. Color4.prototype.scaleToRef = function (scale, result) {
  1961. result.r = this.r * scale;
  1962. result.g = this.g * scale;
  1963. result.b = this.b * scale;
  1964. result.a = this.a * scale;
  1965. return this;
  1966. };
  1967. /**
  1968. * Clamps the rgb values by the min and max values and stores the result into "result"
  1969. * @param min defines minimum clamping value (default is 0)
  1970. * @param max defines maximum clamping value (default is 1)
  1971. * @param result defines color to store the result into.
  1972. * @returns the cuurent Color4
  1973. */
  1974. Color4.prototype.clampToRef = function (min, max, result) {
  1975. if (min === void 0) { min = 0; }
  1976. if (max === void 0) { max = 1; }
  1977. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1978. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1979. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1980. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1981. return this;
  1982. };
  1983. /**
  1984. * Multipy an Color4 value by another and return a new Color4 object
  1985. * @param color defines the Color4 value to multiply by
  1986. * @returns a new Color4 object
  1987. */
  1988. Color4.prototype.multiply = function (color) {
  1989. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1990. };
  1991. /**
  1992. * Multipy a Color4 value by another and push the result in a reference value
  1993. * @param color defines the Color4 value to multiply by
  1994. * @param result defines the Color4 to fill the result in
  1995. * @returns the result Color4
  1996. */
  1997. Color4.prototype.multiplyToRef = function (color, result) {
  1998. result.r = this.r * color.r;
  1999. result.g = this.g * color.g;
  2000. result.b = this.b * color.b;
  2001. result.a = this.a * color.a;
  2002. return result;
  2003. };
  2004. /**
  2005. * Creates a string with the Color4 current values
  2006. * @returns the string representation of the Color4 object
  2007. */
  2008. Color4.prototype.toString = function () {
  2009. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2010. };
  2011. /**
  2012. * Returns the string "Color4"
  2013. * @returns "Color4"
  2014. */
  2015. Color4.prototype.getClassName = function () {
  2016. return "Color4";
  2017. };
  2018. /**
  2019. * Compute the Color4 hash code
  2020. * @returns an unique number that can be used to hash Color4 objects
  2021. */
  2022. Color4.prototype.getHashCode = function () {
  2023. var hash = this.r || 0;
  2024. hash = (hash * 397) ^ (this.g || 0);
  2025. hash = (hash * 397) ^ (this.b || 0);
  2026. hash = (hash * 397) ^ (this.a || 0);
  2027. return hash;
  2028. };
  2029. /**
  2030. * Creates a new Color4 copied from the current one
  2031. * @returns a new Color4 object
  2032. */
  2033. Color4.prototype.clone = function () {
  2034. return new Color4(this.r, this.g, this.b, this.a);
  2035. };
  2036. /**
  2037. * Copies the passed Color4 values into the current one
  2038. * @param source defines the source Color4 object
  2039. * @returns the current updated Color4 object
  2040. */
  2041. Color4.prototype.copyFrom = function (source) {
  2042. this.r = source.r;
  2043. this.g = source.g;
  2044. this.b = source.b;
  2045. this.a = source.a;
  2046. return this;
  2047. };
  2048. /**
  2049. * Copies the passed float values into the current one
  2050. * @param r defines the red component to read from
  2051. * @param g defines the green component to read from
  2052. * @param b defines the blue component to read from
  2053. * @param a defines the alpha component to read from
  2054. * @returns the current updated Color4 object
  2055. */
  2056. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2057. this.r = r;
  2058. this.g = g;
  2059. this.b = b;
  2060. this.a = a;
  2061. return this;
  2062. };
  2063. /**
  2064. * Copies the passed float values into the current one
  2065. * @param r defines the red component to read from
  2066. * @param g defines the green component to read from
  2067. * @param b defines the blue component to read from
  2068. * @param a defines the alpha component to read from
  2069. * @returns the current updated Color4 object
  2070. */
  2071. Color4.prototype.set = function (r, g, b, a) {
  2072. return this.copyFromFloats(r, g, b, a);
  2073. };
  2074. /**
  2075. * Compute the Color4 hexadecimal code as a string
  2076. * @returns a string containing the hexadecimal representation of the Color4 object
  2077. */
  2078. Color4.prototype.toHexString = function () {
  2079. var intR = (this.r * 255) | 0;
  2080. var intG = (this.g * 255) | 0;
  2081. var intB = (this.b * 255) | 0;
  2082. var intA = (this.a * 255) | 0;
  2083. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2084. };
  2085. /**
  2086. * Computes a new Color4 converted from the current one to linear space
  2087. * @returns a new Color4 object
  2088. */
  2089. Color4.prototype.toLinearSpace = function () {
  2090. var convertedColor = new Color4();
  2091. this.toLinearSpaceToRef(convertedColor);
  2092. return convertedColor;
  2093. };
  2094. /**
  2095. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2096. * @param convertedColor defines the Color4 object where to store the linear space version
  2097. * @returns the unmodified Color4
  2098. */
  2099. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2100. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2101. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2102. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2103. convertedColor.a = this.a;
  2104. return this;
  2105. };
  2106. /**
  2107. * Computes a new Color4 converted from the current one to gamma space
  2108. * @returns a new Color4 object
  2109. */
  2110. Color4.prototype.toGammaSpace = function () {
  2111. var convertedColor = new Color4();
  2112. this.toGammaSpaceToRef(convertedColor);
  2113. return convertedColor;
  2114. };
  2115. /**
  2116. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2117. * @param convertedColor defines the Color4 object where to store the gamma space version
  2118. * @returns the unmodified Color4
  2119. */
  2120. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2121. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2122. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2123. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2124. convertedColor.a = this.a;
  2125. return this;
  2126. };
  2127. // Statics
  2128. /**
  2129. * Creates a new Color4 from the string containing valid hexadecimal values
  2130. * @param hex defines a string containing valid hexadecimal values
  2131. * @returns a new Color4 object
  2132. */
  2133. Color4.FromHexString = function (hex) {
  2134. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2135. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  2136. return new Color4(0.0, 0.0, 0.0, 0.0);
  2137. }
  2138. var r = parseInt(hex.substring(1, 3), 16);
  2139. var g = parseInt(hex.substring(3, 5), 16);
  2140. var b = parseInt(hex.substring(5, 7), 16);
  2141. var a = parseInt(hex.substring(7, 9), 16);
  2142. return Color4.FromInts(r, g, b, a);
  2143. };
  2144. /**
  2145. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2146. * @param left defines the start value
  2147. * @param right defines the end value
  2148. * @param amount defines the gradient factor
  2149. * @returns a new Color4 object
  2150. */
  2151. Color4.Lerp = function (left, right, amount) {
  2152. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2153. Color4.LerpToRef(left, right, amount, result);
  2154. return result;
  2155. };
  2156. /**
  2157. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2158. * @param left defines the start value
  2159. * @param right defines the end value
  2160. * @param amount defines the gradient factor
  2161. * @param result defines the Color4 object where to store data
  2162. */
  2163. Color4.LerpToRef = function (left, right, amount, result) {
  2164. result.r = left.r + (right.r - left.r) * amount;
  2165. result.g = left.g + (right.g - left.g) * amount;
  2166. result.b = left.b + (right.b - left.b) * amount;
  2167. result.a = left.a + (right.a - left.a) * amount;
  2168. };
  2169. /**
  2170. * Creates a new Color4 from the starting index element of the passed array
  2171. * @param array defines the source array to read from
  2172. * @param offset defines the offset in the source array
  2173. * @returns a new Color4 object
  2174. */
  2175. Color4.FromArray = function (array, offset) {
  2176. if (offset === void 0) { offset = 0; }
  2177. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2178. };
  2179. /**
  2180. * Creates a new Color3 from integer values (< 256)
  2181. * @param r defines the red component to read from (value between 0 and 255)
  2182. * @param g defines the green component to read from (value between 0 and 255)
  2183. * @param b defines the blue component to read from (value between 0 and 255)
  2184. * @param a defines the alpha component to read from (value between 0 and 255)
  2185. * @returns a new Color3 object
  2186. */
  2187. Color4.FromInts = function (r, g, b, a) {
  2188. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2189. };
  2190. /**
  2191. * Check the content of a given array and convert it to an array containing RGBA data
  2192. * If the original array was already containing count * 4 values then it is returned directly
  2193. * @param colors defines the array to check
  2194. * @param count defines the number of RGBA data to expect
  2195. * @returns an array containing count * 4 values (RGBA)
  2196. */
  2197. Color4.CheckColors4 = function (colors, count) {
  2198. // Check if color3 was used
  2199. if (colors.length === count * 3) {
  2200. var colors4 = [];
  2201. for (var index = 0; index < colors.length; index += 3) {
  2202. var newIndex = (index / 3) * 4;
  2203. colors4[newIndex] = colors[index];
  2204. colors4[newIndex + 1] = colors[index + 1];
  2205. colors4[newIndex + 2] = colors[index + 2];
  2206. colors4[newIndex + 3] = 1.0;
  2207. }
  2208. return colors4;
  2209. }
  2210. return colors;
  2211. };
  2212. return Color4;
  2213. }());
  2214. BABYLON.Color4 = Color4;
  2215. var Vector2 = /** @class */ (function () {
  2216. /**
  2217. * Creates a new Vector2 from the passed x and y coordinates.
  2218. */
  2219. function Vector2(x, y) {
  2220. this.x = x;
  2221. this.y = y;
  2222. }
  2223. /**
  2224. * Returns a string with the Vector2 coordinates.
  2225. */
  2226. Vector2.prototype.toString = function () {
  2227. return "{X: " + this.x + " Y:" + this.y + "}";
  2228. };
  2229. /**
  2230. * Returns the string "Vector2"
  2231. */
  2232. Vector2.prototype.getClassName = function () {
  2233. return "Vector2";
  2234. };
  2235. /**
  2236. * Returns the Vector2 hash code as a number.
  2237. */
  2238. Vector2.prototype.getHashCode = function () {
  2239. var hash = this.x || 0;
  2240. hash = (hash * 397) ^ (this.y || 0);
  2241. return hash;
  2242. };
  2243. // Operators
  2244. /**
  2245. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2246. * Returns the Vector2.
  2247. */
  2248. Vector2.prototype.toArray = function (array, index) {
  2249. if (index === void 0) { index = 0; }
  2250. array[index] = this.x;
  2251. array[index + 1] = this.y;
  2252. return this;
  2253. };
  2254. /**
  2255. * Returns a new array with 2 elements : the Vector2 coordinates.
  2256. */
  2257. Vector2.prototype.asArray = function () {
  2258. var result = new Array();
  2259. this.toArray(result, 0);
  2260. return result;
  2261. };
  2262. /**
  2263. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2264. * Returns the updated Vector2.
  2265. */
  2266. Vector2.prototype.copyFrom = function (source) {
  2267. this.x = source.x;
  2268. this.y = source.y;
  2269. return this;
  2270. };
  2271. /**
  2272. * Sets the Vector2 coordinates with the passed floats.
  2273. * Returns the updated Vector2.
  2274. */
  2275. Vector2.prototype.copyFromFloats = function (x, y) {
  2276. this.x = x;
  2277. this.y = y;
  2278. return this;
  2279. };
  2280. /**
  2281. * Sets the Vector2 coordinates with the passed floats.
  2282. * Returns the updated Vector2.
  2283. */
  2284. Vector2.prototype.set = function (x, y) {
  2285. return this.copyFromFloats(x, y);
  2286. };
  2287. /**
  2288. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2289. */
  2290. Vector2.prototype.add = function (otherVector) {
  2291. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2292. };
  2293. /**
  2294. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2295. * Returns the Vector2.
  2296. */
  2297. Vector2.prototype.addToRef = function (otherVector, result) {
  2298. result.x = this.x + otherVector.x;
  2299. result.y = this.y + otherVector.y;
  2300. return this;
  2301. };
  2302. /**
  2303. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2304. * Returns the updated Vector2.
  2305. */
  2306. Vector2.prototype.addInPlace = function (otherVector) {
  2307. this.x += otherVector.x;
  2308. this.y += otherVector.y;
  2309. return this;
  2310. };
  2311. /**
  2312. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2313. */
  2314. Vector2.prototype.addVector3 = function (otherVector) {
  2315. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2316. };
  2317. /**
  2318. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2319. */
  2320. Vector2.prototype.subtract = function (otherVector) {
  2321. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2322. };
  2323. /**
  2324. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2325. * Returns the Vector2.
  2326. */
  2327. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2328. result.x = this.x - otherVector.x;
  2329. result.y = this.y - otherVector.y;
  2330. return this;
  2331. };
  2332. /**
  2333. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2334. * Returns the updated Vector2.
  2335. */
  2336. Vector2.prototype.subtractInPlace = function (otherVector) {
  2337. this.x -= otherVector.x;
  2338. this.y -= otherVector.y;
  2339. return this;
  2340. };
  2341. /**
  2342. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2343. * Returns the updated Vector2.
  2344. */
  2345. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2346. this.x *= otherVector.x;
  2347. this.y *= otherVector.y;
  2348. return this;
  2349. };
  2350. /**
  2351. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2352. */
  2353. Vector2.prototype.multiply = function (otherVector) {
  2354. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2355. };
  2356. /**
  2357. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2358. * Returns the Vector2.
  2359. */
  2360. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2361. result.x = this.x * otherVector.x;
  2362. result.y = this.y * otherVector.y;
  2363. return this;
  2364. };
  2365. /**
  2366. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2367. */
  2368. Vector2.prototype.multiplyByFloats = function (x, y) {
  2369. return new Vector2(this.x * x, this.y * y);
  2370. };
  2371. /**
  2372. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2373. */
  2374. Vector2.prototype.divide = function (otherVector) {
  2375. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2376. };
  2377. /**
  2378. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2379. * Returns the Vector2.
  2380. */
  2381. Vector2.prototype.divideToRef = function (otherVector, result) {
  2382. result.x = this.x / otherVector.x;
  2383. result.y = this.y / otherVector.y;
  2384. return this;
  2385. };
  2386. /**
  2387. * Divides the current Vector3 coordinates by the passed ones.
  2388. * Returns the updated Vector3.
  2389. */
  2390. Vector2.prototype.divideInPlace = function (otherVector) {
  2391. return this.divideToRef(otherVector, this);
  2392. };
  2393. /**
  2394. * Returns a new Vector2 with current Vector2 negated coordinates.
  2395. */
  2396. Vector2.prototype.negate = function () {
  2397. return new Vector2(-this.x, -this.y);
  2398. };
  2399. /**
  2400. * Multiply the Vector2 coordinates by scale.
  2401. * Returns the updated Vector2.
  2402. */
  2403. Vector2.prototype.scaleInPlace = function (scale) {
  2404. this.x *= scale;
  2405. this.y *= scale;
  2406. return this;
  2407. };
  2408. /**
  2409. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2410. */
  2411. Vector2.prototype.scale = function (scale) {
  2412. return new Vector2(this.x * scale, this.y * scale);
  2413. };
  2414. /**
  2415. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2416. */
  2417. Vector2.prototype.equals = function (otherVector) {
  2418. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2419. };
  2420. /**
  2421. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2422. */
  2423. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2424. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2425. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2426. };
  2427. // Properties
  2428. /**
  2429. * Returns the vector length (float).
  2430. */
  2431. Vector2.prototype.length = function () {
  2432. return Math.sqrt(this.x * this.x + this.y * this.y);
  2433. };
  2434. /**
  2435. * Returns the vector squared length (float);
  2436. */
  2437. Vector2.prototype.lengthSquared = function () {
  2438. return (this.x * this.x + this.y * this.y);
  2439. };
  2440. // Methods
  2441. /**
  2442. * Normalize the vector.
  2443. * Returns the updated Vector2.
  2444. */
  2445. Vector2.prototype.normalize = function () {
  2446. var len = this.length();
  2447. if (len === 0)
  2448. return this;
  2449. var num = 1.0 / len;
  2450. this.x *= num;
  2451. this.y *= num;
  2452. return this;
  2453. };
  2454. /**
  2455. * Returns a new Vector2 copied from the Vector2.
  2456. */
  2457. Vector2.prototype.clone = function () {
  2458. return new Vector2(this.x, this.y);
  2459. };
  2460. // Statics
  2461. /**
  2462. * Returns a new Vector2(0, 0)
  2463. */
  2464. Vector2.Zero = function () {
  2465. return new Vector2(0, 0);
  2466. };
  2467. /**
  2468. * Returns a new Vector2(1, 1)
  2469. */
  2470. Vector2.One = function () {
  2471. return new Vector2(1, 1);
  2472. };
  2473. /**
  2474. * Returns a new Vector2 set from the passed index element of the passed array.
  2475. */
  2476. Vector2.FromArray = function (array, offset) {
  2477. if (offset === void 0) { offset = 0; }
  2478. return new Vector2(array[offset], array[offset + 1]);
  2479. };
  2480. /**
  2481. * Sets "result" from the passed index element of the passed array.
  2482. */
  2483. Vector2.FromArrayToRef = function (array, offset, result) {
  2484. result.x = array[offset];
  2485. result.y = array[offset + 1];
  2486. };
  2487. /**
  2488. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2489. */
  2490. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2491. var squared = amount * amount;
  2492. var cubed = amount * squared;
  2493. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2494. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2495. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2496. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2497. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2498. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2499. return new Vector2(x, y);
  2500. };
  2501. /**
  2502. * 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".
  2503. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2504. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2505. */
  2506. Vector2.Clamp = function (value, min, max) {
  2507. var x = value.x;
  2508. x = (x > max.x) ? max.x : x;
  2509. x = (x < min.x) ? min.x : x;
  2510. var y = value.y;
  2511. y = (y > max.y) ? max.y : y;
  2512. y = (y < min.y) ? min.y : y;
  2513. return new Vector2(x, y);
  2514. };
  2515. /**
  2516. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2517. */
  2518. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2519. var squared = amount * amount;
  2520. var cubed = amount * squared;
  2521. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2522. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2523. var part3 = (cubed - (2.0 * squared)) + amount;
  2524. var part4 = cubed - squared;
  2525. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2526. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2527. return new Vector2(x, y);
  2528. };
  2529. /**
  2530. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2531. */
  2532. Vector2.Lerp = function (start, end, amount) {
  2533. var x = start.x + ((end.x - start.x) * amount);
  2534. var y = start.y + ((end.y - start.y) * amount);
  2535. return new Vector2(x, y);
  2536. };
  2537. /**
  2538. * Returns the dot product (float) of the vector "left" and the vector "right".
  2539. */
  2540. Vector2.Dot = function (left, right) {
  2541. return left.x * right.x + left.y * right.y;
  2542. };
  2543. /**
  2544. * Returns a new Vector2 equal to the normalized passed vector.
  2545. */
  2546. Vector2.Normalize = function (vector) {
  2547. var newVector = vector.clone();
  2548. newVector.normalize();
  2549. return newVector;
  2550. };
  2551. /**
  2552. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2553. */
  2554. Vector2.Minimize = function (left, right) {
  2555. var x = (left.x < right.x) ? left.x : right.x;
  2556. var y = (left.y < right.y) ? left.y : right.y;
  2557. return new Vector2(x, y);
  2558. };
  2559. /**
  2560. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2561. */
  2562. Vector2.Maximize = function (left, right) {
  2563. var x = (left.x > right.x) ? left.x : right.x;
  2564. var y = (left.y > right.y) ? left.y : right.y;
  2565. return new Vector2(x, y);
  2566. };
  2567. /**
  2568. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2569. */
  2570. Vector2.Transform = function (vector, transformation) {
  2571. var r = Vector2.Zero();
  2572. Vector2.TransformToRef(vector, transformation, r);
  2573. return r;
  2574. };
  2575. /**
  2576. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2577. */
  2578. Vector2.TransformToRef = function (vector, transformation, result) {
  2579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2581. result.x = x;
  2582. result.y = y;
  2583. };
  2584. /**
  2585. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2586. */
  2587. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2588. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2589. var sign = a < 0 ? -1 : 1;
  2590. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2591. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2592. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2593. };
  2594. /**
  2595. * Returns the distance (float) between the vectors "value1" and "value2".
  2596. */
  2597. Vector2.Distance = function (value1, value2) {
  2598. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2599. };
  2600. /**
  2601. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2602. */
  2603. Vector2.DistanceSquared = function (value1, value2) {
  2604. var x = value1.x - value2.x;
  2605. var y = value1.y - value2.y;
  2606. return (x * x) + (y * y);
  2607. };
  2608. /**
  2609. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2610. */
  2611. Vector2.Center = function (value1, value2) {
  2612. var center = value1.add(value2);
  2613. center.scaleInPlace(0.5);
  2614. return center;
  2615. };
  2616. /**
  2617. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2618. */
  2619. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2620. var l2 = Vector2.DistanceSquared(segA, segB);
  2621. if (l2 === 0.0) {
  2622. return Vector2.Distance(p, segA);
  2623. }
  2624. var v = segB.subtract(segA);
  2625. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2626. var proj = segA.add(v.multiplyByFloats(t, t));
  2627. return Vector2.Distance(p, proj);
  2628. };
  2629. return Vector2;
  2630. }());
  2631. BABYLON.Vector2 = Vector2;
  2632. /**
  2633. * Classed used to store (x,y,z) vector representation
  2634. * A Vector3 is the main object used in 3D geometry
  2635. * It can represent etiher the coordinates of a point the space, either a direction
  2636. * Reminder: Babylon.js uses a left handed forward facing system
  2637. */
  2638. var Vector3 = /** @class */ (function () {
  2639. /**
  2640. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2641. * @param x defines the first coordinates (on X axis)
  2642. * @param y defines the second coordinates (on Y axis)
  2643. * @param z defines the third coordinates (on Z axis)
  2644. */
  2645. function Vector3(
  2646. /**
  2647. * Defines the first coordinates (on X axis)
  2648. */
  2649. x,
  2650. /**
  2651. * Defines the second coordinates (on Y axis)
  2652. */
  2653. y,
  2654. /**
  2655. * Defines the third coordinates (on Z axis)
  2656. */
  2657. z) {
  2658. this.x = x;
  2659. this.y = y;
  2660. this.z = z;
  2661. }
  2662. /**
  2663. * Creates a string representation of the Vector3
  2664. * @returns a string with the Vector3 coordinates.
  2665. */
  2666. Vector3.prototype.toString = function () {
  2667. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2668. };
  2669. /**
  2670. * Gets the class name
  2671. * @returns the string "Vector3"
  2672. */
  2673. Vector3.prototype.getClassName = function () {
  2674. return "Vector3";
  2675. };
  2676. /**
  2677. * Creates the Vector3 hash code
  2678. * @returns a number which tends to be unique between Vector3 instances
  2679. */
  2680. Vector3.prototype.getHashCode = function () {
  2681. var hash = this.x || 0;
  2682. hash = (hash * 397) ^ (this.y || 0);
  2683. hash = (hash * 397) ^ (this.z || 0);
  2684. return hash;
  2685. };
  2686. // Operators
  2687. /**
  2688. * Creates an array containing three elements : the coordinates of the Vector3
  2689. * @returns a new array of numbers
  2690. */
  2691. Vector3.prototype.asArray = function () {
  2692. var result = [];
  2693. this.toArray(result, 0);
  2694. return result;
  2695. };
  2696. /**
  2697. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2698. * @param array defines the destination array
  2699. * @param index defines the offset in the destination array
  2700. * @returns the current Vector3
  2701. */
  2702. Vector3.prototype.toArray = function (array, index) {
  2703. if (index === void 0) { index = 0; }
  2704. array[index] = this.x;
  2705. array[index + 1] = this.y;
  2706. array[index + 2] = this.z;
  2707. return this;
  2708. };
  2709. /**
  2710. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2711. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2712. */
  2713. Vector3.prototype.toQuaternion = function () {
  2714. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2715. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2716. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2717. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2718. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2719. var cosy = Math.cos(this.y * 0.5);
  2720. var siny = Math.sin(this.y * 0.5);
  2721. result.x = coszMinusx * siny;
  2722. result.y = -sinzMinusx * siny;
  2723. result.z = sinxPlusz * cosy;
  2724. result.w = cosxPlusz * cosy;
  2725. return result;
  2726. };
  2727. /**
  2728. * Adds the passed vector to the current Vector3
  2729. * @param otherVector defines the second operand
  2730. * @returns the current updated Vector3
  2731. */
  2732. Vector3.prototype.addInPlace = function (otherVector) {
  2733. this.x += otherVector.x;
  2734. this.y += otherVector.y;
  2735. this.z += otherVector.z;
  2736. return this;
  2737. };
  2738. /**
  2739. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2740. * @param otherVector defines the second operand
  2741. * @returns the resulting Vector3
  2742. */
  2743. Vector3.prototype.add = function (otherVector) {
  2744. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2745. };
  2746. /**
  2747. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2748. * @param otherVector defines the second operand
  2749. * @param result defines the Vector3 object where to store the result
  2750. * @returns the current Vector3
  2751. */
  2752. Vector3.prototype.addToRef = function (otherVector, result) {
  2753. result.x = this.x + otherVector.x;
  2754. result.y = this.y + otherVector.y;
  2755. result.z = this.z + otherVector.z;
  2756. return this;
  2757. };
  2758. /**
  2759. * Subtract the passed vector from the current Vector3
  2760. * @param otherVector defines the second operand
  2761. * @returns the current updated Vector3
  2762. */
  2763. Vector3.prototype.subtractInPlace = function (otherVector) {
  2764. this.x -= otherVector.x;
  2765. this.y -= otherVector.y;
  2766. this.z -= otherVector.z;
  2767. return this;
  2768. };
  2769. /**
  2770. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2771. * @param otherVector defines the second operand
  2772. * @returns the resulting Vector3
  2773. */
  2774. Vector3.prototype.subtract = function (otherVector) {
  2775. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2776. };
  2777. /**
  2778. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2779. * @param otherVector defines the second operand
  2780. * @param result defines the Vector3 object where to store the result
  2781. * @returns the current Vector3
  2782. */
  2783. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2784. result.x = this.x - otherVector.x;
  2785. result.y = this.y - otherVector.y;
  2786. result.z = this.z - otherVector.z;
  2787. return this;
  2788. };
  2789. /**
  2790. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2791. * @param x defines the x coordinate of the operand
  2792. * @param y defines the y coordinate of the operand
  2793. * @param z defines the z coordinate of the operand
  2794. * @returns the resulting Vector3
  2795. */
  2796. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2797. return new Vector3(this.x - x, this.y - y, this.z - z);
  2798. };
  2799. /**
  2800. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2801. * @param x defines the x coordinate of the operand
  2802. * @param y defines the y coordinate of the operand
  2803. * @param z defines the z coordinate of the operand
  2804. * @param result defines the Vector3 object where to store the result
  2805. * @returns the current Vector3
  2806. */
  2807. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2808. result.x = this.x - x;
  2809. result.y = this.y - y;
  2810. result.z = this.z - z;
  2811. return this;
  2812. };
  2813. /**
  2814. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2815. * @returns a new Vector3
  2816. */
  2817. Vector3.prototype.negate = function () {
  2818. return new Vector3(-this.x, -this.y, -this.z);
  2819. };
  2820. /**
  2821. * Multiplies the Vector3 coordinates by the float "scale"
  2822. * @param scale defines the multiplier factor
  2823. * @returns the current updated Vector3
  2824. */
  2825. Vector3.prototype.scaleInPlace = function (scale) {
  2826. this.x *= scale;
  2827. this.y *= scale;
  2828. this.z *= scale;
  2829. return this;
  2830. };
  2831. /**
  2832. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2833. * @param scale defines the multiplier factor
  2834. * @returns a new Vector3
  2835. */
  2836. Vector3.prototype.scale = function (scale) {
  2837. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2838. };
  2839. /**
  2840. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2841. * @param scale defines the multiplier factor
  2842. * @param result defines the Vector3 object where to store the result
  2843. * @returns the current Vector3
  2844. */
  2845. Vector3.prototype.scaleToRef = function (scale, result) {
  2846. result.x = this.x * scale;
  2847. result.y = this.y * scale;
  2848. result.z = this.z * scale;
  2849. return this;
  2850. };
  2851. /**
  2852. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2853. * @param otherVector defines the second operand
  2854. * @returns true if both vectors are equals
  2855. */
  2856. Vector3.prototype.equals = function (otherVector) {
  2857. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2858. };
  2859. /**
  2860. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2861. * @param otherVector defines the second operand
  2862. * @param epsilon defines the minimal distance to define values as equals
  2863. * @returns true if both vectors are distant less than epsilon
  2864. */
  2865. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2866. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2867. 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);
  2868. };
  2869. /**
  2870. * Returns true if the current Vector3 coordinates equals the passed floats
  2871. * @param x defines the x coordinate of the operand
  2872. * @param y defines the y coordinate of the operand
  2873. * @param z defines the z coordinate of the operand
  2874. * @returns true if both vectors are equals
  2875. */
  2876. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2877. return this.x === x && this.y === y && this.z === z;
  2878. };
  2879. /**
  2880. * Multiplies the current Vector3 coordinates by the passed ones
  2881. * @param otherVector defines the second operand
  2882. * @returns the current updated Vector3
  2883. */
  2884. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2885. this.x *= otherVector.x;
  2886. this.y *= otherVector.y;
  2887. this.z *= otherVector.z;
  2888. return this;
  2889. };
  2890. /**
  2891. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2892. * @param otherVector defines the second operand
  2893. * @returns the new Vector3
  2894. */
  2895. Vector3.prototype.multiply = function (otherVector) {
  2896. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2897. };
  2898. /**
  2899. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2900. * @param otherVector defines the second operand
  2901. * @param result defines the Vector3 object where to store the result
  2902. * @returns the current Vector3
  2903. */
  2904. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2905. result.x = this.x * otherVector.x;
  2906. result.y = this.y * otherVector.y;
  2907. result.z = this.z * otherVector.z;
  2908. return this;
  2909. };
  2910. /**
  2911. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2912. * @param x defines the x coordinate of the operand
  2913. * @param y defines the y coordinate of the operand
  2914. * @param z defines the z coordinate of the operand
  2915. * @returns the new Vector3
  2916. */
  2917. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2918. return new Vector3(this.x * x, this.y * y, this.z * z);
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2922. * @param otherVector defines the second operand
  2923. * @returns the new Vector3
  2924. */
  2925. Vector3.prototype.divide = function (otherVector) {
  2926. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2927. };
  2928. /**
  2929. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2930. * @param otherVector defines the second operand
  2931. * @param result defines the Vector3 object where to store the result
  2932. * @returns the current Vector3
  2933. */
  2934. Vector3.prototype.divideToRef = function (otherVector, result) {
  2935. result.x = this.x / otherVector.x;
  2936. result.y = this.y / otherVector.y;
  2937. result.z = this.z / otherVector.z;
  2938. return this;
  2939. };
  2940. /**
  2941. * Divides the current Vector3 coordinates by the passed ones.
  2942. * @param otherVector defines the second operand
  2943. * @returns the current updated Vector3
  2944. */
  2945. Vector3.prototype.divideInPlace = function (otherVector) {
  2946. return this.divideToRef(otherVector, this);
  2947. };
  2948. /**
  2949. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2950. * @param other defines the second operand
  2951. * @returns the current updated Vector3
  2952. */
  2953. Vector3.prototype.minimizeInPlace = function (other) {
  2954. if (other.x < this.x)
  2955. this.x = other.x;
  2956. if (other.y < this.y)
  2957. this.y = other.y;
  2958. if (other.z < this.z)
  2959. this.z = other.z;
  2960. return this;
  2961. };
  2962. /**
  2963. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2964. * @param other defines the second operand
  2965. * @returns the current updated Vector3
  2966. */
  2967. Vector3.prototype.maximizeInPlace = function (other) {
  2968. if (other.x > this.x)
  2969. this.x = other.x;
  2970. if (other.y > this.y)
  2971. this.y = other.y;
  2972. if (other.z > this.z)
  2973. this.z = other.z;
  2974. return this;
  2975. };
  2976. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2977. /**
  2978. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2979. */
  2980. get: function () {
  2981. var absX = Math.abs(this.x);
  2982. var absY = Math.abs(this.y);
  2983. if (absX !== absY) {
  2984. return true;
  2985. }
  2986. var absZ = Math.abs(this.z);
  2987. if (absX !== absZ) {
  2988. return true;
  2989. }
  2990. if (absY !== absZ) {
  2991. return true;
  2992. }
  2993. return false;
  2994. },
  2995. enumerable: true,
  2996. configurable: true
  2997. });
  2998. // Properties
  2999. /**
  3000. * Gets the length of the Vector3
  3001. * @returns the length of the Vecto3
  3002. */
  3003. Vector3.prototype.length = function () {
  3004. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3005. };
  3006. /**
  3007. * Gets the squared length of the Vector3
  3008. * @returns squared length of the Vector3
  3009. */
  3010. Vector3.prototype.lengthSquared = function () {
  3011. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3012. };
  3013. /**
  3014. * Normalize the current Vector3.
  3015. * Please note that this is an in place operation.
  3016. * @returns the current updated Vector3
  3017. */
  3018. Vector3.prototype.normalize = function () {
  3019. var len = this.length();
  3020. if (len === 0 || len === 1.0)
  3021. return this;
  3022. var num = 1.0 / len;
  3023. this.x *= num;
  3024. this.y *= num;
  3025. this.z *= num;
  3026. return this;
  3027. };
  3028. /**
  3029. * Normalize the current Vector3 to a new vector
  3030. * @returns the new Vector3
  3031. */
  3032. Vector3.prototype.normalizeToNew = function () {
  3033. var normalized = new Vector3(0, 0, 0);
  3034. this.normalizeToRef(normalized);
  3035. return normalized;
  3036. };
  3037. /**
  3038. * Normalize the current Vector3 to the reference
  3039. * @param reference define the Vector3 to update
  3040. * @returns the updated Vector3
  3041. */
  3042. Vector3.prototype.normalizeToRef = function (reference) {
  3043. var len = this.length();
  3044. if (len === 0 || len === 1.0) {
  3045. reference.set(this.x, this.y, this.z);
  3046. return reference;
  3047. }
  3048. var scale = 1.0 / len;
  3049. this.scaleToRef(scale, reference);
  3050. return reference;
  3051. };
  3052. /**
  3053. * Creates a new Vector3 copied from the current Vector3
  3054. * @returns the new Vector3
  3055. */
  3056. Vector3.prototype.clone = function () {
  3057. return new Vector3(this.x, this.y, this.z);
  3058. };
  3059. /**
  3060. * Copies the passed vector coordinates to the current Vector3 ones
  3061. * @param source defines the source Vector3
  3062. * @returns the current updated Vector3
  3063. */
  3064. Vector3.prototype.copyFrom = function (source) {
  3065. this.x = source.x;
  3066. this.y = source.y;
  3067. this.z = source.z;
  3068. return this;
  3069. };
  3070. /**
  3071. * Copies the passed floats to the current Vector3 coordinates
  3072. * @param x defines the x coordinate of the operand
  3073. * @param y defines the y coordinate of the operand
  3074. * @param z defines the z coordinate of the operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3078. this.x = x;
  3079. this.y = y;
  3080. this.z = z;
  3081. return this;
  3082. };
  3083. /**
  3084. * Copies the passed floats to the current Vector3 coordinates
  3085. * @param x defines the x coordinate of the operand
  3086. * @param y defines the y coordinate of the operand
  3087. * @param z defines the z coordinate of the operand
  3088. * @returns the current updated Vector3
  3089. */
  3090. Vector3.prototype.set = function (x, y, z) {
  3091. return this.copyFromFloats(x, y, z);
  3092. };
  3093. // Statics
  3094. /**
  3095. * Get the clip factor between two vectors
  3096. * @param vector0 defines the first operand
  3097. * @param vector1 defines the second operand
  3098. * @param axis defines the axis to use
  3099. * @param size defines the size along the axis
  3100. * @returns the clip factor
  3101. */
  3102. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3103. var d0 = Vector3.Dot(vector0, axis) - size;
  3104. var d1 = Vector3.Dot(vector1, axis) - size;
  3105. var s = d0 / (d0 - d1);
  3106. return s;
  3107. };
  3108. /**
  3109. * Get angle between two vectors
  3110. * @param vector0 angle between vector0 and vector1
  3111. * @param vector1 angle between vector0 and vector1
  3112. * @param normal direction of the normal
  3113. * @return the angle between vector0 and vector1
  3114. */
  3115. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3116. var v0 = vector0.clone().normalize();
  3117. var v1 = vector1.clone().normalize();
  3118. var dot = Vector3.Dot(v0, v1);
  3119. var n = Vector3.Cross(v0, v1);
  3120. if (Vector3.Dot(n, normal) > 0) {
  3121. return Math.acos(dot);
  3122. }
  3123. return -Math.acos(dot);
  3124. };
  3125. /**
  3126. * Returns a new Vector3 set from the index "offset" of the passed array
  3127. * @param array defines the source array
  3128. * @param offset defines the offset in the source array
  3129. * @returns the new Vector3
  3130. */
  3131. Vector3.FromArray = function (array, offset) {
  3132. if (!offset) {
  3133. offset = 0;
  3134. }
  3135. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3136. };
  3137. /**
  3138. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3139. * This function is deprecated. Use FromArray instead
  3140. * @param array defines the source array
  3141. * @param offset defines the offset in the source array
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.FromFloatArray = function (array, offset) {
  3145. return Vector3.FromArray(array, offset);
  3146. };
  3147. /**
  3148. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3149. * @param array defines the source array
  3150. * @param offset defines the offset in the source array
  3151. * @param result defines the Vector3 where to store the result
  3152. */
  3153. Vector3.FromArrayToRef = function (array, offset, result) {
  3154. result.x = array[offset];
  3155. result.y = array[offset + 1];
  3156. result.z = array[offset + 2];
  3157. };
  3158. /**
  3159. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3160. * This function is deprecated. Use FromArrayToRef instead.
  3161. * @param array defines the source array
  3162. * @param offset defines the offset in the source array
  3163. * @param result defines the Vector3 where to store the result
  3164. */
  3165. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3166. return Vector3.FromArrayToRef(array, offset, result);
  3167. };
  3168. /**
  3169. * Sets the passed vector "result" with the passed floats.
  3170. * @param x defines the x coordinate of the source
  3171. * @param y defines the y coordinate of the source
  3172. * @param z defines the z coordinate of the source
  3173. * @param result defines the Vector3 where to store the result
  3174. */
  3175. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3176. result.x = x;
  3177. result.y = y;
  3178. result.z = z;
  3179. };
  3180. /**
  3181. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3182. * @returns a new empty Vector3
  3183. */
  3184. Vector3.Zero = function () {
  3185. return new Vector3(0.0, 0.0, 0.0);
  3186. };
  3187. /**
  3188. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3189. * @returns a new unit Vector3
  3190. */
  3191. Vector3.One = function () {
  3192. return new Vector3(1.0, 1.0, 1.0);
  3193. };
  3194. /**
  3195. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3196. * @returns a new up Vector3
  3197. */
  3198. Vector3.Up = function () {
  3199. return new Vector3(0.0, 1.0, 0.0);
  3200. };
  3201. /**
  3202. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3203. * @returns a new forward Vector3
  3204. */
  3205. Vector3.Forward = function () {
  3206. return new Vector3(0.0, 0.0, 1.0);
  3207. };
  3208. /**
  3209. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3210. * @returns a new right Vector3
  3211. */
  3212. Vector3.Right = function () {
  3213. return new Vector3(1.0, 0.0, 0.0);
  3214. };
  3215. /**
  3216. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3217. * @returns a new left Vector3
  3218. */
  3219. Vector3.Left = function () {
  3220. return new Vector3(-1.0, 0.0, 0.0);
  3221. };
  3222. /**
  3223. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3224. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3225. * @param vector defines the Vector3 to transform
  3226. * @param transformation defines the transformation matrix
  3227. * @returns the transformed Vector3
  3228. */
  3229. Vector3.TransformCoordinates = function (vector, transformation) {
  3230. var result = Vector3.Zero();
  3231. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3232. return result;
  3233. };
  3234. /**
  3235. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3236. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3237. * @param vector defines the Vector3 to transform
  3238. * @param transformation defines the transformation matrix
  3239. * @param result defines the Vector3 where to store the result
  3240. */
  3241. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3242. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3243. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3244. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3245. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3246. result.x = x / w;
  3247. result.y = y / w;
  3248. result.z = z / w;
  3249. };
  3250. /**
  3251. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3252. * This method computes tranformed coordinates only, not transformed direction vectors
  3253. * @param x define the x coordinate of the source vector
  3254. * @param y define the y coordinate of the source vector
  3255. * @param z define the z coordinate of the source vector
  3256. * @param transformation defines the transformation matrix
  3257. * @param result defines the Vector3 where to store the result
  3258. */
  3259. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3260. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3261. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3262. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3263. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3264. result.x = rx / rw;
  3265. result.y = ry / rw;
  3266. result.z = rz / rw;
  3267. };
  3268. /**
  3269. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3270. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3271. * @param vector defines the Vector3 to transform
  3272. * @param transformation defines the transformation matrix
  3273. * @returns the new Vector3
  3274. */
  3275. Vector3.TransformNormal = function (vector, transformation) {
  3276. var result = Vector3.Zero();
  3277. Vector3.TransformNormalToRef(vector, transformation, result);
  3278. return result;
  3279. };
  3280. /**
  3281. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3282. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3283. * @param vector defines the Vector3 to transform
  3284. * @param transformation defines the transformation matrix
  3285. * @param result defines the Vector3 where to store the result
  3286. */
  3287. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3288. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3289. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3290. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3291. result.x = x;
  3292. result.y = y;
  3293. result.z = z;
  3294. };
  3295. /**
  3296. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3297. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3298. * @param x define the x coordinate of the source vector
  3299. * @param y define the y coordinate of the source vector
  3300. * @param z define the z coordinate of the source vector
  3301. * @param transformation defines the transformation matrix
  3302. * @param result defines the Vector3 where to store the result
  3303. */
  3304. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3305. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3306. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3307. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3308. };
  3309. /**
  3310. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3311. * @param value1 defines the first control point
  3312. * @param value2 defines the second control point
  3313. * @param value3 defines the third control point
  3314. * @param value4 defines the fourth control point
  3315. * @param amount defines the amount on the spline to use
  3316. * @returns the new Vector3
  3317. */
  3318. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3319. var squared = amount * amount;
  3320. var cubed = amount * squared;
  3321. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3322. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3323. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3324. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3325. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3326. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3327. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3328. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3329. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3330. return new Vector3(x, y, z);
  3331. };
  3332. /**
  3333. * 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"
  3334. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3335. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3336. * @param value defines the current value
  3337. * @param min defines the lower range value
  3338. * @param max defines the upper range value
  3339. * @returns the new Vector3
  3340. */
  3341. Vector3.Clamp = function (value, min, max) {
  3342. var x = value.x;
  3343. x = (x > max.x) ? max.x : x;
  3344. x = (x < min.x) ? min.x : x;
  3345. var y = value.y;
  3346. y = (y > max.y) ? max.y : y;
  3347. y = (y < min.y) ? min.y : y;
  3348. var z = value.z;
  3349. z = (z > max.z) ? max.z : z;
  3350. z = (z < min.z) ? min.z : z;
  3351. return new Vector3(x, y, z);
  3352. };
  3353. /**
  3354. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3355. * @param value1 defines the first control point
  3356. * @param tangent1 defines the first tangent vector
  3357. * @param value2 defines the second control point
  3358. * @param tangent2 defines the second tangent vector
  3359. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3360. * @returns the new Vector3
  3361. */
  3362. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3363. var squared = amount * amount;
  3364. var cubed = amount * squared;
  3365. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3366. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3367. var part3 = (cubed - (2.0 * squared)) + amount;
  3368. var part4 = cubed - squared;
  3369. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3370. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3371. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3372. return new Vector3(x, y, z);
  3373. };
  3374. /**
  3375. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3376. * @param start defines the start value
  3377. * @param end defines the end value
  3378. * @param amount max defines amount between both (between 0 and 1)
  3379. * @returns the new Vector3
  3380. */
  3381. Vector3.Lerp = function (start, end, amount) {
  3382. var result = new Vector3(0, 0, 0);
  3383. Vector3.LerpToRef(start, end, amount, result);
  3384. return result;
  3385. };
  3386. /**
  3387. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3388. * @param start defines the start value
  3389. * @param end defines the end value
  3390. * @param amount max defines amount between both (between 0 and 1)
  3391. * @param result defines the Vector3 where to store the result
  3392. */
  3393. Vector3.LerpToRef = function (start, end, amount, result) {
  3394. result.x = start.x + ((end.x - start.x) * amount);
  3395. result.y = start.y + ((end.y - start.y) * amount);
  3396. result.z = start.z + ((end.z - start.z) * amount);
  3397. };
  3398. /**
  3399. * Returns the dot product (float) between the vectors "left" and "right"
  3400. * @param left defines the left operand
  3401. * @param right defines the right operand
  3402. * @returns the dot product
  3403. */
  3404. Vector3.Dot = function (left, right) {
  3405. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3409. * The cross product is then orthogonal to both "left" and "right"
  3410. * @param left defines the left operand
  3411. * @param right defines the right operand
  3412. * @returns the cross product
  3413. */
  3414. Vector3.Cross = function (left, right) {
  3415. var result = Vector3.Zero();
  3416. Vector3.CrossToRef(left, right, result);
  3417. return result;
  3418. };
  3419. /**
  3420. * Sets the passed vector "result" with the cross product of "left" and "right"
  3421. * The cross product is then orthogonal to both "left" and "right"
  3422. * @param left defines the left operand
  3423. * @param right defines the right operand
  3424. * @param result defines the Vector3 where to store the result
  3425. */
  3426. Vector3.CrossToRef = function (left, right, result) {
  3427. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3428. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3429. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3430. result.copyFrom(MathTmp.Vector3[0]);
  3431. };
  3432. /**
  3433. * Returns a new Vector3 as the normalization of the passed vector
  3434. * @param vector defines the Vector3 to normalize
  3435. * @returns the new Vector3
  3436. */
  3437. Vector3.Normalize = function (vector) {
  3438. var result = Vector3.Zero();
  3439. Vector3.NormalizeToRef(vector, result);
  3440. return result;
  3441. };
  3442. /**
  3443. * Sets the passed vector "result" with the normalization of the passed first vector
  3444. * @param vector defines the Vector3 to normalize
  3445. * @param result defines the Vector3 where to store the result
  3446. */
  3447. Vector3.NormalizeToRef = function (vector, result) {
  3448. result.copyFrom(vector);
  3449. result.normalize();
  3450. };
  3451. /**
  3452. * Project a Vector3 onto screen space
  3453. * @param vector defines the Vector3 to project
  3454. * @param world defines the world matrix to use
  3455. * @param transform defines the transform (view x projection) matrix to use
  3456. * @param viewport defines the screen viewport to use
  3457. * @returns the new Vector3
  3458. */
  3459. Vector3.Project = function (vector, world, transform, viewport) {
  3460. var cw = viewport.width;
  3461. var ch = viewport.height;
  3462. var cx = viewport.x;
  3463. var cy = viewport.y;
  3464. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3465. 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);
  3466. var matrix = MathTmp.Matrix[0];
  3467. world.multiplyToRef(transform, matrix);
  3468. matrix.multiplyToRef(viewportMatrix, matrix);
  3469. return Vector3.TransformCoordinates(vector, matrix);
  3470. };
  3471. /**
  3472. * Unproject from screen space to object space
  3473. * @param source defines the screen space Vector3 to use
  3474. * @param viewportWidth defines the current width of the viewport
  3475. * @param viewportHeight defines the current height of the viewport
  3476. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3477. * @param transform defines the transform (view x projection) matrix to use
  3478. * @returns the new Vector3
  3479. */
  3480. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3481. var matrix = MathTmp.Matrix[0];
  3482. world.multiplyToRef(transform, matrix);
  3483. matrix.invert();
  3484. source.x = source.x / viewportWidth * 2 - 1;
  3485. source.y = -(source.y / viewportHeight * 2 - 1);
  3486. var vector = Vector3.TransformCoordinates(source, matrix);
  3487. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3488. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3489. vector = vector.scale(1.0 / num);
  3490. }
  3491. return vector;
  3492. };
  3493. /**
  3494. * Unproject from screen space to object space
  3495. * @param source defines the screen space Vector3 to use
  3496. * @param viewportWidth defines the current width of the viewport
  3497. * @param viewportHeight defines the current height of the viewport
  3498. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3499. * @param view defines the view matrix to use
  3500. * @param projection defines the projection matrix to use
  3501. * @returns the new Vector3
  3502. */
  3503. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3504. var result = Vector3.Zero();
  3505. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3506. return result;
  3507. };
  3508. /**
  3509. * Unproject from screen space to object space
  3510. * @param source defines the screen space Vector3 to use
  3511. * @param viewportWidth defines the current width of the viewport
  3512. * @param viewportHeight defines the current height of the viewport
  3513. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3514. * @param view defines the view matrix to use
  3515. * @param projection defines the projection matrix to use
  3516. * @param result defines the Vector3 where to store the result
  3517. */
  3518. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3519. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3520. };
  3521. /**
  3522. * Unproject from screen space to object space
  3523. * @param sourceX defines the screen space x coordinate to use
  3524. * @param sourceY defines the screen space y coordinate to use
  3525. * @param sourceZ defines the screen space z coordinate to use
  3526. * @param viewportWidth defines the current width of the viewport
  3527. * @param viewportHeight defines the current height of the viewport
  3528. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3529. * @param view defines the view matrix to use
  3530. * @param projection defines the projection matrix to use
  3531. * @param result defines the Vector3 where to store the result
  3532. */
  3533. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3534. var matrix = MathTmp.Matrix[0];
  3535. world.multiplyToRef(view, matrix);
  3536. matrix.multiplyToRef(projection, matrix);
  3537. matrix.invert();
  3538. var screenSource = MathTmp.Vector3[0];
  3539. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3540. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3541. screenSource.z = 2 * sourceZ - 1.0;
  3542. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3543. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3544. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3545. result.scaleInPlace(1.0 / num);
  3546. }
  3547. };
  3548. /**
  3549. * Gets the minimal coordinate values between two Vector3
  3550. * @param left defines the first operand
  3551. * @param right defines the second operand
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Minimize = function (left, right) {
  3555. var min = left.clone();
  3556. min.minimizeInPlace(right);
  3557. return min;
  3558. };
  3559. /**
  3560. * Gets the maximal coordinate values between two Vector3
  3561. * @param left defines the first operand
  3562. * @param right defines the second operand
  3563. * @returns the new Vector3
  3564. */
  3565. Vector3.Maximize = function (left, right) {
  3566. var max = left.clone();
  3567. max.maximizeInPlace(right);
  3568. return max;
  3569. };
  3570. /**
  3571. * Returns the distance between the vectors "value1" and "value2"
  3572. * @param value1 defines the first operand
  3573. * @param value2 defines the second operand
  3574. * @returns the distance
  3575. */
  3576. Vector3.Distance = function (value1, value2) {
  3577. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3578. };
  3579. /**
  3580. * Returns the squared distance between the vectors "value1" and "value2"
  3581. * @param value1 defines the first operand
  3582. * @param value2 defines the second operand
  3583. * @returns the squared distance
  3584. */
  3585. Vector3.DistanceSquared = function (value1, value2) {
  3586. var x = value1.x - value2.x;
  3587. var y = value1.y - value2.y;
  3588. var z = value1.z - value2.z;
  3589. return (x * x) + (y * y) + (z * z);
  3590. };
  3591. /**
  3592. * Returns a new Vector3 located at the center between "value1" and "value2"
  3593. * @param value1 defines the first operand
  3594. * @param value2 defines the second operand
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.Center = function (value1, value2) {
  3598. var center = value1.add(value2);
  3599. center.scaleInPlace(0.5);
  3600. return center;
  3601. };
  3602. /**
  3603. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3604. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3605. * to something in order to rotate it from its local system to the given target system
  3606. * Note: axis1, axis2 and axis3 are normalized during this operation
  3607. * @param axis1 defines the first axis
  3608. * @param axis2 defines the second axis
  3609. * @param axis3 defines the third axis
  3610. * @returns a new Vector3
  3611. */
  3612. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3613. var rotation = Vector3.Zero();
  3614. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3615. return rotation;
  3616. };
  3617. /**
  3618. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3619. * @param axis1 defines the first axis
  3620. * @param axis2 defines the second axis
  3621. * @param axis3 defines the third axis
  3622. * @param ref defines the Vector3 where to store the result
  3623. */
  3624. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3625. var quat = MathTmp.Quaternion[0];
  3626. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3627. quat.toEulerAnglesToRef(ref);
  3628. };
  3629. return Vector3;
  3630. }());
  3631. BABYLON.Vector3 = Vector3;
  3632. //Vector4 class created for EulerAngle class conversion to Quaternion
  3633. var Vector4 = /** @class */ (function () {
  3634. /**
  3635. * Creates a Vector4 object from the passed floats.
  3636. */
  3637. function Vector4(x, y, z, w) {
  3638. this.x = x;
  3639. this.y = y;
  3640. this.z = z;
  3641. this.w = w;
  3642. }
  3643. /**
  3644. * Returns the string with the Vector4 coordinates.
  3645. */
  3646. Vector4.prototype.toString = function () {
  3647. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3648. };
  3649. /**
  3650. * Returns the string "Vector4".
  3651. */
  3652. Vector4.prototype.getClassName = function () {
  3653. return "Vector4";
  3654. };
  3655. /**
  3656. * Returns the Vector4 hash code.
  3657. */
  3658. Vector4.prototype.getHashCode = function () {
  3659. var hash = this.x || 0;
  3660. hash = (hash * 397) ^ (this.y || 0);
  3661. hash = (hash * 397) ^ (this.z || 0);
  3662. hash = (hash * 397) ^ (this.w || 0);
  3663. return hash;
  3664. };
  3665. // Operators
  3666. /**
  3667. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3668. */
  3669. Vector4.prototype.asArray = function () {
  3670. var result = new Array();
  3671. this.toArray(result, 0);
  3672. return result;
  3673. };
  3674. /**
  3675. * Populates the passed array from the passed index with the Vector4 coordinates.
  3676. * Returns the Vector4.
  3677. */
  3678. Vector4.prototype.toArray = function (array, index) {
  3679. if (index === undefined) {
  3680. index = 0;
  3681. }
  3682. array[index] = this.x;
  3683. array[index + 1] = this.y;
  3684. array[index + 2] = this.z;
  3685. array[index + 3] = this.w;
  3686. return this;
  3687. };
  3688. /**
  3689. * Adds the passed vector to the current Vector4.
  3690. * Returns the updated Vector4.
  3691. */
  3692. Vector4.prototype.addInPlace = function (otherVector) {
  3693. this.x += otherVector.x;
  3694. this.y += otherVector.y;
  3695. this.z += otherVector.z;
  3696. this.w += otherVector.w;
  3697. return this;
  3698. };
  3699. /**
  3700. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3701. */
  3702. Vector4.prototype.add = function (otherVector) {
  3703. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3704. };
  3705. /**
  3706. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3707. * Returns the current Vector4.
  3708. */
  3709. Vector4.prototype.addToRef = function (otherVector, result) {
  3710. result.x = this.x + otherVector.x;
  3711. result.y = this.y + otherVector.y;
  3712. result.z = this.z + otherVector.z;
  3713. result.w = this.w + otherVector.w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Subtract in place the passed vector from the current Vector4.
  3718. * Returns the updated Vector4.
  3719. */
  3720. Vector4.prototype.subtractInPlace = function (otherVector) {
  3721. this.x -= otherVector.x;
  3722. this.y -= otherVector.y;
  3723. this.z -= otherVector.z;
  3724. this.w -= otherVector.w;
  3725. return this;
  3726. };
  3727. /**
  3728. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3729. */
  3730. Vector4.prototype.subtract = function (otherVector) {
  3731. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3732. };
  3733. /**
  3734. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3735. * Returns the current Vector4.
  3736. */
  3737. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3738. result.x = this.x - otherVector.x;
  3739. result.y = this.y - otherVector.y;
  3740. result.z = this.z - otherVector.z;
  3741. result.w = this.w - otherVector.w;
  3742. return this;
  3743. };
  3744. /**
  3745. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3746. */
  3747. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3748. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3749. };
  3750. /**
  3751. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3752. * Returns the current Vector4.
  3753. */
  3754. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3755. result.x = this.x - x;
  3756. result.y = this.y - y;
  3757. result.z = this.z - z;
  3758. result.w = this.w - w;
  3759. return this;
  3760. };
  3761. /**
  3762. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3763. */
  3764. Vector4.prototype.negate = function () {
  3765. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3766. };
  3767. /**
  3768. * Multiplies the current Vector4 coordinates by scale (float).
  3769. * Returns the updated Vector4.
  3770. */
  3771. Vector4.prototype.scaleInPlace = function (scale) {
  3772. this.x *= scale;
  3773. this.y *= scale;
  3774. this.z *= scale;
  3775. this.w *= scale;
  3776. return this;
  3777. };
  3778. /**
  3779. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3780. */
  3781. Vector4.prototype.scale = function (scale) {
  3782. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3783. };
  3784. /**
  3785. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3786. * Returns the current Vector4.
  3787. */
  3788. Vector4.prototype.scaleToRef = function (scale, result) {
  3789. result.x = this.x * scale;
  3790. result.y = this.y * scale;
  3791. result.z = this.z * scale;
  3792. result.w = this.w * scale;
  3793. return this;
  3794. };
  3795. /**
  3796. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3797. */
  3798. Vector4.prototype.equals = function (otherVector) {
  3799. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3800. };
  3801. /**
  3802. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3803. */
  3804. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3805. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3806. return otherVector
  3807. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3808. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3809. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3810. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3811. };
  3812. /**
  3813. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3814. */
  3815. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3816. return this.x === x && this.y === y && this.z === z && this.w === w;
  3817. };
  3818. /**
  3819. * Multiplies in place the current Vector4 by the passed one.
  3820. * Returns the updated Vector4.
  3821. */
  3822. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3823. this.x *= otherVector.x;
  3824. this.y *= otherVector.y;
  3825. this.z *= otherVector.z;
  3826. this.w *= otherVector.w;
  3827. return this;
  3828. };
  3829. /**
  3830. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3831. */
  3832. Vector4.prototype.multiply = function (otherVector) {
  3833. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3834. };
  3835. /**
  3836. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3837. * Returns the current Vector4.
  3838. */
  3839. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3840. result.x = this.x * otherVector.x;
  3841. result.y = this.y * otherVector.y;
  3842. result.z = this.z * otherVector.z;
  3843. result.w = this.w * otherVector.w;
  3844. return this;
  3845. };
  3846. /**
  3847. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3848. */
  3849. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3850. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3851. };
  3852. /**
  3853. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3854. */
  3855. Vector4.prototype.divide = function (otherVector) {
  3856. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3857. };
  3858. /**
  3859. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3860. * Returns the current Vector4.
  3861. */
  3862. Vector4.prototype.divideToRef = function (otherVector, result) {
  3863. result.x = this.x / otherVector.x;
  3864. result.y = this.y / otherVector.y;
  3865. result.z = this.z / otherVector.z;
  3866. result.w = this.w / otherVector.w;
  3867. return this;
  3868. };
  3869. /**
  3870. * Divides the current Vector3 coordinates by the passed ones.
  3871. * @returns the updated Vector3.
  3872. */
  3873. Vector4.prototype.divideInPlace = function (otherVector) {
  3874. return this.divideToRef(otherVector, this);
  3875. };
  3876. /**
  3877. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3878. * @param other defines the second operand
  3879. * @returns the current updated Vector4
  3880. */
  3881. Vector4.prototype.minimizeInPlace = function (other) {
  3882. if (other.x < this.x)
  3883. this.x = other.x;
  3884. if (other.y < this.y)
  3885. this.y = other.y;
  3886. if (other.z < this.z)
  3887. this.z = other.z;
  3888. if (other.w < this.w)
  3889. this.w = other.w;
  3890. return this;
  3891. };
  3892. /**
  3893. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3894. * @param other defines the second operand
  3895. * @returns the current updated Vector4
  3896. */
  3897. Vector4.prototype.maximizeInPlace = function (other) {
  3898. if (other.x > this.x)
  3899. this.x = other.x;
  3900. if (other.y > this.y)
  3901. this.y = other.y;
  3902. if (other.z > this.z)
  3903. this.z = other.z;
  3904. if (other.w > this.w)
  3905. this.w = other.w;
  3906. return this;
  3907. };
  3908. // Properties
  3909. /**
  3910. * Returns the Vector4 length (float).
  3911. */
  3912. Vector4.prototype.length = function () {
  3913. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3914. };
  3915. /**
  3916. * Returns the Vector4 squared length (float).
  3917. */
  3918. Vector4.prototype.lengthSquared = function () {
  3919. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3920. };
  3921. // Methods
  3922. /**
  3923. * Normalizes in place the Vector4.
  3924. * Returns the updated Vector4.
  3925. */
  3926. Vector4.prototype.normalize = function () {
  3927. var len = this.length();
  3928. if (len === 0)
  3929. return this;
  3930. var num = 1.0 / len;
  3931. this.x *= num;
  3932. this.y *= num;
  3933. this.z *= num;
  3934. this.w *= num;
  3935. return this;
  3936. };
  3937. /**
  3938. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3939. */
  3940. Vector4.prototype.toVector3 = function () {
  3941. return new Vector3(this.x, this.y, this.z);
  3942. };
  3943. /**
  3944. * Returns a new Vector4 copied from the current one.
  3945. */
  3946. Vector4.prototype.clone = function () {
  3947. return new Vector4(this.x, this.y, this.z, this.w);
  3948. };
  3949. /**
  3950. * Updates the current Vector4 with the passed one coordinates.
  3951. * Returns the updated Vector4.
  3952. */
  3953. Vector4.prototype.copyFrom = function (source) {
  3954. this.x = source.x;
  3955. this.y = source.y;
  3956. this.z = source.z;
  3957. this.w = source.w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Updates the current Vector4 coordinates with the passed floats.
  3962. * Returns the updated Vector4.
  3963. */
  3964. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3965. this.x = x;
  3966. this.y = y;
  3967. this.z = z;
  3968. this.w = w;
  3969. return this;
  3970. };
  3971. /**
  3972. * Updates the current Vector4 coordinates with the passed floats.
  3973. * Returns the updated Vector4.
  3974. */
  3975. Vector4.prototype.set = function (x, y, z, w) {
  3976. return this.copyFromFloats(x, y, z, w);
  3977. };
  3978. // Statics
  3979. /**
  3980. * Returns a new Vector4 set from the starting index of the passed array.
  3981. */
  3982. Vector4.FromArray = function (array, offset) {
  3983. if (!offset) {
  3984. offset = 0;
  3985. }
  3986. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3987. };
  3988. /**
  3989. * Updates the passed vector "result" from the starting index of the passed array.
  3990. */
  3991. Vector4.FromArrayToRef = function (array, offset, result) {
  3992. result.x = array[offset];
  3993. result.y = array[offset + 1];
  3994. result.z = array[offset + 2];
  3995. result.w = array[offset + 3];
  3996. };
  3997. /**
  3998. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3999. */
  4000. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4001. Vector4.FromArrayToRef(array, offset, result);
  4002. };
  4003. /**
  4004. * Updates the passed vector "result" coordinates from the passed floats.
  4005. */
  4006. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4007. result.x = x;
  4008. result.y = y;
  4009. result.z = z;
  4010. result.w = w;
  4011. };
  4012. /**
  4013. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4014. */
  4015. Vector4.Zero = function () {
  4016. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4017. };
  4018. /**
  4019. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4020. */
  4021. Vector4.One = function () {
  4022. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4023. };
  4024. /**
  4025. * Returns a new normalized Vector4 from the passed one.
  4026. */
  4027. Vector4.Normalize = function (vector) {
  4028. var result = Vector4.Zero();
  4029. Vector4.NormalizeToRef(vector, result);
  4030. return result;
  4031. };
  4032. /**
  4033. * Updates the passed vector "result" from the normalization of the passed one.
  4034. */
  4035. Vector4.NormalizeToRef = function (vector, result) {
  4036. result.copyFrom(vector);
  4037. result.normalize();
  4038. };
  4039. Vector4.Minimize = function (left, right) {
  4040. var min = left.clone();
  4041. min.minimizeInPlace(right);
  4042. return min;
  4043. };
  4044. Vector4.Maximize = function (left, right) {
  4045. var max = left.clone();
  4046. max.maximizeInPlace(right);
  4047. return max;
  4048. };
  4049. /**
  4050. * Returns the distance (float) between the vectors "value1" and "value2".
  4051. */
  4052. Vector4.Distance = function (value1, value2) {
  4053. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4054. };
  4055. /**
  4056. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4057. */
  4058. Vector4.DistanceSquared = function (value1, value2) {
  4059. var x = value1.x - value2.x;
  4060. var y = value1.y - value2.y;
  4061. var z = value1.z - value2.z;
  4062. var w = value1.w - value2.w;
  4063. return (x * x) + (y * y) + (z * z) + (w * w);
  4064. };
  4065. /**
  4066. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4067. */
  4068. Vector4.Center = function (value1, value2) {
  4069. var center = value1.add(value2);
  4070. center.scaleInPlace(0.5);
  4071. return center;
  4072. };
  4073. /**
  4074. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4075. * This methods computes transformed normalized direction vectors only.
  4076. */
  4077. Vector4.TransformNormal = function (vector, transformation) {
  4078. var result = Vector4.Zero();
  4079. Vector4.TransformNormalToRef(vector, transformation, result);
  4080. return result;
  4081. };
  4082. /**
  4083. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4084. * This methods computes transformed normalized direction vectors only.
  4085. */
  4086. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4087. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4088. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4089. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4090. result.x = x;
  4091. result.y = y;
  4092. result.z = z;
  4093. result.w = vector.w;
  4094. };
  4095. /**
  4096. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4097. * This methods computes transformed normalized direction vectors only.
  4098. */
  4099. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4100. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4101. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4102. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4103. result.w = w;
  4104. };
  4105. return Vector4;
  4106. }());
  4107. BABYLON.Vector4 = Vector4;
  4108. var Size = /** @class */ (function () {
  4109. /**
  4110. * Creates a Size object from the passed width and height (floats).
  4111. */
  4112. function Size(width, height) {
  4113. this.width = width;
  4114. this.height = height;
  4115. }
  4116. // Returns a string with the Size width and height.
  4117. Size.prototype.toString = function () {
  4118. return "{W: " + this.width + ", H: " + this.height + "}";
  4119. };
  4120. /**
  4121. * Returns the string "Size"
  4122. */
  4123. Size.prototype.getClassName = function () {
  4124. return "Size";
  4125. };
  4126. /**
  4127. * Returns the Size hash code.
  4128. */
  4129. Size.prototype.getHashCode = function () {
  4130. var hash = this.width || 0;
  4131. hash = (hash * 397) ^ (this.height || 0);
  4132. return hash;
  4133. };
  4134. /**
  4135. * Updates the current size from the passed one.
  4136. * Returns the updated Size.
  4137. */
  4138. Size.prototype.copyFrom = function (src) {
  4139. this.width = src.width;
  4140. this.height = src.height;
  4141. };
  4142. /**
  4143. * Updates in place the current Size from the passed floats.
  4144. * Returns the updated Size.
  4145. */
  4146. Size.prototype.copyFromFloats = function (width, height) {
  4147. this.width = width;
  4148. this.height = height;
  4149. return this;
  4150. };
  4151. /**
  4152. * Updates in place the current Size from the passed floats.
  4153. * Returns the updated Size.
  4154. */
  4155. Size.prototype.set = function (width, height) {
  4156. return this.copyFromFloats(width, height);
  4157. };
  4158. /**
  4159. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4160. */
  4161. Size.prototype.multiplyByFloats = function (w, h) {
  4162. return new Size(this.width * w, this.height * h);
  4163. };
  4164. /**
  4165. * Returns a new Size copied from the passed one.
  4166. */
  4167. Size.prototype.clone = function () {
  4168. return new Size(this.width, this.height);
  4169. };
  4170. /**
  4171. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4172. */
  4173. Size.prototype.equals = function (other) {
  4174. if (!other) {
  4175. return false;
  4176. }
  4177. return (this.width === other.width) && (this.height === other.height);
  4178. };
  4179. Object.defineProperty(Size.prototype, "surface", {
  4180. /**
  4181. * Returns the surface of the Size : width * height (float).
  4182. */
  4183. get: function () {
  4184. return this.width * this.height;
  4185. },
  4186. enumerable: true,
  4187. configurable: true
  4188. });
  4189. /**
  4190. * Returns a new Size set to (0.0, 0.0)
  4191. */
  4192. Size.Zero = function () {
  4193. return new Size(0.0, 0.0);
  4194. };
  4195. /**
  4196. * Returns a new Size set as the addition result of the current Size and the passed one.
  4197. */
  4198. Size.prototype.add = function (otherSize) {
  4199. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4200. return r;
  4201. };
  4202. /**
  4203. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4204. */
  4205. Size.prototype.subtract = function (otherSize) {
  4206. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4207. return r;
  4208. };
  4209. /**
  4210. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4211. */
  4212. Size.Lerp = function (start, end, amount) {
  4213. var w = start.width + ((end.width - start.width) * amount);
  4214. var h = start.height + ((end.height - start.height) * amount);
  4215. return new Size(w, h);
  4216. };
  4217. return Size;
  4218. }());
  4219. BABYLON.Size = Size;
  4220. var Quaternion = /** @class */ (function () {
  4221. /**
  4222. * Creates a new Quaternion from the passed floats.
  4223. */
  4224. function Quaternion(x, y, z, w) {
  4225. if (x === void 0) { x = 0.0; }
  4226. if (y === void 0) { y = 0.0; }
  4227. if (z === void 0) { z = 0.0; }
  4228. if (w === void 0) { w = 1.0; }
  4229. this.x = x;
  4230. this.y = y;
  4231. this.z = z;
  4232. this.w = w;
  4233. }
  4234. /**
  4235. * Returns a string with the Quaternion coordinates.
  4236. */
  4237. Quaternion.prototype.toString = function () {
  4238. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4239. };
  4240. /**
  4241. * Returns the string "Quaternion".
  4242. */
  4243. Quaternion.prototype.getClassName = function () {
  4244. return "Quaternion";
  4245. };
  4246. /**
  4247. * Returns the Quaternion hash code.
  4248. */
  4249. Quaternion.prototype.getHashCode = function () {
  4250. var hash = this.x || 0;
  4251. hash = (hash * 397) ^ (this.y || 0);
  4252. hash = (hash * 397) ^ (this.z || 0);
  4253. hash = (hash * 397) ^ (this.w || 0);
  4254. return hash;
  4255. };
  4256. /**
  4257. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4258. */
  4259. Quaternion.prototype.asArray = function () {
  4260. return [this.x, this.y, this.z, this.w];
  4261. };
  4262. /**
  4263. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4264. */
  4265. Quaternion.prototype.equals = function (otherQuaternion) {
  4266. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4267. };
  4268. /**
  4269. * Returns a new Quaternion copied from the current one.
  4270. */
  4271. Quaternion.prototype.clone = function () {
  4272. return new Quaternion(this.x, this.y, this.z, this.w);
  4273. };
  4274. /**
  4275. * Updates the current Quaternion from the passed one coordinates.
  4276. * Returns the updated Quaterion.
  4277. */
  4278. Quaternion.prototype.copyFrom = function (other) {
  4279. this.x = other.x;
  4280. this.y = other.y;
  4281. this.z = other.z;
  4282. this.w = other.w;
  4283. return this;
  4284. };
  4285. /**
  4286. * Updates the current Quaternion from the passed float coordinates.
  4287. * Returns the updated Quaterion.
  4288. */
  4289. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4290. this.x = x;
  4291. this.y = y;
  4292. this.z = z;
  4293. this.w = w;
  4294. return this;
  4295. };
  4296. /**
  4297. * Updates the current Quaternion from the passed float coordinates.
  4298. * Returns the updated Quaterion.
  4299. */
  4300. Quaternion.prototype.set = function (x, y, z, w) {
  4301. return this.copyFromFloats(x, y, z, w);
  4302. };
  4303. /**
  4304. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4305. */
  4306. Quaternion.prototype.add = function (other) {
  4307. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4308. };
  4309. /**
  4310. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4311. */
  4312. Quaternion.prototype.subtract = function (other) {
  4313. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4314. };
  4315. /**
  4316. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4317. */
  4318. Quaternion.prototype.scale = function (value) {
  4319. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4320. };
  4321. /**
  4322. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4323. */
  4324. Quaternion.prototype.multiply = function (q1) {
  4325. var result = new Quaternion(0, 0, 0, 1.0);
  4326. this.multiplyToRef(q1, result);
  4327. return result;
  4328. };
  4329. /**
  4330. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4331. * Returns the current Quaternion.
  4332. */
  4333. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4334. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4335. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4336. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4337. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4338. result.copyFromFloats(x, y, z, w);
  4339. return this;
  4340. };
  4341. /**
  4342. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4343. * Returns the updated Quaternion.
  4344. */
  4345. Quaternion.prototype.multiplyInPlace = function (q1) {
  4346. this.multiplyToRef(q1, this);
  4347. return this;
  4348. };
  4349. /**
  4350. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4351. * Returns the current Quaternion.
  4352. */
  4353. Quaternion.prototype.conjugateToRef = function (ref) {
  4354. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4355. return this;
  4356. };
  4357. /**
  4358. * Conjugates in place the current Quaternion.
  4359. * Returns the updated Quaternion.
  4360. */
  4361. Quaternion.prototype.conjugateInPlace = function () {
  4362. this.x *= -1;
  4363. this.y *= -1;
  4364. this.z *= -1;
  4365. return this;
  4366. };
  4367. /**
  4368. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4369. */
  4370. Quaternion.prototype.conjugate = function () {
  4371. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4372. return result;
  4373. };
  4374. /**
  4375. * Returns the Quaternion length (float).
  4376. */
  4377. Quaternion.prototype.length = function () {
  4378. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4379. };
  4380. /**
  4381. * Normalize in place the current Quaternion.
  4382. * Returns the updated Quaternion.
  4383. */
  4384. Quaternion.prototype.normalize = function () {
  4385. var length = 1.0 / this.length();
  4386. this.x *= length;
  4387. this.y *= length;
  4388. this.z *= length;
  4389. this.w *= length;
  4390. return this;
  4391. };
  4392. /**
  4393. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4394. */
  4395. Quaternion.prototype.toEulerAngles = function (order) {
  4396. if (order === void 0) { order = "YZX"; }
  4397. var result = Vector3.Zero();
  4398. this.toEulerAnglesToRef(result, order);
  4399. return result;
  4400. };
  4401. /**
  4402. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4403. * Returns the current Quaternion.
  4404. */
  4405. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4406. if (order === void 0) { order = "YZX"; }
  4407. var qz = this.z;
  4408. var qx = this.x;
  4409. var qy = this.y;
  4410. var qw = this.w;
  4411. var sqw = qw * qw;
  4412. var sqz = qz * qz;
  4413. var sqx = qx * qx;
  4414. var sqy = qy * qy;
  4415. var zAxisY = qy * qz - qx * qw;
  4416. var limit = .4999999;
  4417. if (zAxisY < -limit) {
  4418. result.y = 2 * Math.atan2(qy, qw);
  4419. result.x = Math.PI / 2;
  4420. result.z = 0;
  4421. }
  4422. else if (zAxisY > limit) {
  4423. result.y = 2 * Math.atan2(qy, qw);
  4424. result.x = -Math.PI / 2;
  4425. result.z = 0;
  4426. }
  4427. else {
  4428. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4429. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4430. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4431. }
  4432. return this;
  4433. };
  4434. /**
  4435. * Updates the passed rotation matrix with the current Quaternion values.
  4436. * Returns the current Quaternion.
  4437. */
  4438. Quaternion.prototype.toRotationMatrix = function (result) {
  4439. var xx = this.x * this.x;
  4440. var yy = this.y * this.y;
  4441. var zz = this.z * this.z;
  4442. var xy = this.x * this.y;
  4443. var zw = this.z * this.w;
  4444. var zx = this.z * this.x;
  4445. var yw = this.y * this.w;
  4446. var yz = this.y * this.z;
  4447. var xw = this.x * this.w;
  4448. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4449. result.m[1] = 2.0 * (xy + zw);
  4450. result.m[2] = 2.0 * (zx - yw);
  4451. result.m[3] = 0;
  4452. result.m[4] = 2.0 * (xy - zw);
  4453. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4454. result.m[6] = 2.0 * (yz + xw);
  4455. result.m[7] = 0;
  4456. result.m[8] = 2.0 * (zx + yw);
  4457. result.m[9] = 2.0 * (yz - xw);
  4458. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4459. result.m[11] = 0;
  4460. result.m[12] = 0;
  4461. result.m[13] = 0;
  4462. result.m[14] = 0;
  4463. result.m[15] = 1.0;
  4464. result._markAsUpdated();
  4465. return this;
  4466. };
  4467. /**
  4468. * Updates the current Quaternion from the passed rotation matrix values.
  4469. * Returns the updated Quaternion.
  4470. */
  4471. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4472. Quaternion.FromRotationMatrixToRef(matrix, this);
  4473. return this;
  4474. };
  4475. // Statics
  4476. /**
  4477. * Returns a new Quaternion set from the passed rotation matrix values.
  4478. */
  4479. Quaternion.FromRotationMatrix = function (matrix) {
  4480. var result = new Quaternion();
  4481. Quaternion.FromRotationMatrixToRef(matrix, result);
  4482. return result;
  4483. };
  4484. /**
  4485. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4486. */
  4487. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4488. var data = matrix.m;
  4489. var m11 = data[0], m12 = data[4], m13 = data[8];
  4490. var m21 = data[1], m22 = data[5], m23 = data[9];
  4491. var m31 = data[2], m32 = data[6], m33 = data[10];
  4492. var trace = m11 + m22 + m33;
  4493. var s;
  4494. if (trace > 0) {
  4495. s = 0.5 / Math.sqrt(trace + 1.0);
  4496. result.w = 0.25 / s;
  4497. result.x = (m32 - m23) * s;
  4498. result.y = (m13 - m31) * s;
  4499. result.z = (m21 - m12) * s;
  4500. }
  4501. else if (m11 > m22 && m11 > m33) {
  4502. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4503. result.w = (m32 - m23) / s;
  4504. result.x = 0.25 * s;
  4505. result.y = (m12 + m21) / s;
  4506. result.z = (m13 + m31) / s;
  4507. }
  4508. else if (m22 > m33) {
  4509. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4510. result.w = (m13 - m31) / s;
  4511. result.x = (m12 + m21) / s;
  4512. result.y = 0.25 * s;
  4513. result.z = (m23 + m32) / s;
  4514. }
  4515. else {
  4516. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4517. result.w = (m21 - m12) / s;
  4518. result.x = (m13 + m31) / s;
  4519. result.y = (m23 + m32) / s;
  4520. result.z = 0.25 * s;
  4521. }
  4522. };
  4523. /**
  4524. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4525. */
  4526. Quaternion.Zero = function () {
  4527. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4528. };
  4529. /**
  4530. * Returns a new Quaternion as the inverted current Quaternion.
  4531. */
  4532. Quaternion.Inverse = function (q) {
  4533. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4534. };
  4535. /**
  4536. * Returns the identity Quaternion.
  4537. */
  4538. Quaternion.Identity = function () {
  4539. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4540. };
  4541. Quaternion.IsIdentity = function (quaternion) {
  4542. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4543. };
  4544. /**
  4545. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4546. */
  4547. Quaternion.RotationAxis = function (axis, angle) {
  4548. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4549. };
  4550. /**
  4551. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4552. */
  4553. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4554. var sin = Math.sin(angle / 2);
  4555. axis.normalize();
  4556. result.w = Math.cos(angle / 2);
  4557. result.x = axis.x * sin;
  4558. result.y = axis.y * sin;
  4559. result.z = axis.z * sin;
  4560. return result;
  4561. };
  4562. /**
  4563. * Retuns a new Quaternion set from the starting index of the passed array.
  4564. */
  4565. Quaternion.FromArray = function (array, offset) {
  4566. if (!offset) {
  4567. offset = 0;
  4568. }
  4569. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4570. };
  4571. /**
  4572. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4573. */
  4574. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4575. var q = new Quaternion();
  4576. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4577. return q;
  4578. };
  4579. /**
  4580. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4581. */
  4582. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4583. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4584. var halfRoll = roll * 0.5;
  4585. var halfPitch = pitch * 0.5;
  4586. var halfYaw = yaw * 0.5;
  4587. var sinRoll = Math.sin(halfRoll);
  4588. var cosRoll = Math.cos(halfRoll);
  4589. var sinPitch = Math.sin(halfPitch);
  4590. var cosPitch = Math.cos(halfPitch);
  4591. var sinYaw = Math.sin(halfYaw);
  4592. var cosYaw = Math.cos(halfYaw);
  4593. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4594. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4595. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4596. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4597. };
  4598. /**
  4599. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4600. */
  4601. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4602. var result = new Quaternion();
  4603. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4604. return result;
  4605. };
  4606. /**
  4607. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4608. */
  4609. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4610. // Produces a quaternion from Euler angles in the z-x-z orientation
  4611. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4612. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4613. var halfBeta = beta * 0.5;
  4614. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4615. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4616. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4617. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4618. };
  4619. /**
  4620. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4621. * cf to Vector3.RotationFromAxis() documentation.
  4622. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4623. */
  4624. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4625. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4626. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4627. return quat;
  4628. };
  4629. /**
  4630. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4631. * cf to Vector3.RotationFromAxis() documentation.
  4632. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4633. */
  4634. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4635. var rotMat = MathTmp.Matrix[0];
  4636. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4637. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4638. };
  4639. Quaternion.Slerp = function (left, right, amount) {
  4640. var result = Quaternion.Identity();
  4641. Quaternion.SlerpToRef(left, right, amount, result);
  4642. return result;
  4643. };
  4644. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4645. var num2;
  4646. var num3;
  4647. var num = amount;
  4648. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4649. var flag = false;
  4650. if (num4 < 0) {
  4651. flag = true;
  4652. num4 = -num4;
  4653. }
  4654. if (num4 > 0.999999) {
  4655. num3 = 1 - num;
  4656. num2 = flag ? -num : num;
  4657. }
  4658. else {
  4659. var num5 = Math.acos(num4);
  4660. var num6 = (1.0 / Math.sin(num5));
  4661. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4662. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4663. }
  4664. result.x = (num3 * left.x) + (num2 * right.x);
  4665. result.y = (num3 * left.y) + (num2 * right.y);
  4666. result.z = (num3 * left.z) + (num2 * right.z);
  4667. result.w = (num3 * left.w) + (num2 * right.w);
  4668. };
  4669. /**
  4670. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4671. */
  4672. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4673. var squared = amount * amount;
  4674. var cubed = amount * squared;
  4675. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4676. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4677. var part3 = (cubed - (2.0 * squared)) + amount;
  4678. var part4 = cubed - squared;
  4679. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4680. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4681. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4682. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4683. return new Quaternion(x, y, z, w);
  4684. };
  4685. return Quaternion;
  4686. }());
  4687. BABYLON.Quaternion = Quaternion;
  4688. var Matrix = /** @class */ (function () {
  4689. function Matrix() {
  4690. this._isIdentity = false;
  4691. this._isIdentityDirty = true;
  4692. this.m = new Float32Array(16);
  4693. this._markAsUpdated();
  4694. }
  4695. Matrix.prototype._markAsUpdated = function () {
  4696. this.updateFlag = Matrix._updateFlagSeed++;
  4697. this._isIdentityDirty = true;
  4698. };
  4699. // Properties
  4700. /**
  4701. * Boolean : True is the matrix is the identity matrix
  4702. */
  4703. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4704. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4705. if (this._isIdentityDirty) {
  4706. this._isIdentityDirty = false;
  4707. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4708. this._isIdentity = false;
  4709. }
  4710. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4711. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4712. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4713. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4714. this._isIdentity = false;
  4715. }
  4716. else {
  4717. this._isIdentity = true;
  4718. }
  4719. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4720. this._isIdentity = false;
  4721. }
  4722. }
  4723. return this._isIdentity;
  4724. };
  4725. /**
  4726. * Returns the matrix determinant (float).
  4727. */
  4728. Matrix.prototype.determinant = function () {
  4729. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4730. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4731. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4732. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4733. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4734. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4735. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4736. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4737. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4738. };
  4739. // Methods
  4740. /**
  4741. * Returns the matrix underlying array.
  4742. */
  4743. Matrix.prototype.toArray = function () {
  4744. return this.m;
  4745. };
  4746. /**
  4747. * Returns the matrix underlying array.
  4748. */
  4749. Matrix.prototype.asArray = function () {
  4750. return this.toArray();
  4751. };
  4752. /**
  4753. * Inverts in place the Matrix.
  4754. * Returns the Matrix inverted.
  4755. */
  4756. Matrix.prototype.invert = function () {
  4757. this.invertToRef(this);
  4758. return this;
  4759. };
  4760. /**
  4761. * Sets all the matrix elements to zero.
  4762. * Returns the Matrix.
  4763. */
  4764. Matrix.prototype.reset = function () {
  4765. for (var index = 0; index < 16; index++) {
  4766. this.m[index] = 0.0;
  4767. }
  4768. this._markAsUpdated();
  4769. return this;
  4770. };
  4771. /**
  4772. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4773. */
  4774. Matrix.prototype.add = function (other) {
  4775. var result = new Matrix();
  4776. this.addToRef(other, result);
  4777. return result;
  4778. };
  4779. /**
  4780. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4781. * Returns the Matrix.
  4782. */
  4783. Matrix.prototype.addToRef = function (other, result) {
  4784. for (var index = 0; index < 16; index++) {
  4785. result.m[index] = this.m[index] + other.m[index];
  4786. }
  4787. result._markAsUpdated();
  4788. return this;
  4789. };
  4790. /**
  4791. * Adds in place the passed matrix to the current Matrix.
  4792. * Returns the updated Matrix.
  4793. */
  4794. Matrix.prototype.addToSelf = function (other) {
  4795. for (var index = 0; index < 16; index++) {
  4796. this.m[index] += other.m[index];
  4797. }
  4798. this._markAsUpdated();
  4799. return this;
  4800. };
  4801. /**
  4802. * Sets the passed matrix with the current inverted Matrix.
  4803. * Returns the unmodified current Matrix.
  4804. */
  4805. Matrix.prototype.invertToRef = function (other) {
  4806. var l1 = this.m[0];
  4807. var l2 = this.m[1];
  4808. var l3 = this.m[2];
  4809. var l4 = this.m[3];
  4810. var l5 = this.m[4];
  4811. var l6 = this.m[5];
  4812. var l7 = this.m[6];
  4813. var l8 = this.m[7];
  4814. var l9 = this.m[8];
  4815. var l10 = this.m[9];
  4816. var l11 = this.m[10];
  4817. var l12 = this.m[11];
  4818. var l13 = this.m[12];
  4819. var l14 = this.m[13];
  4820. var l15 = this.m[14];
  4821. var l16 = this.m[15];
  4822. var l17 = (l11 * l16) - (l12 * l15);
  4823. var l18 = (l10 * l16) - (l12 * l14);
  4824. var l19 = (l10 * l15) - (l11 * l14);
  4825. var l20 = (l9 * l16) - (l12 * l13);
  4826. var l21 = (l9 * l15) - (l11 * l13);
  4827. var l22 = (l9 * l14) - (l10 * l13);
  4828. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4829. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4830. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4831. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4832. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4833. var l28 = (l7 * l16) - (l8 * l15);
  4834. var l29 = (l6 * l16) - (l8 * l14);
  4835. var l30 = (l6 * l15) - (l7 * l14);
  4836. var l31 = (l5 * l16) - (l8 * l13);
  4837. var l32 = (l5 * l15) - (l7 * l13);
  4838. var l33 = (l5 * l14) - (l6 * l13);
  4839. var l34 = (l7 * l12) - (l8 * l11);
  4840. var l35 = (l6 * l12) - (l8 * l10);
  4841. var l36 = (l6 * l11) - (l7 * l10);
  4842. var l37 = (l5 * l12) - (l8 * l9);
  4843. var l38 = (l5 * l11) - (l7 * l9);
  4844. var l39 = (l5 * l10) - (l6 * l9);
  4845. other.m[0] = l23 * l27;
  4846. other.m[4] = l24 * l27;
  4847. other.m[8] = l25 * l27;
  4848. other.m[12] = l26 * l27;
  4849. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4850. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4851. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4852. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4853. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4854. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4855. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4856. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4857. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4858. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4859. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4860. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4861. other._markAsUpdated();
  4862. return this;
  4863. };
  4864. /**
  4865. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4866. * Returns the updated Matrix.
  4867. */
  4868. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4869. this.m[12] = x;
  4870. this.m[13] = y;
  4871. this.m[14] = z;
  4872. this._markAsUpdated();
  4873. return this;
  4874. };
  4875. /**
  4876. * Inserts the translation vector in the current Matrix.
  4877. * Returns the updated Matrix.
  4878. */
  4879. Matrix.prototype.setTranslation = function (vector3) {
  4880. this.m[12] = vector3.x;
  4881. this.m[13] = vector3.y;
  4882. this.m[14] = vector3.z;
  4883. this._markAsUpdated();
  4884. return this;
  4885. };
  4886. /**
  4887. * Returns a new Vector3 as the extracted translation from the Matrix.
  4888. */
  4889. Matrix.prototype.getTranslation = function () {
  4890. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4891. };
  4892. /**
  4893. * Fill a Vector3 with the extracted translation from the Matrix.
  4894. */
  4895. Matrix.prototype.getTranslationToRef = function (result) {
  4896. result.x = this.m[12];
  4897. result.y = this.m[13];
  4898. result.z = this.m[14];
  4899. return this;
  4900. };
  4901. /**
  4902. * Remove rotation and scaling part from the Matrix.
  4903. * Returns the updated Matrix.
  4904. */
  4905. Matrix.prototype.removeRotationAndScaling = function () {
  4906. this.setRowFromFloats(0, 1, 0, 0, 0);
  4907. this.setRowFromFloats(1, 0, 1, 0, 0);
  4908. this.setRowFromFloats(2, 0, 0, 1, 0);
  4909. return this;
  4910. };
  4911. /**
  4912. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4913. */
  4914. Matrix.prototype.multiply = function (other) {
  4915. var result = new Matrix();
  4916. this.multiplyToRef(other, result);
  4917. return result;
  4918. };
  4919. /**
  4920. * Updates the current Matrix from the passed one values.
  4921. * Returns the updated Matrix.
  4922. */
  4923. Matrix.prototype.copyFrom = function (other) {
  4924. for (var index = 0; index < 16; index++) {
  4925. this.m[index] = other.m[index];
  4926. }
  4927. this._markAsUpdated();
  4928. return this;
  4929. };
  4930. /**
  4931. * Populates the passed array from the starting index with the Matrix values.
  4932. * Returns the Matrix.
  4933. */
  4934. Matrix.prototype.copyToArray = function (array, offset) {
  4935. if (offset === void 0) { offset = 0; }
  4936. for (var index = 0; index < 16; index++) {
  4937. array[offset + index] = this.m[index];
  4938. }
  4939. return this;
  4940. };
  4941. /**
  4942. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4943. */
  4944. Matrix.prototype.multiplyToRef = function (other, result) {
  4945. this.multiplyToArray(other, result.m, 0);
  4946. result._markAsUpdated();
  4947. return this;
  4948. };
  4949. /**
  4950. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4951. */
  4952. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4953. var tm0 = this.m[0];
  4954. var tm1 = this.m[1];
  4955. var tm2 = this.m[2];
  4956. var tm3 = this.m[3];
  4957. var tm4 = this.m[4];
  4958. var tm5 = this.m[5];
  4959. var tm6 = this.m[6];
  4960. var tm7 = this.m[7];
  4961. var tm8 = this.m[8];
  4962. var tm9 = this.m[9];
  4963. var tm10 = this.m[10];
  4964. var tm11 = this.m[11];
  4965. var tm12 = this.m[12];
  4966. var tm13 = this.m[13];
  4967. var tm14 = this.m[14];
  4968. var tm15 = this.m[15];
  4969. var om0 = other.m[0];
  4970. var om1 = other.m[1];
  4971. var om2 = other.m[2];
  4972. var om3 = other.m[3];
  4973. var om4 = other.m[4];
  4974. var om5 = other.m[5];
  4975. var om6 = other.m[6];
  4976. var om7 = other.m[7];
  4977. var om8 = other.m[8];
  4978. var om9 = other.m[9];
  4979. var om10 = other.m[10];
  4980. var om11 = other.m[11];
  4981. var om12 = other.m[12];
  4982. var om13 = other.m[13];
  4983. var om14 = other.m[14];
  4984. var om15 = other.m[15];
  4985. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4986. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4987. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4988. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4989. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4990. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4991. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4992. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4993. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4994. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4995. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4996. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4997. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4998. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4999. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5000. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5001. return this;
  5002. };
  5003. /**
  5004. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5005. */
  5006. Matrix.prototype.equals = function (value) {
  5007. return value &&
  5008. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5009. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5010. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5011. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5012. };
  5013. /**
  5014. * Returns a new Matrix from the current Matrix.
  5015. */
  5016. Matrix.prototype.clone = function () {
  5017. 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]);
  5018. };
  5019. /**
  5020. * Returns the string "Matrix"
  5021. */
  5022. Matrix.prototype.getClassName = function () {
  5023. return "Matrix";
  5024. };
  5025. /**
  5026. * Returns the Matrix hash code.
  5027. */
  5028. Matrix.prototype.getHashCode = function () {
  5029. var hash = this.m[0] || 0;
  5030. for (var i = 1; i < 16; i++) {
  5031. hash = (hash * 397) ^ (this.m[i] || 0);
  5032. }
  5033. return hash;
  5034. };
  5035. /**
  5036. * Decomposes the current Matrix into :
  5037. * - a scale vector3 passed as a reference to update,
  5038. * - a rotation quaternion passed as a reference to update,
  5039. * - a translation vector3 passed as a reference to update.
  5040. * Returns the true if operation was successful.
  5041. */
  5042. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5043. translation.x = this.m[12];
  5044. translation.y = this.m[13];
  5045. translation.z = this.m[14];
  5046. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5047. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5048. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5049. if (this.determinant() <= 0) {
  5050. scale.y *= -1;
  5051. }
  5052. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5053. rotation.x = 0;
  5054. rotation.y = 0;
  5055. rotation.z = 0;
  5056. rotation.w = 1;
  5057. return false;
  5058. }
  5059. 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]);
  5060. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5061. return true;
  5062. };
  5063. /**
  5064. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5065. * @param ref matrix to store the result
  5066. */
  5067. Matrix.prototype.toNormalMatrix = function (ref) {
  5068. this.invertToRef(ref);
  5069. ref.transpose();
  5070. var m = ref.m;
  5071. 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);
  5072. };
  5073. /**
  5074. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5075. */
  5076. Matrix.prototype.getRotationMatrix = function () {
  5077. var result = Matrix.Identity();
  5078. this.getRotationMatrixToRef(result);
  5079. return result;
  5080. };
  5081. /**
  5082. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5083. * Returns the current Matrix.
  5084. */
  5085. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5086. var m = this.m;
  5087. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5088. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5089. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5090. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5091. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5092. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5093. 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);
  5094. return this;
  5095. };
  5096. // Statics
  5097. /**
  5098. * Returns a new Matrix set from the starting index of the passed array.
  5099. */
  5100. Matrix.FromArray = function (array, offset) {
  5101. var result = new Matrix();
  5102. if (!offset) {
  5103. offset = 0;
  5104. }
  5105. Matrix.FromArrayToRef(array, offset, result);
  5106. return result;
  5107. };
  5108. /**
  5109. * Sets the passed "result" matrix from the starting index of the passed array.
  5110. */
  5111. Matrix.FromArrayToRef = function (array, offset, result) {
  5112. for (var index = 0; index < 16; index++) {
  5113. result.m[index] = array[index + offset];
  5114. }
  5115. result._markAsUpdated();
  5116. };
  5117. /**
  5118. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5119. */
  5120. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5121. for (var index = 0; index < 16; index++) {
  5122. result.m[index] = array[index + offset] * scale;
  5123. }
  5124. result._markAsUpdated();
  5125. };
  5126. /**
  5127. * Sets the passed matrix "result" with the 16 passed floats.
  5128. */
  5129. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5130. result.m[0] = initialM11;
  5131. result.m[1] = initialM12;
  5132. result.m[2] = initialM13;
  5133. result.m[3] = initialM14;
  5134. result.m[4] = initialM21;
  5135. result.m[5] = initialM22;
  5136. result.m[6] = initialM23;
  5137. result.m[7] = initialM24;
  5138. result.m[8] = initialM31;
  5139. result.m[9] = initialM32;
  5140. result.m[10] = initialM33;
  5141. result.m[11] = initialM34;
  5142. result.m[12] = initialM41;
  5143. result.m[13] = initialM42;
  5144. result.m[14] = initialM43;
  5145. result.m[15] = initialM44;
  5146. result._markAsUpdated();
  5147. };
  5148. /**
  5149. * Returns the index-th row of the current matrix as a new Vector4.
  5150. */
  5151. Matrix.prototype.getRow = function (index) {
  5152. if (index < 0 || index > 3) {
  5153. return null;
  5154. }
  5155. var i = index * 4;
  5156. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5157. };
  5158. /**
  5159. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5160. * Returns the updated Matrix.
  5161. */
  5162. Matrix.prototype.setRow = function (index, row) {
  5163. if (index < 0 || index > 3) {
  5164. return this;
  5165. }
  5166. var i = index * 4;
  5167. this.m[i + 0] = row.x;
  5168. this.m[i + 1] = row.y;
  5169. this.m[i + 2] = row.z;
  5170. this.m[i + 3] = row.w;
  5171. this._markAsUpdated();
  5172. return this;
  5173. };
  5174. /**
  5175. * Compute the transpose of the matrix.
  5176. * Returns a new Matrix.
  5177. */
  5178. Matrix.prototype.transpose = function () {
  5179. return Matrix.Transpose(this);
  5180. };
  5181. /**
  5182. * Compute the transpose of the matrix.
  5183. * Returns the current matrix.
  5184. */
  5185. Matrix.prototype.transposeToRef = function (result) {
  5186. Matrix.TransposeToRef(this, result);
  5187. return this;
  5188. };
  5189. /**
  5190. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5191. * Returns the updated Matrix.
  5192. */
  5193. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5194. if (index < 0 || index > 3) {
  5195. return this;
  5196. }
  5197. var i = index * 4;
  5198. this.m[i + 0] = x;
  5199. this.m[i + 1] = y;
  5200. this.m[i + 2] = z;
  5201. this.m[i + 3] = w;
  5202. this._markAsUpdated();
  5203. return this;
  5204. };
  5205. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5206. /**
  5207. * Static identity matrix to be used as readonly matrix
  5208. * Must not be updated.
  5209. */
  5210. get: function () {
  5211. return Matrix._identityReadOnly;
  5212. },
  5213. enumerable: true,
  5214. configurable: true
  5215. });
  5216. /**
  5217. * Returns a new Matrix set from the 16 passed floats.
  5218. */
  5219. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5220. var result = new Matrix();
  5221. result.m[0] = initialM11;
  5222. result.m[1] = initialM12;
  5223. result.m[2] = initialM13;
  5224. result.m[3] = initialM14;
  5225. result.m[4] = initialM21;
  5226. result.m[5] = initialM22;
  5227. result.m[6] = initialM23;
  5228. result.m[7] = initialM24;
  5229. result.m[8] = initialM31;
  5230. result.m[9] = initialM32;
  5231. result.m[10] = initialM33;
  5232. result.m[11] = initialM34;
  5233. result.m[12] = initialM41;
  5234. result.m[13] = initialM42;
  5235. result.m[14] = initialM43;
  5236. result.m[15] = initialM44;
  5237. return result;
  5238. };
  5239. /**
  5240. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5241. */
  5242. Matrix.Compose = function (scale, rotation, translation) {
  5243. var result = Matrix.Identity();
  5244. Matrix.ComposeToRef(scale, rotation, translation, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5249. */
  5250. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5251. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5252. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5253. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5254. result.setTranslation(translation);
  5255. };
  5256. /**
  5257. * Returns a new indentity Matrix.
  5258. */
  5259. Matrix.Identity = function () {
  5260. 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);
  5261. };
  5262. /**
  5263. * Sets the passed "result" as an identity matrix.
  5264. */
  5265. Matrix.IdentityToRef = function (result) {
  5266. 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);
  5267. };
  5268. /**
  5269. * Returns a new zero Matrix.
  5270. */
  5271. Matrix.Zero = function () {
  5272. 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);
  5273. };
  5274. /**
  5275. * Returns a new rotation matrix for "angle" radians around the X axis.
  5276. */
  5277. Matrix.RotationX = function (angle) {
  5278. var result = new Matrix();
  5279. Matrix.RotationXToRef(angle, result);
  5280. return result;
  5281. };
  5282. /**
  5283. * Returns a new Matrix as the passed inverted one.
  5284. */
  5285. Matrix.Invert = function (source) {
  5286. var result = new Matrix();
  5287. source.invertToRef(result);
  5288. return result;
  5289. };
  5290. /**
  5291. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5292. */
  5293. Matrix.RotationXToRef = function (angle, result) {
  5294. var s = Math.sin(angle);
  5295. var c = Math.cos(angle);
  5296. result.m[0] = 1.0;
  5297. result.m[15] = 1.0;
  5298. result.m[5] = c;
  5299. result.m[10] = c;
  5300. result.m[9] = -s;
  5301. result.m[6] = s;
  5302. result.m[1] = 0.0;
  5303. result.m[2] = 0.0;
  5304. result.m[3] = 0.0;
  5305. result.m[4] = 0.0;
  5306. result.m[7] = 0.0;
  5307. result.m[8] = 0.0;
  5308. result.m[11] = 0.0;
  5309. result.m[12] = 0.0;
  5310. result.m[13] = 0.0;
  5311. result.m[14] = 0.0;
  5312. result._markAsUpdated();
  5313. };
  5314. /**
  5315. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5316. */
  5317. Matrix.RotationY = function (angle) {
  5318. var result = new Matrix();
  5319. Matrix.RotationYToRef(angle, result);
  5320. return result;
  5321. };
  5322. /**
  5323. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5324. */
  5325. Matrix.RotationYToRef = function (angle, result) {
  5326. var s = Math.sin(angle);
  5327. var c = Math.cos(angle);
  5328. result.m[5] = 1.0;
  5329. result.m[15] = 1.0;
  5330. result.m[0] = c;
  5331. result.m[2] = -s;
  5332. result.m[8] = s;
  5333. result.m[10] = c;
  5334. result.m[1] = 0.0;
  5335. result.m[3] = 0.0;
  5336. result.m[4] = 0.0;
  5337. result.m[6] = 0.0;
  5338. result.m[7] = 0.0;
  5339. result.m[9] = 0.0;
  5340. result.m[11] = 0.0;
  5341. result.m[12] = 0.0;
  5342. result.m[13] = 0.0;
  5343. result.m[14] = 0.0;
  5344. result._markAsUpdated();
  5345. };
  5346. /**
  5347. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5348. */
  5349. Matrix.RotationZ = function (angle) {
  5350. var result = new Matrix();
  5351. Matrix.RotationZToRef(angle, result);
  5352. return result;
  5353. };
  5354. /**
  5355. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5356. */
  5357. Matrix.RotationZToRef = function (angle, result) {
  5358. var s = Math.sin(angle);
  5359. var c = Math.cos(angle);
  5360. result.m[10] = 1.0;
  5361. result.m[15] = 1.0;
  5362. result.m[0] = c;
  5363. result.m[1] = s;
  5364. result.m[4] = -s;
  5365. result.m[5] = c;
  5366. result.m[2] = 0.0;
  5367. result.m[3] = 0.0;
  5368. result.m[6] = 0.0;
  5369. result.m[7] = 0.0;
  5370. result.m[8] = 0.0;
  5371. result.m[9] = 0.0;
  5372. result.m[11] = 0.0;
  5373. result.m[12] = 0.0;
  5374. result.m[13] = 0.0;
  5375. result.m[14] = 0.0;
  5376. result._markAsUpdated();
  5377. };
  5378. /**
  5379. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5380. */
  5381. Matrix.RotationAxis = function (axis, angle) {
  5382. var result = Matrix.Zero();
  5383. Matrix.RotationAxisToRef(axis, angle, result);
  5384. return result;
  5385. };
  5386. /**
  5387. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5388. */
  5389. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5390. var s = Math.sin(-angle);
  5391. var c = Math.cos(-angle);
  5392. var c1 = 1 - c;
  5393. axis.normalize();
  5394. result.m[0] = (axis.x * axis.x) * c1 + c;
  5395. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5396. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5397. result.m[3] = 0.0;
  5398. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5399. result.m[5] = (axis.y * axis.y) * c1 + c;
  5400. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5401. result.m[7] = 0.0;
  5402. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5403. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5404. result.m[10] = (axis.z * axis.z) * c1 + c;
  5405. result.m[11] = 0.0;
  5406. result.m[15] = 1.0;
  5407. result._markAsUpdated();
  5408. };
  5409. /**
  5410. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5411. */
  5412. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5413. var result = new Matrix();
  5414. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5415. return result;
  5416. };
  5417. /**
  5418. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5419. */
  5420. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5421. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5422. this._tempQuaternion.toRotationMatrix(result);
  5423. };
  5424. /**
  5425. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5426. */
  5427. Matrix.Scaling = function (x, y, z) {
  5428. var result = Matrix.Zero();
  5429. Matrix.ScalingToRef(x, y, z, result);
  5430. return result;
  5431. };
  5432. /**
  5433. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5434. */
  5435. Matrix.ScalingToRef = function (x, y, z, result) {
  5436. result.m[0] = x;
  5437. result.m[1] = 0.0;
  5438. result.m[2] = 0.0;
  5439. result.m[3] = 0.0;
  5440. result.m[4] = 0.0;
  5441. result.m[5] = y;
  5442. result.m[6] = 0.0;
  5443. result.m[7] = 0.0;
  5444. result.m[8] = 0.0;
  5445. result.m[9] = 0.0;
  5446. result.m[10] = z;
  5447. result.m[11] = 0.0;
  5448. result.m[12] = 0.0;
  5449. result.m[13] = 0.0;
  5450. result.m[14] = 0.0;
  5451. result.m[15] = 1.0;
  5452. result._markAsUpdated();
  5453. };
  5454. /**
  5455. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5456. */
  5457. Matrix.Translation = function (x, y, z) {
  5458. var result = Matrix.Identity();
  5459. Matrix.TranslationToRef(x, y, z, result);
  5460. return result;
  5461. };
  5462. /**
  5463. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5464. */
  5465. Matrix.TranslationToRef = function (x, y, z, result) {
  5466. 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);
  5467. };
  5468. /**
  5469. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5470. */
  5471. Matrix.Lerp = function (startValue, endValue, gradient) {
  5472. var result = Matrix.Zero();
  5473. for (var index = 0; index < 16; index++) {
  5474. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5475. }
  5476. result._markAsUpdated();
  5477. return result;
  5478. };
  5479. /**
  5480. * Returns a new Matrix whose values are computed by :
  5481. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5482. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5483. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5484. */
  5485. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5486. var startScale = new Vector3(0, 0, 0);
  5487. var startRotation = new Quaternion();
  5488. var startTranslation = new Vector3(0, 0, 0);
  5489. startValue.decompose(startScale, startRotation, startTranslation);
  5490. var endScale = new Vector3(0, 0, 0);
  5491. var endRotation = new Quaternion();
  5492. var endTranslation = new Vector3(0, 0, 0);
  5493. endValue.decompose(endScale, endRotation, endTranslation);
  5494. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5495. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5496. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5497. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5498. };
  5499. /**
  5500. * 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".
  5501. * This methods works for a Left-Handed system.
  5502. */
  5503. Matrix.LookAtLH = function (eye, target, up) {
  5504. var result = Matrix.Zero();
  5505. Matrix.LookAtLHToRef(eye, target, up, result);
  5506. return result;
  5507. };
  5508. /**
  5509. * 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".
  5510. * This methods works for a Left-Handed system.
  5511. */
  5512. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5513. // Z axis
  5514. target.subtractToRef(eye, this._zAxis);
  5515. this._zAxis.normalize();
  5516. // X axis
  5517. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5518. if (this._xAxis.lengthSquared() === 0) {
  5519. this._xAxis.x = 1.0;
  5520. }
  5521. else {
  5522. this._xAxis.normalize();
  5523. }
  5524. // Y axis
  5525. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5526. this._yAxis.normalize();
  5527. // Eye angles
  5528. var ex = -Vector3.Dot(this._xAxis, eye);
  5529. var ey = -Vector3.Dot(this._yAxis, eye);
  5530. var ez = -Vector3.Dot(this._zAxis, eye);
  5531. 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);
  5532. };
  5533. /**
  5534. * 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".
  5535. * This methods works for a Right-Handed system.
  5536. */
  5537. Matrix.LookAtRH = function (eye, target, up) {
  5538. var result = Matrix.Zero();
  5539. Matrix.LookAtRHToRef(eye, target, up, result);
  5540. return result;
  5541. };
  5542. /**
  5543. * 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".
  5544. * This methods works for a Left-Handed system.
  5545. */
  5546. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5547. // Z axis
  5548. eye.subtractToRef(target, this._zAxis);
  5549. this._zAxis.normalize();
  5550. // X axis
  5551. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5552. if (this._xAxis.lengthSquared() === 0) {
  5553. this._xAxis.x = 1.0;
  5554. }
  5555. else {
  5556. this._xAxis.normalize();
  5557. }
  5558. // Y axis
  5559. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5560. this._yAxis.normalize();
  5561. // Eye angles
  5562. var ex = -Vector3.Dot(this._xAxis, eye);
  5563. var ey = -Vector3.Dot(this._yAxis, eye);
  5564. var ez = -Vector3.Dot(this._zAxis, eye);
  5565. 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);
  5566. };
  5567. /**
  5568. * 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.
  5569. */
  5570. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5571. var matrix = Matrix.Zero();
  5572. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5573. return matrix;
  5574. };
  5575. /**
  5576. * 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.
  5577. */
  5578. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5579. var n = znear;
  5580. var f = zfar;
  5581. var a = 2.0 / width;
  5582. var b = 2.0 / height;
  5583. var c = 2.0 / (f - n);
  5584. var d = -(f + n) / (f - n);
  5585. 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);
  5586. };
  5587. /**
  5588. * 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.
  5589. */
  5590. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5591. var matrix = Matrix.Zero();
  5592. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5593. return matrix;
  5594. };
  5595. /**
  5596. * 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.
  5597. */
  5598. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5599. var n = znear;
  5600. var f = zfar;
  5601. var a = 2.0 / (right - left);
  5602. var b = 2.0 / (top - bottom);
  5603. var c = 2.0 / (f - n);
  5604. var d = -(f + n) / (f - n);
  5605. var i0 = (left + right) / (left - right);
  5606. var i1 = (top + bottom) / (bottom - top);
  5607. 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);
  5608. };
  5609. /**
  5610. * 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.
  5611. */
  5612. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5613. var matrix = Matrix.Zero();
  5614. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5615. return matrix;
  5616. };
  5617. /**
  5618. * 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.
  5619. */
  5620. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5621. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5622. result.m[10] *= -1.0;
  5623. };
  5624. /**
  5625. * 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.
  5626. */
  5627. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5628. var matrix = Matrix.Zero();
  5629. var n = znear;
  5630. var f = zfar;
  5631. var a = 2.0 * n / width;
  5632. var b = 2.0 * n / height;
  5633. var c = (f + n) / (f - n);
  5634. var d = -2.0 * f * n / (f - n);
  5635. 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);
  5636. return matrix;
  5637. };
  5638. /**
  5639. * 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.
  5640. */
  5641. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5642. var matrix = Matrix.Zero();
  5643. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5644. return matrix;
  5645. };
  5646. /**
  5647. * 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.
  5648. */
  5649. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5650. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5651. var n = znear;
  5652. var f = zfar;
  5653. var t = 1.0 / (Math.tan(fov * 0.5));
  5654. var a = isVerticalFovFixed ? (t / aspect) : t;
  5655. var b = isVerticalFovFixed ? t : (t * aspect);
  5656. var c = (f + n) / (f - n);
  5657. var d = -2.0 * f * n / (f - n);
  5658. 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);
  5659. };
  5660. /**
  5661. * 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.
  5662. */
  5663. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5664. var matrix = Matrix.Zero();
  5665. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5666. return matrix;
  5667. };
  5668. /**
  5669. * 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.
  5670. */
  5671. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5672. //alternatively this could be expressed as:
  5673. // m = PerspectiveFovLHToRef
  5674. // m[10] *= -1.0;
  5675. // m[11] *= -1.0;
  5676. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5677. var n = znear;
  5678. var f = zfar;
  5679. var t = 1.0 / (Math.tan(fov * 0.5));
  5680. var a = isVerticalFovFixed ? (t / aspect) : t;
  5681. var b = isVerticalFovFixed ? t : (t * aspect);
  5682. var c = -(f + n) / (f - n);
  5683. var d = -2 * f * n / (f - n);
  5684. 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);
  5685. };
  5686. /**
  5687. * 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.
  5688. */
  5689. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5690. if (rightHanded === void 0) { rightHanded = false; }
  5691. var rightHandedFactor = rightHanded ? -1 : 1;
  5692. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5693. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5694. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5695. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5696. var xScale = 2.0 / (leftTan + rightTan);
  5697. var yScale = 2.0 / (upTan + downTan);
  5698. result.m[0] = xScale;
  5699. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5700. result.m[5] = yScale;
  5701. result.m[6] = result.m[7] = 0.0;
  5702. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5703. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5704. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5705. result.m[10] = -zfar / (znear - zfar);
  5706. result.m[11] = 1.0 * rightHandedFactor;
  5707. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5708. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5709. // result.m[14] = (znear * zfar) / (znear - zfar);
  5710. result._markAsUpdated();
  5711. };
  5712. /**
  5713. * Returns the final transformation matrix : world * view * projection * viewport
  5714. */
  5715. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5716. var cw = viewport.width;
  5717. var ch = viewport.height;
  5718. var cx = viewport.x;
  5719. var cy = viewport.y;
  5720. 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);
  5721. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5722. };
  5723. /**
  5724. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5725. */
  5726. Matrix.GetAsMatrix2x2 = function (matrix) {
  5727. return new Float32Array([
  5728. matrix.m[0], matrix.m[1],
  5729. matrix.m[4], matrix.m[5]
  5730. ]);
  5731. };
  5732. /**
  5733. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5734. */
  5735. Matrix.GetAsMatrix3x3 = function (matrix) {
  5736. return new Float32Array([
  5737. matrix.m[0], matrix.m[1], matrix.m[2],
  5738. matrix.m[4], matrix.m[5], matrix.m[6],
  5739. matrix.m[8], matrix.m[9], matrix.m[10]
  5740. ]);
  5741. };
  5742. /**
  5743. * Compute the transpose of the passed Matrix.
  5744. * Returns a new Matrix.
  5745. */
  5746. Matrix.Transpose = function (matrix) {
  5747. var result = new Matrix();
  5748. Matrix.TransposeToRef(matrix, result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5753. */
  5754. Matrix.TransposeToRef = function (matrix, result) {
  5755. result.m[0] = matrix.m[0];
  5756. result.m[1] = matrix.m[4];
  5757. result.m[2] = matrix.m[8];
  5758. result.m[3] = matrix.m[12];
  5759. result.m[4] = matrix.m[1];
  5760. result.m[5] = matrix.m[5];
  5761. result.m[6] = matrix.m[9];
  5762. result.m[7] = matrix.m[13];
  5763. result.m[8] = matrix.m[2];
  5764. result.m[9] = matrix.m[6];
  5765. result.m[10] = matrix.m[10];
  5766. result.m[11] = matrix.m[14];
  5767. result.m[12] = matrix.m[3];
  5768. result.m[13] = matrix.m[7];
  5769. result.m[14] = matrix.m[11];
  5770. result.m[15] = matrix.m[15];
  5771. };
  5772. /**
  5773. * Returns a new Matrix as the reflection matrix across the passed plane.
  5774. */
  5775. Matrix.Reflection = function (plane) {
  5776. var matrix = new Matrix();
  5777. Matrix.ReflectionToRef(plane, matrix);
  5778. return matrix;
  5779. };
  5780. /**
  5781. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5782. */
  5783. Matrix.ReflectionToRef = function (plane, result) {
  5784. plane.normalize();
  5785. var x = plane.normal.x;
  5786. var y = plane.normal.y;
  5787. var z = plane.normal.z;
  5788. var temp = -2 * x;
  5789. var temp2 = -2 * y;
  5790. var temp3 = -2 * z;
  5791. result.m[0] = (temp * x) + 1;
  5792. result.m[1] = temp2 * x;
  5793. result.m[2] = temp3 * x;
  5794. result.m[3] = 0.0;
  5795. result.m[4] = temp * y;
  5796. result.m[5] = (temp2 * y) + 1;
  5797. result.m[6] = temp3 * y;
  5798. result.m[7] = 0.0;
  5799. result.m[8] = temp * z;
  5800. result.m[9] = temp2 * z;
  5801. result.m[10] = (temp3 * z) + 1;
  5802. result.m[11] = 0.0;
  5803. result.m[12] = temp * plane.d;
  5804. result.m[13] = temp2 * plane.d;
  5805. result.m[14] = temp3 * plane.d;
  5806. result.m[15] = 1.0;
  5807. result._markAsUpdated();
  5808. };
  5809. /**
  5810. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5811. */
  5812. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5813. result.m[0] = xaxis.x;
  5814. result.m[1] = xaxis.y;
  5815. result.m[2] = xaxis.z;
  5816. result.m[3] = 0.0;
  5817. result.m[4] = yaxis.x;
  5818. result.m[5] = yaxis.y;
  5819. result.m[6] = yaxis.z;
  5820. result.m[7] = 0.0;
  5821. result.m[8] = zaxis.x;
  5822. result.m[9] = zaxis.y;
  5823. result.m[10] = zaxis.z;
  5824. result.m[11] = 0.0;
  5825. result.m[12] = 0.0;
  5826. result.m[13] = 0.0;
  5827. result.m[14] = 0.0;
  5828. result.m[15] = 1.0;
  5829. result._markAsUpdated();
  5830. };
  5831. /**
  5832. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5833. */
  5834. Matrix.FromQuaternionToRef = function (quat, result) {
  5835. var xx = quat.x * quat.x;
  5836. var yy = quat.y * quat.y;
  5837. var zz = quat.z * quat.z;
  5838. var xy = quat.x * quat.y;
  5839. var zw = quat.z * quat.w;
  5840. var zx = quat.z * quat.x;
  5841. var yw = quat.y * quat.w;
  5842. var yz = quat.y * quat.z;
  5843. var xw = quat.x * quat.w;
  5844. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5845. result.m[1] = 2.0 * (xy + zw);
  5846. result.m[2] = 2.0 * (zx - yw);
  5847. result.m[3] = 0.0;
  5848. result.m[4] = 2.0 * (xy - zw);
  5849. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5850. result.m[6] = 2.0 * (yz + xw);
  5851. result.m[7] = 0.0;
  5852. result.m[8] = 2.0 * (zx + yw);
  5853. result.m[9] = 2.0 * (yz - xw);
  5854. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5855. result.m[11] = 0.0;
  5856. result.m[12] = 0.0;
  5857. result.m[13] = 0.0;
  5858. result.m[14] = 0.0;
  5859. result.m[15] = 1.0;
  5860. result._markAsUpdated();
  5861. };
  5862. Matrix._tempQuaternion = new Quaternion();
  5863. Matrix._xAxis = Vector3.Zero();
  5864. Matrix._yAxis = Vector3.Zero();
  5865. Matrix._zAxis = Vector3.Zero();
  5866. Matrix._updateFlagSeed = 0;
  5867. Matrix._identityReadOnly = Matrix.Identity();
  5868. return Matrix;
  5869. }());
  5870. BABYLON.Matrix = Matrix;
  5871. var Plane = /** @class */ (function () {
  5872. /**
  5873. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5874. */
  5875. function Plane(a, b, c, d) {
  5876. this.normal = new Vector3(a, b, c);
  5877. this.d = d;
  5878. }
  5879. /**
  5880. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5881. */
  5882. Plane.prototype.asArray = function () {
  5883. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5884. };
  5885. // Methods
  5886. /**
  5887. * Returns a new plane copied from the current Plane.
  5888. */
  5889. Plane.prototype.clone = function () {
  5890. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5891. };
  5892. /**
  5893. * Returns the string "Plane".
  5894. */
  5895. Plane.prototype.getClassName = function () {
  5896. return "Plane";
  5897. };
  5898. /**
  5899. * Returns the Plane hash code.
  5900. */
  5901. Plane.prototype.getHashCode = function () {
  5902. var hash = this.normal.getHashCode();
  5903. hash = (hash * 397) ^ (this.d || 0);
  5904. return hash;
  5905. };
  5906. /**
  5907. * Normalize the current Plane in place.
  5908. * Returns the updated Plane.
  5909. */
  5910. Plane.prototype.normalize = function () {
  5911. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5912. var magnitude = 0.0;
  5913. if (norm !== 0) {
  5914. magnitude = 1.0 / norm;
  5915. }
  5916. this.normal.x *= magnitude;
  5917. this.normal.y *= magnitude;
  5918. this.normal.z *= magnitude;
  5919. this.d *= magnitude;
  5920. return this;
  5921. };
  5922. /**
  5923. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5924. */
  5925. Plane.prototype.transform = function (transformation) {
  5926. var transposedMatrix = Matrix.Transpose(transformation);
  5927. var x = this.normal.x;
  5928. var y = this.normal.y;
  5929. var z = this.normal.z;
  5930. var d = this.d;
  5931. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5932. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5933. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5934. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5935. return new Plane(normalX, normalY, normalZ, finalD);
  5936. };
  5937. /**
  5938. * Returns the dot product (float) of the point coordinates and the plane normal.
  5939. */
  5940. Plane.prototype.dotCoordinate = function (point) {
  5941. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5942. };
  5943. /**
  5944. * Updates the current Plane from the plane defined by the three passed points.
  5945. * Returns the updated Plane.
  5946. */
  5947. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5948. var x1 = point2.x - point1.x;
  5949. var y1 = point2.y - point1.y;
  5950. var z1 = point2.z - point1.z;
  5951. var x2 = point3.x - point1.x;
  5952. var y2 = point3.y - point1.y;
  5953. var z2 = point3.z - point1.z;
  5954. var yz = (y1 * z2) - (z1 * y2);
  5955. var xz = (z1 * x2) - (x1 * z2);
  5956. var xy = (x1 * y2) - (y1 * x2);
  5957. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5958. var invPyth;
  5959. if (pyth !== 0) {
  5960. invPyth = 1.0 / pyth;
  5961. }
  5962. else {
  5963. invPyth = 0.0;
  5964. }
  5965. this.normal.x = yz * invPyth;
  5966. this.normal.y = xz * invPyth;
  5967. this.normal.z = xy * invPyth;
  5968. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5969. return this;
  5970. };
  5971. /**
  5972. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5973. */
  5974. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5975. var dot = Vector3.Dot(this.normal, direction);
  5976. return (dot <= epsilon);
  5977. };
  5978. /**
  5979. * Returns the signed distance (float) from the passed point to the Plane.
  5980. */
  5981. Plane.prototype.signedDistanceTo = function (point) {
  5982. return Vector3.Dot(point, this.normal) + this.d;
  5983. };
  5984. // Statics
  5985. /**
  5986. * Returns a new Plane from the passed array.
  5987. */
  5988. Plane.FromArray = function (array) {
  5989. return new Plane(array[0], array[1], array[2], array[3]);
  5990. };
  5991. /**
  5992. * Returns a new Plane defined by the three passed points.
  5993. */
  5994. Plane.FromPoints = function (point1, point2, point3) {
  5995. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5996. result.copyFromPoints(point1, point2, point3);
  5997. return result;
  5998. };
  5999. /**
  6000. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6001. * Note : the vector "normal" is updated because normalized.
  6002. */
  6003. Plane.FromPositionAndNormal = function (origin, normal) {
  6004. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6005. normal.normalize();
  6006. result.normal = normal;
  6007. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6008. return result;
  6009. };
  6010. /**
  6011. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6012. */
  6013. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6014. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6015. return Vector3.Dot(point, normal) + d;
  6016. };
  6017. return Plane;
  6018. }());
  6019. BABYLON.Plane = Plane;
  6020. var Viewport = /** @class */ (function () {
  6021. /**
  6022. * Creates a Viewport object located at (x, y) and sized (width, height).
  6023. */
  6024. function Viewport(x, y, width, height) {
  6025. this.x = x;
  6026. this.y = y;
  6027. this.width = width;
  6028. this.height = height;
  6029. }
  6030. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6031. if (renderWidthOrEngine.getRenderWidth) {
  6032. var engine = renderWidthOrEngine;
  6033. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6034. }
  6035. var renderWidth = renderWidthOrEngine;
  6036. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6037. };
  6038. /**
  6039. * Returns a new Viewport copied from the current one.
  6040. */
  6041. Viewport.prototype.clone = function () {
  6042. return new Viewport(this.x, this.y, this.width, this.height);
  6043. };
  6044. return Viewport;
  6045. }());
  6046. BABYLON.Viewport = Viewport;
  6047. var Frustum = /** @class */ (function () {
  6048. function Frustum() {
  6049. }
  6050. /**
  6051. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6052. */
  6053. Frustum.GetPlanes = function (transform) {
  6054. var frustumPlanes = [];
  6055. for (var index = 0; index < 6; index++) {
  6056. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6057. }
  6058. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6059. return frustumPlanes;
  6060. };
  6061. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6062. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6063. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6064. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6065. frustumPlane.d = transform.m[15] + transform.m[14];
  6066. frustumPlane.normalize();
  6067. };
  6068. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6069. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6070. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6071. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6072. frustumPlane.d = transform.m[15] - transform.m[14];
  6073. frustumPlane.normalize();
  6074. };
  6075. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6076. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6077. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6078. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6079. frustumPlane.d = transform.m[15] + transform.m[12];
  6080. frustumPlane.normalize();
  6081. };
  6082. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6083. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6084. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6085. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6086. frustumPlane.d = transform.m[15] - transform.m[12];
  6087. frustumPlane.normalize();
  6088. };
  6089. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6090. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6091. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6092. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6093. frustumPlane.d = transform.m[15] - transform.m[13];
  6094. frustumPlane.normalize();
  6095. };
  6096. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6097. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6098. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6099. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6100. frustumPlane.d = transform.m[15] + transform.m[13];
  6101. frustumPlane.normalize();
  6102. };
  6103. /**
  6104. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6105. */
  6106. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6107. // Near
  6108. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6109. // Far
  6110. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6111. // Left
  6112. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6113. // Right
  6114. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6115. // Top
  6116. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6117. // Bottom
  6118. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6119. };
  6120. return Frustum;
  6121. }());
  6122. BABYLON.Frustum = Frustum;
  6123. var Space;
  6124. (function (Space) {
  6125. Space[Space["LOCAL"] = 0] = "LOCAL";
  6126. Space[Space["WORLD"] = 1] = "WORLD";
  6127. Space[Space["BONE"] = 2] = "BONE";
  6128. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6129. var Axis = /** @class */ (function () {
  6130. function Axis() {
  6131. }
  6132. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6133. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6134. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6135. return Axis;
  6136. }());
  6137. BABYLON.Axis = Axis;
  6138. ;
  6139. var BezierCurve = /** @class */ (function () {
  6140. function BezierCurve() {
  6141. }
  6142. /**
  6143. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6144. */
  6145. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6146. // Extract X (which is equal to time here)
  6147. var f0 = 1 - 3 * x2 + 3 * x1;
  6148. var f1 = 3 * x2 - 6 * x1;
  6149. var f2 = 3 * x1;
  6150. var refinedT = t;
  6151. for (var i = 0; i < 5; i++) {
  6152. var refinedT2 = refinedT * refinedT;
  6153. var refinedT3 = refinedT2 * refinedT;
  6154. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6155. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6156. refinedT -= (x - t) * slope;
  6157. refinedT = Math.min(1, Math.max(0, refinedT));
  6158. }
  6159. // Resolve cubic bezier for the given x
  6160. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6161. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6162. Math.pow(refinedT, 3);
  6163. };
  6164. return BezierCurve;
  6165. }());
  6166. BABYLON.BezierCurve = BezierCurve;
  6167. var Orientation;
  6168. (function (Orientation) {
  6169. Orientation[Orientation["CW"] = 0] = "CW";
  6170. Orientation[Orientation["CCW"] = 1] = "CCW";
  6171. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6172. var Angle = /** @class */ (function () {
  6173. /**
  6174. * Creates an Angle object of "radians" radians (float).
  6175. */
  6176. function Angle(radians) {
  6177. var _this = this;
  6178. /**
  6179. * Returns the Angle value in degrees (float).
  6180. */
  6181. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6182. /**
  6183. * Returns the Angle value in radians (float).
  6184. */
  6185. this.radians = function () { return _this._radians; };
  6186. this._radians = radians;
  6187. if (this._radians < 0.0)
  6188. this._radians += (2.0 * Math.PI);
  6189. }
  6190. /**
  6191. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6192. */
  6193. Angle.BetweenTwoPoints = function (a, b) {
  6194. var delta = b.subtract(a);
  6195. var theta = Math.atan2(delta.y, delta.x);
  6196. return new Angle(theta);
  6197. };
  6198. /**
  6199. * Returns a new Angle object from the passed float in radians.
  6200. */
  6201. Angle.FromRadians = function (radians) {
  6202. return new Angle(radians);
  6203. };
  6204. /**
  6205. * Returns a new Angle object from the passed float in degrees.
  6206. */
  6207. Angle.FromDegrees = function (degrees) {
  6208. return new Angle(degrees * Math.PI / 180.0);
  6209. };
  6210. return Angle;
  6211. }());
  6212. BABYLON.Angle = Angle;
  6213. var Arc2 = /** @class */ (function () {
  6214. /**
  6215. * Creates an Arc object from the three passed points : start, middle and end.
  6216. */
  6217. function Arc2(startPoint, midPoint, endPoint) {
  6218. this.startPoint = startPoint;
  6219. this.midPoint = midPoint;
  6220. this.endPoint = endPoint;
  6221. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6222. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6223. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6224. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6225. 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);
  6226. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6227. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6228. var a1 = this.startAngle.degrees();
  6229. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6230. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6231. // angles correction
  6232. if (a2 - a1 > +180.0)
  6233. a2 -= 360.0;
  6234. if (a2 - a1 < -180.0)
  6235. a2 += 360.0;
  6236. if (a3 - a2 > +180.0)
  6237. a3 -= 360.0;
  6238. if (a3 - a2 < -180.0)
  6239. a3 += 360.0;
  6240. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6241. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6242. }
  6243. return Arc2;
  6244. }());
  6245. BABYLON.Arc2 = Arc2;
  6246. var Path2 = /** @class */ (function () {
  6247. /**
  6248. * Creates a Path2 object from the starting 2D coordinates x and y.
  6249. */
  6250. function Path2(x, y) {
  6251. this._points = new Array();
  6252. this._length = 0.0;
  6253. this.closed = false;
  6254. this._points.push(new Vector2(x, y));
  6255. }
  6256. /**
  6257. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6258. * Returns the updated Path2.
  6259. */
  6260. Path2.prototype.addLineTo = function (x, y) {
  6261. if (this.closed) {
  6262. //Tools.Error("cannot add lines to closed paths");
  6263. return this;
  6264. }
  6265. var newPoint = new Vector2(x, y);
  6266. var previousPoint = this._points[this._points.length - 1];
  6267. this._points.push(newPoint);
  6268. this._length += newPoint.subtract(previousPoint).length();
  6269. return this;
  6270. };
  6271. /**
  6272. * 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.
  6273. * Returns the updated Path2.
  6274. */
  6275. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6276. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6277. if (this.closed) {
  6278. //Tools.Error("cannot add arcs to closed paths");
  6279. return this;
  6280. }
  6281. var startPoint = this._points[this._points.length - 1];
  6282. var midPoint = new Vector2(midX, midY);
  6283. var endPoint = new Vector2(endX, endY);
  6284. var arc = new Arc2(startPoint, midPoint, endPoint);
  6285. var increment = arc.angle.radians() / numberOfSegments;
  6286. if (arc.orientation === Orientation.CW)
  6287. increment *= -1;
  6288. var currentAngle = arc.startAngle.radians() + increment;
  6289. for (var i = 0; i < numberOfSegments; i++) {
  6290. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6291. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6292. this.addLineTo(x, y);
  6293. currentAngle += increment;
  6294. }
  6295. return this;
  6296. };
  6297. /**
  6298. * Closes the Path2.
  6299. * Returns the Path2.
  6300. */
  6301. Path2.prototype.close = function () {
  6302. this.closed = true;
  6303. return this;
  6304. };
  6305. /**
  6306. * Returns the Path2 total length (float).
  6307. */
  6308. Path2.prototype.length = function () {
  6309. var result = this._length;
  6310. if (!this.closed) {
  6311. var lastPoint = this._points[this._points.length - 1];
  6312. var firstPoint = this._points[0];
  6313. result += (firstPoint.subtract(lastPoint).length());
  6314. }
  6315. return result;
  6316. };
  6317. /**
  6318. * Returns the Path2 internal array of points.
  6319. */
  6320. Path2.prototype.getPoints = function () {
  6321. return this._points;
  6322. };
  6323. /**
  6324. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6325. */
  6326. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6327. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6328. //Tools.Error("normalized length position should be between 0 and 1.");
  6329. return Vector2.Zero();
  6330. }
  6331. var lengthPosition = normalizedLengthPosition * this.length();
  6332. var previousOffset = 0;
  6333. for (var i = 0; i < this._points.length; i++) {
  6334. var j = (i + 1) % this._points.length;
  6335. var a = this._points[i];
  6336. var b = this._points[j];
  6337. var bToA = b.subtract(a);
  6338. var nextOffset = (bToA.length() + previousOffset);
  6339. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6340. var dir = bToA.normalize();
  6341. var localOffset = lengthPosition - previousOffset;
  6342. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6343. }
  6344. previousOffset = nextOffset;
  6345. }
  6346. //Tools.Error("internal error");
  6347. return Vector2.Zero();
  6348. };
  6349. /**
  6350. * Returns a new Path2 starting at the coordinates (x, y).
  6351. */
  6352. Path2.StartingAt = function (x, y) {
  6353. return new Path2(x, y);
  6354. };
  6355. return Path2;
  6356. }());
  6357. BABYLON.Path2 = Path2;
  6358. var Path3D = /** @class */ (function () {
  6359. /**
  6360. * new Path3D(path, normal, raw)
  6361. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6362. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6363. * path : an array of Vector3, the curve axis of the Path3D
  6364. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6365. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6366. */
  6367. function Path3D(path, firstNormal, raw) {
  6368. if (firstNormal === void 0) { firstNormal = null; }
  6369. this.path = path;
  6370. this._curve = new Array();
  6371. this._distances = new Array();
  6372. this._tangents = new Array();
  6373. this._normals = new Array();
  6374. this._binormals = new Array();
  6375. for (var p = 0; p < path.length; p++) {
  6376. this._curve[p] = path[p].clone(); // hard copy
  6377. }
  6378. this._raw = raw || false;
  6379. this._compute(firstNormal);
  6380. }
  6381. /**
  6382. * Returns the Path3D array of successive Vector3 designing its curve.
  6383. */
  6384. Path3D.prototype.getCurve = function () {
  6385. return this._curve;
  6386. };
  6387. /**
  6388. * Returns an array populated with tangent vectors on each Path3D curve point.
  6389. */
  6390. Path3D.prototype.getTangents = function () {
  6391. return this._tangents;
  6392. };
  6393. /**
  6394. * Returns an array populated with normal vectors on each Path3D curve point.
  6395. */
  6396. Path3D.prototype.getNormals = function () {
  6397. return this._normals;
  6398. };
  6399. /**
  6400. * Returns an array populated with binormal vectors on each Path3D curve point.
  6401. */
  6402. Path3D.prototype.getBinormals = function () {
  6403. return this._binormals;
  6404. };
  6405. /**
  6406. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6407. */
  6408. Path3D.prototype.getDistances = function () {
  6409. return this._distances;
  6410. };
  6411. /**
  6412. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6413. * Returns the same object updated.
  6414. */
  6415. Path3D.prototype.update = function (path, firstNormal) {
  6416. if (firstNormal === void 0) { firstNormal = null; }
  6417. for (var p = 0; p < path.length; p++) {
  6418. this._curve[p].x = path[p].x;
  6419. this._curve[p].y = path[p].y;
  6420. this._curve[p].z = path[p].z;
  6421. }
  6422. this._compute(firstNormal);
  6423. return this;
  6424. };
  6425. // private function compute() : computes tangents, normals and binormals
  6426. Path3D.prototype._compute = function (firstNormal) {
  6427. var l = this._curve.length;
  6428. // first and last tangents
  6429. this._tangents[0] = this._getFirstNonNullVector(0);
  6430. if (!this._raw) {
  6431. this._tangents[0].normalize();
  6432. }
  6433. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6434. if (!this._raw) {
  6435. this._tangents[l - 1].normalize();
  6436. }
  6437. // normals and binormals at first point : arbitrary vector with _normalVector()
  6438. var tg0 = this._tangents[0];
  6439. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6440. this._normals[0] = pp0;
  6441. if (!this._raw) {
  6442. this._normals[0].normalize();
  6443. }
  6444. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6445. if (!this._raw) {
  6446. this._binormals[0].normalize();
  6447. }
  6448. this._distances[0] = 0.0;
  6449. // normals and binormals : next points
  6450. var prev; // previous vector (segment)
  6451. var cur; // current vector (segment)
  6452. var curTang; // current tangent
  6453. // previous normal
  6454. var prevBinor; // previous binormal
  6455. for (var i = 1; i < l; i++) {
  6456. // tangents
  6457. prev = this._getLastNonNullVector(i);
  6458. if (i < l - 1) {
  6459. cur = this._getFirstNonNullVector(i);
  6460. this._tangents[i] = prev.add(cur);
  6461. this._tangents[i].normalize();
  6462. }
  6463. this._distances[i] = this._distances[i - 1] + prev.length();
  6464. // normals and binormals
  6465. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6466. curTang = this._tangents[i];
  6467. prevBinor = this._binormals[i - 1];
  6468. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6469. if (!this._raw) {
  6470. this._normals[i].normalize();
  6471. }
  6472. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6473. if (!this._raw) {
  6474. this._binormals[i].normalize();
  6475. }
  6476. }
  6477. };
  6478. // private function getFirstNonNullVector(index)
  6479. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6480. Path3D.prototype._getFirstNonNullVector = function (index) {
  6481. var i = 1;
  6482. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6483. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6484. i++;
  6485. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6486. }
  6487. return nNVector;
  6488. };
  6489. // private function getLastNonNullVector(index)
  6490. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6491. Path3D.prototype._getLastNonNullVector = function (index) {
  6492. var i = 1;
  6493. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6494. while (nLVector.length() === 0 && index > i + 1) {
  6495. i++;
  6496. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6497. }
  6498. return nLVector;
  6499. };
  6500. // private function normalVector(v0, vt, va) :
  6501. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6502. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6503. Path3D.prototype._normalVector = function (v0, vt, va) {
  6504. var normal0;
  6505. var tgl = vt.length();
  6506. if (tgl === 0.0) {
  6507. tgl = 1.0;
  6508. }
  6509. if (va === undefined || va === null) {
  6510. var point;
  6511. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6512. point = new Vector3(0.0, -1.0, 0.0);
  6513. }
  6514. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6515. point = new Vector3(1.0, 0.0, 0.0);
  6516. }
  6517. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6518. point = new Vector3(0.0, 0.0, 1.0);
  6519. }
  6520. else {
  6521. point = Vector3.Zero();
  6522. }
  6523. normal0 = Vector3.Cross(vt, point);
  6524. }
  6525. else {
  6526. normal0 = Vector3.Cross(vt, va);
  6527. Vector3.CrossToRef(normal0, vt, normal0);
  6528. }
  6529. normal0.normalize();
  6530. return normal0;
  6531. };
  6532. return Path3D;
  6533. }());
  6534. BABYLON.Path3D = Path3D;
  6535. var Curve3 = /** @class */ (function () {
  6536. /**
  6537. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6538. * A Curve3 is designed from a series of successive Vector3.
  6539. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6540. */
  6541. function Curve3(points) {
  6542. this._length = 0.0;
  6543. this._points = points;
  6544. this._length = this._computeLength(points);
  6545. }
  6546. /**
  6547. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6548. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6549. * @param v1 (Vector3) the control point
  6550. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6551. * @param nbPoints (integer) the wanted number of points in the curve
  6552. */
  6553. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6554. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6555. var bez = new Array();
  6556. var equation = function (t, val0, val1, val2) {
  6557. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6558. return res;
  6559. };
  6560. for (var i = 0; i <= nbPoints; i++) {
  6561. 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)));
  6562. }
  6563. return new Curve3(bez);
  6564. };
  6565. /**
  6566. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6567. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6568. * @param v1 (Vector3) the first control point
  6569. * @param v2 (Vector3) the second control point
  6570. * @param v3 (Vector3) the end point of the Cubic Bezier
  6571. * @param nbPoints (integer) the wanted number of points in the curve
  6572. */
  6573. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6574. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6575. var bez = new Array();
  6576. var equation = function (t, val0, val1, val2, val3) {
  6577. 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;
  6578. return res;
  6579. };
  6580. for (var i = 0; i <= nbPoints; i++) {
  6581. 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)));
  6582. }
  6583. return new Curve3(bez);
  6584. };
  6585. /**
  6586. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6587. * @param p1 (Vector3) the origin point of the Hermite Spline
  6588. * @param t1 (Vector3) the tangent vector at the origin point
  6589. * @param p2 (Vector3) the end point of the Hermite Spline
  6590. * @param t2 (Vector3) the tangent vector at the end point
  6591. * @param nbPoints (integer) the wanted number of points in the curve
  6592. */
  6593. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6594. var hermite = new Array();
  6595. var step = 1.0 / nbPoints;
  6596. for (var i = 0; i <= nbPoints; i++) {
  6597. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6598. }
  6599. return new Curve3(hermite);
  6600. };
  6601. /**
  6602. * Returns a Curve3 object along a CatmullRom Spline curve :
  6603. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6604. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6605. */
  6606. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6607. var totalPoints = new Array();
  6608. totalPoints.push(points[0].clone());
  6609. Array.prototype.push.apply(totalPoints, points);
  6610. totalPoints.push(points[points.length - 1].clone());
  6611. var catmullRom = new Array();
  6612. var step = 1.0 / nbPoints;
  6613. var amount = 0.0;
  6614. for (var i = 0; i < totalPoints.length - 3; i++) {
  6615. amount = 0;
  6616. for (var c = 0; c < nbPoints; c++) {
  6617. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6618. amount += step;
  6619. }
  6620. }
  6621. i--;
  6622. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6623. return new Curve3(catmullRom);
  6624. };
  6625. /**
  6626. * Returns the Curve3 stored array of successive Vector3
  6627. */
  6628. Curve3.prototype.getPoints = function () {
  6629. return this._points;
  6630. };
  6631. /**
  6632. * Returns the computed length (float) of the curve.
  6633. */
  6634. Curve3.prototype.length = function () {
  6635. return this._length;
  6636. };
  6637. /**
  6638. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6639. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6640. * curveA and curveB keep unchanged.
  6641. */
  6642. Curve3.prototype.continue = function (curve) {
  6643. var lastPoint = this._points[this._points.length - 1];
  6644. var continuedPoints = this._points.slice();
  6645. var curvePoints = curve.getPoints();
  6646. for (var i = 1; i < curvePoints.length; i++) {
  6647. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6648. }
  6649. var continuedCurve = new Curve3(continuedPoints);
  6650. return continuedCurve;
  6651. };
  6652. Curve3.prototype._computeLength = function (path) {
  6653. var l = 0;
  6654. for (var i = 1; i < path.length; i++) {
  6655. l += (path[i].subtract(path[i - 1])).length();
  6656. }
  6657. return l;
  6658. };
  6659. return Curve3;
  6660. }());
  6661. BABYLON.Curve3 = Curve3;
  6662. // Vertex formats
  6663. var PositionNormalVertex = /** @class */ (function () {
  6664. function PositionNormalVertex(position, normal) {
  6665. if (position === void 0) { position = Vector3.Zero(); }
  6666. if (normal === void 0) { normal = Vector3.Up(); }
  6667. this.position = position;
  6668. this.normal = normal;
  6669. }
  6670. PositionNormalVertex.prototype.clone = function () {
  6671. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6672. };
  6673. return PositionNormalVertex;
  6674. }());
  6675. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6676. var PositionNormalTextureVertex = /** @class */ (function () {
  6677. function PositionNormalTextureVertex(position, normal, uv) {
  6678. if (position === void 0) { position = Vector3.Zero(); }
  6679. if (normal === void 0) { normal = Vector3.Up(); }
  6680. if (uv === void 0) { uv = Vector2.Zero(); }
  6681. this.position = position;
  6682. this.normal = normal;
  6683. this.uv = uv;
  6684. }
  6685. PositionNormalTextureVertex.prototype.clone = function () {
  6686. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6687. };
  6688. return PositionNormalTextureVertex;
  6689. }());
  6690. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6691. // Temporary pre-allocated objects for engine internal use
  6692. // usage in any internal function :
  6693. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6694. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6695. var Tmp = /** @class */ (function () {
  6696. function Tmp() {
  6697. }
  6698. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6699. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6700. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6701. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6702. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6703. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6704. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6705. Matrix.Zero(), Matrix.Zero(),
  6706. Matrix.Zero(), Matrix.Zero(),
  6707. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6708. return Tmp;
  6709. }());
  6710. BABYLON.Tmp = Tmp;
  6711. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6712. var MathTmp = /** @class */ (function () {
  6713. function MathTmp() {
  6714. }
  6715. MathTmp.Vector3 = [Vector3.Zero()];
  6716. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6717. MathTmp.Quaternion = [Quaternion.Zero()];
  6718. return MathTmp;
  6719. }());
  6720. })(BABYLON || (BABYLON = {}));
  6721. //# sourceMappingURL=babylon.math.js.map
  6722. var BABYLON;
  6723. (function (BABYLON) {
  6724. var Scalar = /** @class */ (function () {
  6725. function Scalar() {
  6726. }
  6727. /**
  6728. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6729. */
  6730. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6731. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6732. var num = a - b;
  6733. return -epsilon <= num && num <= epsilon;
  6734. };
  6735. /**
  6736. * Returns a string : the upper case translation of the number i to hexadecimal.
  6737. */
  6738. Scalar.ToHex = function (i) {
  6739. var str = i.toString(16);
  6740. if (i <= 15) {
  6741. return ("0" + str).toUpperCase();
  6742. }
  6743. return str.toUpperCase();
  6744. };
  6745. /**
  6746. * Returns -1 if value is negative and +1 is value is positive.
  6747. * Returns the value itself if it's equal to zero.
  6748. */
  6749. Scalar.Sign = function (value) {
  6750. value = +value; // convert to a number
  6751. if (value === 0 || isNaN(value))
  6752. return value;
  6753. return value > 0 ? 1 : -1;
  6754. };
  6755. /**
  6756. * Returns the value itself if it's between min and max.
  6757. * Returns min if the value is lower than min.
  6758. * Returns max if the value is greater than max.
  6759. */
  6760. Scalar.Clamp = function (value, min, max) {
  6761. if (min === void 0) { min = 0; }
  6762. if (max === void 0) { max = 1; }
  6763. return Math.min(max, Math.max(min, value));
  6764. };
  6765. /**
  6766. * Returns the log2 of value.
  6767. */
  6768. Scalar.Log2 = function (value) {
  6769. return Math.log(value) * Math.LOG2E;
  6770. };
  6771. /**
  6772. * Loops the value, so that it is never larger than length and never smaller than 0.
  6773. *
  6774. * This is similar to the modulo operator but it works with floating point numbers.
  6775. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6776. * With t = 5 and length = 2.5, the result would be 0.0.
  6777. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6778. */
  6779. Scalar.Repeat = function (value, length) {
  6780. return value - Math.floor(value / length) * length;
  6781. };
  6782. /**
  6783. * Normalize the value between 0.0 and 1.0 using min and max values
  6784. */
  6785. Scalar.Normalize = function (value, min, max) {
  6786. return (value - min) / (max - min);
  6787. };
  6788. /**
  6789. * Denormalize the value from 0.0 and 1.0 using min and max values
  6790. */
  6791. Scalar.Denormalize = function (normalized, min, max) {
  6792. return (normalized * (max - min) + min);
  6793. };
  6794. /**
  6795. * Calculates the shortest difference between two given angles given in degrees.
  6796. */
  6797. Scalar.DeltaAngle = function (current, target) {
  6798. var num = Scalar.Repeat(target - current, 360.0);
  6799. if (num > 180.0) {
  6800. num -= 360.0;
  6801. }
  6802. return num;
  6803. };
  6804. /**
  6805. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6806. *
  6807. * The returned value will move back and forth between 0 and length
  6808. */
  6809. Scalar.PingPong = function (tx, length) {
  6810. var t = Scalar.Repeat(tx, length * 2.0);
  6811. return length - Math.abs(t - length);
  6812. };
  6813. /**
  6814. * Interpolates between min and max with smoothing at the limits.
  6815. *
  6816. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6817. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6818. */
  6819. Scalar.SmoothStep = function (from, to, tx) {
  6820. var t = Scalar.Clamp(tx);
  6821. t = -2.0 * t * t * t + 3.0 * t * t;
  6822. return to * t + from * (1.0 - t);
  6823. };
  6824. /**
  6825. * Moves a value current towards target.
  6826. *
  6827. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6828. * Negative values of maxDelta pushes the value away from target.
  6829. */
  6830. Scalar.MoveTowards = function (current, target, maxDelta) {
  6831. var result = 0;
  6832. if (Math.abs(target - current) <= maxDelta) {
  6833. result = target;
  6834. }
  6835. else {
  6836. result = current + Scalar.Sign(target - current) * maxDelta;
  6837. }
  6838. return result;
  6839. };
  6840. /**
  6841. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6842. *
  6843. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6844. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6845. */
  6846. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6847. var num = Scalar.DeltaAngle(current, target);
  6848. var result = 0;
  6849. if (-maxDelta < num && num < maxDelta) {
  6850. result = target;
  6851. }
  6852. else {
  6853. target = current + num;
  6854. result = Scalar.MoveTowards(current, target, maxDelta);
  6855. }
  6856. return result;
  6857. };
  6858. /**
  6859. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6860. */
  6861. Scalar.Lerp = function (start, end, amount) {
  6862. return start + ((end - start) * amount);
  6863. };
  6864. /**
  6865. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6866. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6867. */
  6868. Scalar.LerpAngle = function (start, end, amount) {
  6869. var num = Scalar.Repeat(end - start, 360.0);
  6870. if (num > 180.0) {
  6871. num -= 360.0;
  6872. }
  6873. return start + num * Scalar.Clamp(amount);
  6874. };
  6875. /**
  6876. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6877. */
  6878. Scalar.InverseLerp = function (a, b, value) {
  6879. var result = 0;
  6880. if (a != b) {
  6881. result = Scalar.Clamp((value - a) / (b - a));
  6882. }
  6883. else {
  6884. result = 0.0;
  6885. }
  6886. return result;
  6887. };
  6888. /**
  6889. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6890. */
  6891. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6892. var squared = amount * amount;
  6893. var cubed = amount * squared;
  6894. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6895. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6896. var part3 = (cubed - (2.0 * squared)) + amount;
  6897. var part4 = cubed - squared;
  6898. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6899. };
  6900. /**
  6901. * Returns a random float number between and min and max values
  6902. */
  6903. Scalar.RandomRange = function (min, max) {
  6904. if (min === max)
  6905. return min;
  6906. return ((Math.random() * (max - min)) + min);
  6907. };
  6908. /**
  6909. * This function returns percentage of a number in a given range.
  6910. *
  6911. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6912. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6913. */
  6914. Scalar.RangeToPercent = function (number, min, max) {
  6915. return ((number - min) / (max - min));
  6916. };
  6917. /**
  6918. * This function returns number that corresponds to the percentage in a given range.
  6919. *
  6920. * PercentToRange(0.34,0,100) will return 34.
  6921. */
  6922. Scalar.PercentToRange = function (percent, min, max) {
  6923. return ((max - min) * percent + min);
  6924. };
  6925. /**
  6926. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6927. * @param angle The angle to normalize in radian.
  6928. * @return The converted angle.
  6929. */
  6930. Scalar.NormalizeRadians = function (angle) {
  6931. // More precise but slower version kept for reference.
  6932. // angle = angle % Tools.TwoPi;
  6933. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6934. //if (angle > Math.PI) {
  6935. // angle -= Tools.TwoPi;
  6936. //}
  6937. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6938. return angle;
  6939. };
  6940. /**
  6941. * Two pi constants convenient for computation.
  6942. */
  6943. Scalar.TwoPi = Math.PI * 2;
  6944. return Scalar;
  6945. }());
  6946. BABYLON.Scalar = Scalar;
  6947. })(BABYLON || (BABYLON = {}));
  6948. //# sourceMappingURL=babylon.math.scalar.js.map
  6949. //# sourceMappingURL=babylon.mixins.js.map
  6950. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6951. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6952. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6953. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6954. //# sourceMappingURL=babylon.webgl2.js.map
  6955. var BABYLON;
  6956. (function (BABYLON) {
  6957. var __decoratorInitialStore = {};
  6958. var __mergedStore = {};
  6959. var _copySource = function (creationFunction, source, instanciate) {
  6960. var destination = creationFunction();
  6961. // Tags
  6962. if (BABYLON.Tags) {
  6963. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6964. }
  6965. var classStore = getMergedStore(destination);
  6966. // Properties
  6967. for (var property in classStore) {
  6968. var propertyDescriptor = classStore[property];
  6969. var sourceProperty = source[property];
  6970. var propertyType = propertyDescriptor.type;
  6971. if (sourceProperty !== undefined && sourceProperty !== null) {
  6972. switch (propertyType) {
  6973. case 0: // Value
  6974. case 6:// Mesh reference
  6975. destination[property] = sourceProperty;
  6976. break;
  6977. case 1:// Texture
  6978. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6979. break;
  6980. case 2: // Color3
  6981. case 3: // FresnelParameters
  6982. case 4: // Vector2
  6983. case 5: // Vector3
  6984. case 7: // Color Curves
  6985. case 10:// Quaternion
  6986. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6987. break;
  6988. }
  6989. }
  6990. }
  6991. return destination;
  6992. };
  6993. function getDirectStore(target) {
  6994. var classKey = target.getClassName();
  6995. if (!__decoratorInitialStore[classKey]) {
  6996. __decoratorInitialStore[classKey] = {};
  6997. }
  6998. return __decoratorInitialStore[classKey];
  6999. }
  7000. /**
  7001. * Return the list of properties flagged as serializable
  7002. * @param target: host object
  7003. */
  7004. function getMergedStore(target) {
  7005. var classKey = target.getClassName();
  7006. if (__mergedStore[classKey]) {
  7007. return __mergedStore[classKey];
  7008. }
  7009. __mergedStore[classKey] = {};
  7010. var store = __mergedStore[classKey];
  7011. var currentTarget = target;
  7012. var currentKey = classKey;
  7013. while (currentKey) {
  7014. var initialStore = __decoratorInitialStore[currentKey];
  7015. for (var property in initialStore) {
  7016. store[property] = initialStore[property];
  7017. }
  7018. var parent_1 = void 0;
  7019. var done = false;
  7020. do {
  7021. parent_1 = Object.getPrototypeOf(currentTarget);
  7022. if (!parent_1.getClassName) {
  7023. done = true;
  7024. break;
  7025. }
  7026. if (parent_1.getClassName() !== currentKey) {
  7027. break;
  7028. }
  7029. currentTarget = parent_1;
  7030. } while (parent_1);
  7031. if (done) {
  7032. break;
  7033. }
  7034. currentKey = parent_1.getClassName();
  7035. currentTarget = parent_1;
  7036. }
  7037. return store;
  7038. }
  7039. function generateSerializableMember(type, sourceName) {
  7040. return function (target, propertyKey) {
  7041. var classStore = getDirectStore(target);
  7042. if (!classStore[propertyKey]) {
  7043. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7044. }
  7045. };
  7046. }
  7047. function generateExpandMember(setCallback, targetKey) {
  7048. if (targetKey === void 0) { targetKey = null; }
  7049. return function (target, propertyKey) {
  7050. var key = targetKey || ("_" + propertyKey);
  7051. Object.defineProperty(target, propertyKey, {
  7052. get: function () {
  7053. return this[key];
  7054. },
  7055. set: function (value) {
  7056. if (this[key] === value) {
  7057. return;
  7058. }
  7059. this[key] = value;
  7060. target[setCallback].apply(this);
  7061. },
  7062. enumerable: true,
  7063. configurable: true
  7064. });
  7065. };
  7066. }
  7067. function expandToProperty(callback, targetKey) {
  7068. if (targetKey === void 0) { targetKey = null; }
  7069. return generateExpandMember(callback, targetKey);
  7070. }
  7071. BABYLON.expandToProperty = expandToProperty;
  7072. function serialize(sourceName) {
  7073. return generateSerializableMember(0, sourceName); // value member
  7074. }
  7075. BABYLON.serialize = serialize;
  7076. function serializeAsTexture(sourceName) {
  7077. return generateSerializableMember(1, sourceName); // texture member
  7078. }
  7079. BABYLON.serializeAsTexture = serializeAsTexture;
  7080. function serializeAsColor3(sourceName) {
  7081. return generateSerializableMember(2, sourceName); // color3 member
  7082. }
  7083. BABYLON.serializeAsColor3 = serializeAsColor3;
  7084. function serializeAsFresnelParameters(sourceName) {
  7085. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7086. }
  7087. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7088. function serializeAsVector2(sourceName) {
  7089. return generateSerializableMember(4, sourceName); // vector2 member
  7090. }
  7091. BABYLON.serializeAsVector2 = serializeAsVector2;
  7092. function serializeAsVector3(sourceName) {
  7093. return generateSerializableMember(5, sourceName); // vector3 member
  7094. }
  7095. BABYLON.serializeAsVector3 = serializeAsVector3;
  7096. function serializeAsMeshReference(sourceName) {
  7097. return generateSerializableMember(6, sourceName); // mesh reference member
  7098. }
  7099. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7100. function serializeAsColorCurves(sourceName) {
  7101. return generateSerializableMember(7, sourceName); // color curves
  7102. }
  7103. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7104. function serializeAsColor4(sourceName) {
  7105. return generateSerializableMember(8, sourceName); // color 4
  7106. }
  7107. BABYLON.serializeAsColor4 = serializeAsColor4;
  7108. function serializeAsImageProcessingConfiguration(sourceName) {
  7109. return generateSerializableMember(9, sourceName); // image processing
  7110. }
  7111. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7112. function serializeAsQuaternion(sourceName) {
  7113. return generateSerializableMember(10, sourceName); // quaternion member
  7114. }
  7115. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7116. var SerializationHelper = /** @class */ (function () {
  7117. function SerializationHelper() {
  7118. }
  7119. SerializationHelper.Serialize = function (entity, serializationObject) {
  7120. if (!serializationObject) {
  7121. serializationObject = {};
  7122. }
  7123. // Tags
  7124. if (BABYLON.Tags) {
  7125. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7126. }
  7127. var serializedProperties = getMergedStore(entity);
  7128. // Properties
  7129. for (var property in serializedProperties) {
  7130. var propertyDescriptor = serializedProperties[property];
  7131. var targetPropertyName = propertyDescriptor.sourceName || property;
  7132. var propertyType = propertyDescriptor.type;
  7133. var sourceProperty = entity[property];
  7134. if (sourceProperty !== undefined && sourceProperty !== null) {
  7135. switch (propertyType) {
  7136. case 0:// Value
  7137. serializationObject[targetPropertyName] = sourceProperty;
  7138. break;
  7139. case 1:// Texture
  7140. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7141. break;
  7142. case 2:// Color3
  7143. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7144. break;
  7145. case 3:// FresnelParameters
  7146. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7147. break;
  7148. case 4:// Vector2
  7149. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7150. break;
  7151. case 5:// Vector3
  7152. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7153. break;
  7154. case 6:// Mesh reference
  7155. serializationObject[targetPropertyName] = sourceProperty.id;
  7156. break;
  7157. case 7:// Color Curves
  7158. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7159. break;
  7160. case 8:// Color 4
  7161. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7162. break;
  7163. case 9:// Image Processing
  7164. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7165. break;
  7166. }
  7167. }
  7168. }
  7169. return serializationObject;
  7170. };
  7171. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7172. if (rootUrl === void 0) { rootUrl = null; }
  7173. var destination = creationFunction();
  7174. if (!rootUrl) {
  7175. rootUrl = "";
  7176. }
  7177. // Tags
  7178. if (BABYLON.Tags) {
  7179. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7180. }
  7181. var classStore = getMergedStore(destination);
  7182. // Properties
  7183. for (var property in classStore) {
  7184. var propertyDescriptor = classStore[property];
  7185. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7186. var propertyType = propertyDescriptor.type;
  7187. if (sourceProperty !== undefined && sourceProperty !== null) {
  7188. var dest = destination;
  7189. switch (propertyType) {
  7190. case 0:// Value
  7191. dest[property] = sourceProperty;
  7192. break;
  7193. case 1:// Texture
  7194. if (scene) {
  7195. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7196. }
  7197. break;
  7198. case 2:// Color3
  7199. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7200. break;
  7201. case 3:// FresnelParameters
  7202. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7203. break;
  7204. case 4:// Vector2
  7205. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7206. break;
  7207. case 5:// Vector3
  7208. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7209. break;
  7210. case 6:// Mesh reference
  7211. if (scene) {
  7212. dest[property] = scene.getLastMeshByID(sourceProperty);
  7213. }
  7214. break;
  7215. case 7:// Color Curves
  7216. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7217. break;
  7218. case 8:// Color 4
  7219. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7220. break;
  7221. case 9:// Image Processing
  7222. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7223. break;
  7224. }
  7225. }
  7226. }
  7227. return destination;
  7228. };
  7229. SerializationHelper.Clone = function (creationFunction, source) {
  7230. return _copySource(creationFunction, source, false);
  7231. };
  7232. SerializationHelper.Instanciate = function (creationFunction, source) {
  7233. return _copySource(creationFunction, source, true);
  7234. };
  7235. return SerializationHelper;
  7236. }());
  7237. BABYLON.SerializationHelper = SerializationHelper;
  7238. })(BABYLON || (BABYLON = {}));
  7239. //# sourceMappingURL=babylon.decorators.js.map
  7240. var BABYLON;
  7241. (function (BABYLON) {
  7242. /**
  7243. * Wrapper class for promise with external resolve and reject.
  7244. */
  7245. var Deferred = /** @class */ (function () {
  7246. /**
  7247. * Constructor for this deferred object.
  7248. */
  7249. function Deferred() {
  7250. var _this = this;
  7251. this.promise = new Promise(function (resolve, reject) {
  7252. _this._resolve = resolve;
  7253. _this._reject = reject;
  7254. });
  7255. }
  7256. Object.defineProperty(Deferred.prototype, "resolve", {
  7257. /**
  7258. * The resolve method of the promise associated with this deferred object.
  7259. */
  7260. get: function () {
  7261. return this._resolve;
  7262. },
  7263. enumerable: true,
  7264. configurable: true
  7265. });
  7266. Object.defineProperty(Deferred.prototype, "reject", {
  7267. /**
  7268. * The reject method of the promise associated with this deferred object.
  7269. */
  7270. get: function () {
  7271. return this._reject;
  7272. },
  7273. enumerable: true,
  7274. configurable: true
  7275. });
  7276. return Deferred;
  7277. }());
  7278. BABYLON.Deferred = Deferred;
  7279. })(BABYLON || (BABYLON = {}));
  7280. //# sourceMappingURL=babylon.deferred.js.map
  7281. var BABYLON;
  7282. (function (BABYLON) {
  7283. /**
  7284. * A class serves as a medium between the observable and its observers
  7285. */
  7286. var EventState = /** @class */ (function () {
  7287. /**
  7288. * Create a new EventState
  7289. * @param mask defines the mask associated with this state
  7290. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7291. * @param target defines the original target of the state
  7292. * @param currentTarget defines the current target of the state
  7293. */
  7294. function EventState(mask, skipNextObservers, target, currentTarget) {
  7295. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7296. this.initalize(mask, skipNextObservers, target, currentTarget);
  7297. }
  7298. /**
  7299. * Initialize the current event state
  7300. * @param mask defines the mask associated with this state
  7301. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7302. * @param target defines the original target of the state
  7303. * @param currentTarget defines the current target of the state
  7304. * @returns the current event state
  7305. */
  7306. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7307. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7308. this.mask = mask;
  7309. this.skipNextObservers = skipNextObservers;
  7310. this.target = target;
  7311. this.currentTarget = currentTarget;
  7312. return this;
  7313. };
  7314. return EventState;
  7315. }());
  7316. BABYLON.EventState = EventState;
  7317. /**
  7318. * Represent an Observer registered to a given Observable object.
  7319. */
  7320. var Observer = /** @class */ (function () {
  7321. /**
  7322. * Creates a new observer
  7323. * @param callback defines the callback to call when the observer is notified
  7324. * @param mask defines the mask of the observer (used to filter notifications)
  7325. * @param scope defines the current scope used to restore the JS context
  7326. */
  7327. function Observer(
  7328. /**
  7329. * Defines the callback to call when the observer is notified
  7330. */
  7331. callback,
  7332. /**
  7333. * Defines the mask of the observer (used to filter notifications)
  7334. */
  7335. mask,
  7336. /**
  7337. * Defines the current scope used to restore the JS context
  7338. */
  7339. scope) {
  7340. if (scope === void 0) { scope = null; }
  7341. this.callback = callback;
  7342. this.mask = mask;
  7343. this.scope = scope;
  7344. /** @ignore */
  7345. this._willBeUnregistered = false;
  7346. /**
  7347. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7348. */
  7349. this.unregisterOnNextCall = false;
  7350. }
  7351. return Observer;
  7352. }());
  7353. BABYLON.Observer = Observer;
  7354. /**
  7355. * Represent a list of observers registered to multiple Observables object.
  7356. */
  7357. var MultiObserver = /** @class */ (function () {
  7358. function MultiObserver() {
  7359. }
  7360. /**
  7361. * Release associated resources
  7362. */
  7363. MultiObserver.prototype.dispose = function () {
  7364. if (this._observers && this._observables) {
  7365. for (var index = 0; index < this._observers.length; index++) {
  7366. this._observables[index].remove(this._observers[index]);
  7367. }
  7368. }
  7369. this._observers = null;
  7370. this._observables = null;
  7371. };
  7372. /**
  7373. * Raise a callback when one of the observable will notify
  7374. * @param observables defines a list of observables to watch
  7375. * @param callback defines the callback to call on notification
  7376. * @param mask defines the mask used to filter notifications
  7377. * @param scope defines the current scope used to restore the JS context
  7378. * @returns the new MultiObserver
  7379. */
  7380. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7381. if (mask === void 0) { mask = -1; }
  7382. if (scope === void 0) { scope = null; }
  7383. var result = new MultiObserver();
  7384. result._observers = new Array();
  7385. result._observables = observables;
  7386. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7387. var observable = observables_1[_i];
  7388. var observer = observable.add(callback, mask, false, scope);
  7389. if (observer) {
  7390. result._observers.push(observer);
  7391. }
  7392. }
  7393. return result;
  7394. };
  7395. return MultiObserver;
  7396. }());
  7397. BABYLON.MultiObserver = MultiObserver;
  7398. /**
  7399. * The Observable class is a simple implementation of the Observable pattern.
  7400. * 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.
  7401. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7402. * 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).
  7403. * 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.
  7404. */
  7405. var Observable = /** @class */ (function () {
  7406. /**
  7407. * Creates a new observable
  7408. * @param onObserverAdded defines a callback to call when a new observer is added
  7409. */
  7410. function Observable(onObserverAdded) {
  7411. this._observers = new Array();
  7412. this._eventState = new EventState(0);
  7413. if (onObserverAdded) {
  7414. this._onObserverAdded = onObserverAdded;
  7415. }
  7416. }
  7417. /**
  7418. * Create a new Observer with the specified callback
  7419. * @param callback the callback that will be executed for that Observer
  7420. * @param mask the mask used to filter observers
  7421. * @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.
  7422. * @param scope optional scope for the callback to be called from
  7423. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7424. * @returns the new observer created for the callback
  7425. */
  7426. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7427. if (mask === void 0) { mask = -1; }
  7428. if (insertFirst === void 0) { insertFirst = false; }
  7429. if (scope === void 0) { scope = null; }
  7430. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7431. if (!callback) {
  7432. return null;
  7433. }
  7434. var observer = new Observer(callback, mask, scope);
  7435. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7436. if (insertFirst) {
  7437. this._observers.unshift(observer);
  7438. }
  7439. else {
  7440. this._observers.push(observer);
  7441. }
  7442. if (this._onObserverAdded) {
  7443. this._onObserverAdded(observer);
  7444. }
  7445. return observer;
  7446. };
  7447. /**
  7448. * Remove an Observer from the Observable object
  7449. * @param observer the instance of the Observer to remove
  7450. * @returns false if it doesn't belong to this Observable
  7451. */
  7452. Observable.prototype.remove = function (observer) {
  7453. if (!observer) {
  7454. return false;
  7455. }
  7456. var index = this._observers.indexOf(observer);
  7457. if (index !== -1) {
  7458. this._observers.splice(index, 1);
  7459. return true;
  7460. }
  7461. return false;
  7462. };
  7463. /**
  7464. * Remove a callback from the Observable object
  7465. * @param callback the callback to remove
  7466. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7467. * @returns false if it doesn't belong to this Observable
  7468. */
  7469. Observable.prototype.removeCallback = function (callback, scope) {
  7470. for (var index = 0; index < this._observers.length; index++) {
  7471. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7472. this._observers.splice(index, 1);
  7473. return true;
  7474. }
  7475. }
  7476. return false;
  7477. };
  7478. Observable.prototype._deferUnregister = function (observer) {
  7479. var _this = this;
  7480. observer.unregisterOnNextCall = false;
  7481. observer._willBeUnregistered = true;
  7482. BABYLON.Tools.SetImmediate(function () {
  7483. _this.remove(observer);
  7484. });
  7485. };
  7486. /**
  7487. * Notify all Observers by calling their respective callback with the given data
  7488. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7489. * @param eventData defines the data to send to all observers
  7490. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7491. * @param target defines the original target of the state
  7492. * @param currentTarget defines the current target of the state
  7493. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7494. */
  7495. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7496. if (mask === void 0) { mask = -1; }
  7497. if (!this._observers.length) {
  7498. return true;
  7499. }
  7500. var state = this._eventState;
  7501. state.mask = mask;
  7502. state.target = target;
  7503. state.currentTarget = currentTarget;
  7504. state.skipNextObservers = false;
  7505. state.lastReturnValue = eventData;
  7506. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7507. var obs = _a[_i];
  7508. if (obs._willBeUnregistered) {
  7509. continue;
  7510. }
  7511. if (obs.mask & mask) {
  7512. if (obs.scope) {
  7513. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7514. }
  7515. else {
  7516. state.lastReturnValue = obs.callback(eventData, state);
  7517. }
  7518. if (obs.unregisterOnNextCall) {
  7519. this._deferUnregister(obs);
  7520. }
  7521. }
  7522. if (state.skipNextObservers) {
  7523. return false;
  7524. }
  7525. }
  7526. return true;
  7527. };
  7528. /**
  7529. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7530. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7531. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7532. * and it is crucial that all callbacks will be executed.
  7533. * The order of the callbacks is kept, callbacks are not executed parallel.
  7534. *
  7535. * @param eventData The data to be sent to each callback
  7536. * @param mask is used to filter observers defaults to -1
  7537. * @param target defines the callback target (see EventState)
  7538. * @param currentTarget defines he current object in the bubbling phase
  7539. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7540. */
  7541. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7542. var _this = this;
  7543. if (mask === void 0) { mask = -1; }
  7544. // create an empty promise
  7545. var p = Promise.resolve(eventData);
  7546. // no observers? return this promise.
  7547. if (!this._observers.length) {
  7548. return p;
  7549. }
  7550. var state = this._eventState;
  7551. state.mask = mask;
  7552. state.target = target;
  7553. state.currentTarget = currentTarget;
  7554. state.skipNextObservers = false;
  7555. // execute one callback after another (not using Promise.all, the order is important)
  7556. this._observers.forEach(function (obs) {
  7557. if (state.skipNextObservers) {
  7558. return;
  7559. }
  7560. if (obs._willBeUnregistered) {
  7561. return;
  7562. }
  7563. if (obs.mask & mask) {
  7564. if (obs.scope) {
  7565. p = p.then(function (lastReturnedValue) {
  7566. state.lastReturnValue = lastReturnedValue;
  7567. return obs.callback.apply(obs.scope, [eventData, state]);
  7568. });
  7569. }
  7570. else {
  7571. p = p.then(function (lastReturnedValue) {
  7572. state.lastReturnValue = lastReturnedValue;
  7573. return obs.callback(eventData, state);
  7574. });
  7575. }
  7576. if (obs.unregisterOnNextCall) {
  7577. _this._deferUnregister(obs);
  7578. }
  7579. }
  7580. });
  7581. // return the eventData
  7582. return p.then(function () { return eventData; });
  7583. };
  7584. /**
  7585. * Notify a specific observer
  7586. * @param observer defines the observer to notify
  7587. * @param eventData defines the data to be sent to each callback
  7588. * @param mask is used to filter observers defaults to -1
  7589. */
  7590. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7591. if (mask === void 0) { mask = -1; }
  7592. var state = this._eventState;
  7593. state.mask = mask;
  7594. state.skipNextObservers = false;
  7595. observer.callback(eventData, state);
  7596. };
  7597. /**
  7598. * Gets a boolean indicating if the observable has at least one observer
  7599. * @returns true is the Observable has at least one Observer registered
  7600. */
  7601. Observable.prototype.hasObservers = function () {
  7602. return this._observers.length > 0;
  7603. };
  7604. /**
  7605. * Clear the list of observers
  7606. */
  7607. Observable.prototype.clear = function () {
  7608. this._observers = new Array();
  7609. this._onObserverAdded = null;
  7610. };
  7611. /**
  7612. * Clone the current observable
  7613. * @returns a new observable
  7614. */
  7615. Observable.prototype.clone = function () {
  7616. var result = new Observable();
  7617. result._observers = this._observers.slice(0);
  7618. return result;
  7619. };
  7620. /**
  7621. * Does this observable handles observer registered with a given mask
  7622. * @param mask defines the mask to be tested
  7623. * @return whether or not one observer registered with the given mask is handeled
  7624. **/
  7625. Observable.prototype.hasSpecificMask = function (mask) {
  7626. if (mask === void 0) { mask = -1; }
  7627. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7628. var obs = _a[_i];
  7629. if (obs.mask & mask || obs.mask === mask) {
  7630. return true;
  7631. }
  7632. }
  7633. return false;
  7634. };
  7635. return Observable;
  7636. }());
  7637. BABYLON.Observable = Observable;
  7638. })(BABYLON || (BABYLON = {}));
  7639. //# sourceMappingURL=babylon.observable.js.map
  7640. var BABYLON;
  7641. (function (BABYLON) {
  7642. var SmartArray = /** @class */ (function () {
  7643. function SmartArray(capacity) {
  7644. this.length = 0;
  7645. this.data = new Array(capacity);
  7646. this._id = SmartArray._GlobalId++;
  7647. }
  7648. SmartArray.prototype.push = function (value) {
  7649. this.data[this.length++] = value;
  7650. if (this.length > this.data.length) {
  7651. this.data.length *= 2;
  7652. }
  7653. };
  7654. SmartArray.prototype.forEach = function (func) {
  7655. for (var index = 0; index < this.length; index++) {
  7656. func(this.data[index]);
  7657. }
  7658. };
  7659. SmartArray.prototype.sort = function (compareFn) {
  7660. this.data.sort(compareFn);
  7661. };
  7662. SmartArray.prototype.reset = function () {
  7663. this.length = 0;
  7664. };
  7665. SmartArray.prototype.dispose = function () {
  7666. this.reset();
  7667. if (this.data) {
  7668. this.data.length = 0;
  7669. this.data = [];
  7670. }
  7671. };
  7672. SmartArray.prototype.concat = function (array) {
  7673. if (array.length === 0) {
  7674. return;
  7675. }
  7676. if (this.length + array.length > this.data.length) {
  7677. this.data.length = (this.length + array.length) * 2;
  7678. }
  7679. for (var index = 0; index < array.length; index++) {
  7680. this.data[this.length++] = (array.data || array)[index];
  7681. }
  7682. };
  7683. SmartArray.prototype.indexOf = function (value) {
  7684. var position = this.data.indexOf(value);
  7685. if (position >= this.length) {
  7686. return -1;
  7687. }
  7688. return position;
  7689. };
  7690. SmartArray.prototype.contains = function (value) {
  7691. return this.data.indexOf(value) !== -1;
  7692. };
  7693. // Statics
  7694. SmartArray._GlobalId = 0;
  7695. return SmartArray;
  7696. }());
  7697. BABYLON.SmartArray = SmartArray;
  7698. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7699. __extends(SmartArrayNoDuplicate, _super);
  7700. function SmartArrayNoDuplicate() {
  7701. var _this = _super !== null && _super.apply(this, arguments) || this;
  7702. _this._duplicateId = 0;
  7703. return _this;
  7704. }
  7705. SmartArrayNoDuplicate.prototype.push = function (value) {
  7706. _super.prototype.push.call(this, value);
  7707. if (!value.__smartArrayFlags) {
  7708. value.__smartArrayFlags = {};
  7709. }
  7710. value.__smartArrayFlags[this._id] = this._duplicateId;
  7711. };
  7712. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7713. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7714. return false;
  7715. }
  7716. this.push(value);
  7717. return true;
  7718. };
  7719. SmartArrayNoDuplicate.prototype.reset = function () {
  7720. _super.prototype.reset.call(this);
  7721. this._duplicateId++;
  7722. };
  7723. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7724. if (array.length === 0) {
  7725. return;
  7726. }
  7727. if (this.length + array.length > this.data.length) {
  7728. this.data.length = (this.length + array.length) * 2;
  7729. }
  7730. for (var index = 0; index < array.length; index++) {
  7731. var item = (array.data || array)[index];
  7732. this.pushNoDuplicate(item);
  7733. }
  7734. };
  7735. return SmartArrayNoDuplicate;
  7736. }(SmartArray));
  7737. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7738. })(BABYLON || (BABYLON = {}));
  7739. //# sourceMappingURL=babylon.smartArray.js.map
  7740. var BABYLON;
  7741. (function (BABYLON) {
  7742. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7743. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7744. var LoadFileError = /** @class */ (function (_super) {
  7745. __extends(LoadFileError, _super);
  7746. function LoadFileError(message, request) {
  7747. var _this = _super.call(this, message) || this;
  7748. _this.request = request;
  7749. _this.name = "LoadFileError";
  7750. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7751. return _this;
  7752. }
  7753. // Polyfill for Object.setPrototypeOf if necessary.
  7754. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7755. return LoadFileError;
  7756. }(Error));
  7757. BABYLON.LoadFileError = LoadFileError;
  7758. var RetryStrategy = /** @class */ (function () {
  7759. function RetryStrategy() {
  7760. }
  7761. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7762. if (maxRetries === void 0) { maxRetries = 3; }
  7763. if (baseInterval === void 0) { baseInterval = 500; }
  7764. return function (url, request, retryIndex) {
  7765. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7766. return -1;
  7767. }
  7768. return Math.pow(2, retryIndex) * baseInterval;
  7769. };
  7770. };
  7771. return RetryStrategy;
  7772. }());
  7773. BABYLON.RetryStrategy = RetryStrategy;
  7774. // Screenshots
  7775. var screenshotCanvas;
  7776. var cloneValue = function (source, destinationObject) {
  7777. if (!source)
  7778. return null;
  7779. if (source instanceof BABYLON.Mesh) {
  7780. return null;
  7781. }
  7782. if (source instanceof BABYLON.SubMesh) {
  7783. return source.clone(destinationObject);
  7784. }
  7785. else if (source.clone) {
  7786. return source.clone();
  7787. }
  7788. return null;
  7789. };
  7790. var Tools = /** @class */ (function () {
  7791. function Tools() {
  7792. }
  7793. /**
  7794. * Interpolates between a and b via alpha
  7795. * @param a The lower value (returned when alpha = 0)
  7796. * @param b The upper value (returned when alpha = 1)
  7797. * @param alpha The interpolation-factor
  7798. * @return The mixed value
  7799. */
  7800. Tools.Mix = function (a, b, alpha) {
  7801. return a * (1 - alpha) + b * alpha;
  7802. };
  7803. Tools.Instantiate = function (className) {
  7804. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7805. return Tools.RegisteredExternalClasses[className];
  7806. }
  7807. var arr = className.split(".");
  7808. var fn = (window || this);
  7809. for (var i = 0, len = arr.length; i < len; i++) {
  7810. fn = fn[arr[i]];
  7811. }
  7812. if (typeof fn !== "function") {
  7813. return null;
  7814. }
  7815. return fn;
  7816. };
  7817. /**
  7818. * Provides a slice function that will work even on IE
  7819. * @param data defines the array to slice
  7820. * @returns the new sliced array
  7821. */
  7822. Tools.Slice = function (data) {
  7823. if (data.slice) {
  7824. return data.slice();
  7825. }
  7826. return Array.prototype.slice.call(data);
  7827. };
  7828. Tools.SetImmediate = function (action) {
  7829. if (window.setImmediate) {
  7830. window.setImmediate(action);
  7831. }
  7832. else {
  7833. setTimeout(action, 1);
  7834. }
  7835. };
  7836. Tools.IsExponentOfTwo = function (value) {
  7837. var count = 1;
  7838. do {
  7839. count *= 2;
  7840. } while (count < value);
  7841. return count === value;
  7842. };
  7843. /**
  7844. * Find the next highest power of two.
  7845. * @param x Number to start search from.
  7846. * @return Next highest power of two.
  7847. */
  7848. Tools.CeilingPOT = function (x) {
  7849. x--;
  7850. x |= x >> 1;
  7851. x |= x >> 2;
  7852. x |= x >> 4;
  7853. x |= x >> 8;
  7854. x |= x >> 16;
  7855. x++;
  7856. return x;
  7857. };
  7858. /**
  7859. * Find the next lowest power of two.
  7860. * @param x Number to start search from.
  7861. * @return Next lowest power of two.
  7862. */
  7863. Tools.FloorPOT = function (x) {
  7864. x = x | (x >> 1);
  7865. x = x | (x >> 2);
  7866. x = x | (x >> 4);
  7867. x = x | (x >> 8);
  7868. x = x | (x >> 16);
  7869. return x - (x >> 1);
  7870. };
  7871. /**
  7872. * Find the nearest power of two.
  7873. * @param x Number to start search from.
  7874. * @return Next nearest power of two.
  7875. */
  7876. Tools.NearestPOT = function (x) {
  7877. var c = Tools.CeilingPOT(x);
  7878. var f = Tools.FloorPOT(x);
  7879. return (c - x) > (x - f) ? f : c;
  7880. };
  7881. Tools.GetExponentOfTwo = function (value, max, mode) {
  7882. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7883. var pot;
  7884. switch (mode) {
  7885. case BABYLON.Engine.SCALEMODE_FLOOR:
  7886. pot = Tools.FloorPOT(value);
  7887. break;
  7888. case BABYLON.Engine.SCALEMODE_NEAREST:
  7889. pot = Tools.NearestPOT(value);
  7890. break;
  7891. case BABYLON.Engine.SCALEMODE_CEILING:
  7892. default:
  7893. pot = Tools.CeilingPOT(value);
  7894. break;
  7895. }
  7896. return Math.min(pot, max);
  7897. };
  7898. Tools.GetFilename = function (path) {
  7899. var index = path.lastIndexOf("/");
  7900. if (index < 0)
  7901. return path;
  7902. return path.substring(index + 1);
  7903. };
  7904. /**
  7905. * Extracts the "folder" part of a path (everything before the filename).
  7906. * @param uri The URI to extract the info from
  7907. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7908. * @returns The "folder" part of the path
  7909. */
  7910. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7911. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7912. var index = uri.lastIndexOf("/");
  7913. if (index < 0) {
  7914. if (returnUnchangedIfNoSlash) {
  7915. return uri;
  7916. }
  7917. return "";
  7918. }
  7919. return uri.substring(0, index + 1);
  7920. };
  7921. Tools.GetDOMTextContent = function (element) {
  7922. var result = "";
  7923. var child = element.firstChild;
  7924. while (child) {
  7925. if (child.nodeType === 3) {
  7926. result += child.textContent;
  7927. }
  7928. child = child.nextSibling;
  7929. }
  7930. return result;
  7931. };
  7932. Tools.ToDegrees = function (angle) {
  7933. return angle * 180 / Math.PI;
  7934. };
  7935. Tools.ToRadians = function (angle) {
  7936. return angle * Math.PI / 180;
  7937. };
  7938. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7939. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7940. var output = "";
  7941. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7942. var i = 0;
  7943. var bytes = new Uint8Array(buffer);
  7944. while (i < bytes.length) {
  7945. chr1 = bytes[i++];
  7946. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7947. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7948. enc1 = chr1 >> 2;
  7949. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7950. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7951. enc4 = chr3 & 63;
  7952. if (isNaN(chr2)) {
  7953. enc3 = enc4 = 64;
  7954. }
  7955. else if (isNaN(chr3)) {
  7956. enc4 = 64;
  7957. }
  7958. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7959. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7960. }
  7961. return "data:image/png;base64," + output;
  7962. };
  7963. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7964. if (bias === void 0) { bias = null; }
  7965. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7966. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7967. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7968. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7969. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7970. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7971. }
  7972. if (bias) {
  7973. minimum.x -= minimum.x * bias.x + bias.y;
  7974. minimum.y -= minimum.y * bias.x + bias.y;
  7975. minimum.z -= minimum.z * bias.x + bias.y;
  7976. maximum.x += maximum.x * bias.x + bias.y;
  7977. maximum.y += maximum.y * bias.x + bias.y;
  7978. maximum.z += maximum.z * bias.x + bias.y;
  7979. }
  7980. return {
  7981. minimum: minimum,
  7982. maximum: maximum
  7983. };
  7984. };
  7985. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7986. if (bias === void 0) { bias = null; }
  7987. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7988. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7989. if (!stride) {
  7990. stride = 3;
  7991. }
  7992. for (var index = start; index < start + count; index++) {
  7993. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7994. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7995. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7996. }
  7997. if (bias) {
  7998. minimum.x -= minimum.x * bias.x + bias.y;
  7999. minimum.y -= minimum.y * bias.x + bias.y;
  8000. minimum.z -= minimum.z * bias.x + bias.y;
  8001. maximum.x += maximum.x * bias.x + bias.y;
  8002. maximum.y += maximum.y * bias.x + bias.y;
  8003. maximum.z += maximum.z * bias.x + bias.y;
  8004. }
  8005. return {
  8006. minimum: minimum,
  8007. maximum: maximum
  8008. };
  8009. };
  8010. Tools.Vector2ArrayFeeder = function (array) {
  8011. return function (index) {
  8012. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8013. var length = isFloatArray ? array.length / 2 : array.length;
  8014. if (index >= length) {
  8015. return null;
  8016. }
  8017. if (isFloatArray) {
  8018. var fa = array;
  8019. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8020. }
  8021. var a = array;
  8022. return a[index];
  8023. };
  8024. };
  8025. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8026. if (bias === void 0) { bias = null; }
  8027. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8028. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8029. var i = 0;
  8030. var cur = feeder(i++);
  8031. while (cur) {
  8032. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8033. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8034. cur = feeder(i++);
  8035. }
  8036. if (bias) {
  8037. minimum.x -= minimum.x * bias.x + bias.y;
  8038. minimum.y -= minimum.y * bias.x + bias.y;
  8039. maximum.x += maximum.x * bias.x + bias.y;
  8040. maximum.y += maximum.y * bias.x + bias.y;
  8041. }
  8042. return {
  8043. minimum: minimum,
  8044. maximum: maximum
  8045. };
  8046. };
  8047. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8048. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8049. return null;
  8050. return Array.isArray(obj) ? obj : [obj];
  8051. };
  8052. // Misc.
  8053. Tools.GetPointerPrefix = function () {
  8054. var eventPrefix = "pointer";
  8055. // Check if pointer events are supported
  8056. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8057. eventPrefix = "mouse";
  8058. }
  8059. return eventPrefix;
  8060. };
  8061. /**
  8062. * @param func - the function to be called
  8063. * @param requester - the object that will request the next frame. Falls back to window.
  8064. */
  8065. Tools.QueueNewFrame = function (func, requester) {
  8066. if (!Tools.IsWindowObjectExist()) {
  8067. return setTimeout(func, 16);
  8068. }
  8069. if (!requester) {
  8070. requester = window;
  8071. }
  8072. if (requester.requestAnimationFrame) {
  8073. return requester.requestAnimationFrame(func);
  8074. }
  8075. else if (requester.msRequestAnimationFrame) {
  8076. return requester.msRequestAnimationFrame(func);
  8077. }
  8078. else if (requester.webkitRequestAnimationFrame) {
  8079. return requester.webkitRequestAnimationFrame(func);
  8080. }
  8081. else if (requester.mozRequestAnimationFrame) {
  8082. return requester.mozRequestAnimationFrame(func);
  8083. }
  8084. else if (requester.oRequestAnimationFrame) {
  8085. return requester.oRequestAnimationFrame(func);
  8086. }
  8087. else {
  8088. return window.setTimeout(func, 16);
  8089. }
  8090. };
  8091. Tools.RequestFullscreen = function (element) {
  8092. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8093. if (!requestFunction)
  8094. return;
  8095. requestFunction.call(element);
  8096. };
  8097. Tools.ExitFullscreen = function () {
  8098. if (document.exitFullscreen) {
  8099. document.exitFullscreen();
  8100. }
  8101. else if (document.mozCancelFullScreen) {
  8102. document.mozCancelFullScreen();
  8103. }
  8104. else if (document.webkitCancelFullScreen) {
  8105. document.webkitCancelFullScreen();
  8106. }
  8107. else if (document.msCancelFullScreen) {
  8108. document.msCancelFullScreen();
  8109. }
  8110. };
  8111. Tools.SetCorsBehavior = function (url, element) {
  8112. if (url && url.indexOf("data:") === 0) {
  8113. return;
  8114. }
  8115. if (Tools.CorsBehavior) {
  8116. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8117. element.crossOrigin = Tools.CorsBehavior;
  8118. }
  8119. else {
  8120. var result = Tools.CorsBehavior(url);
  8121. if (result) {
  8122. element.crossOrigin = result;
  8123. }
  8124. }
  8125. }
  8126. };
  8127. // External files
  8128. Tools.CleanUrl = function (url) {
  8129. url = url.replace(/#/mg, "%23");
  8130. return url;
  8131. };
  8132. Tools.LoadImage = function (url, onLoad, onError, database) {
  8133. if (url instanceof ArrayBuffer) {
  8134. url = Tools.EncodeArrayBufferTobase64(url);
  8135. }
  8136. url = Tools.CleanUrl(url);
  8137. url = Tools.PreprocessUrl(url);
  8138. var img = new Image();
  8139. Tools.SetCorsBehavior(url, img);
  8140. var loadHandler = function () {
  8141. img.removeEventListener("load", loadHandler);
  8142. img.removeEventListener("error", errorHandler);
  8143. onLoad(img);
  8144. };
  8145. var errorHandler = function (err) {
  8146. img.removeEventListener("load", loadHandler);
  8147. img.removeEventListener("error", errorHandler);
  8148. Tools.Error("Error while trying to load image: " + url);
  8149. if (onError) {
  8150. onError("Error while trying to load image: " + url, err);
  8151. }
  8152. };
  8153. img.addEventListener("load", loadHandler);
  8154. img.addEventListener("error", errorHandler);
  8155. var noIndexedDB = function () {
  8156. img.src = url;
  8157. };
  8158. var loadFromIndexedDB = function () {
  8159. if (database) {
  8160. database.loadImageFromDB(url, img);
  8161. }
  8162. };
  8163. //ANY database to do!
  8164. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8165. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8166. }
  8167. else {
  8168. if (url.indexOf("file:") !== -1) {
  8169. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8170. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8171. try {
  8172. var blobURL;
  8173. try {
  8174. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8175. }
  8176. catch (ex) {
  8177. // Chrome doesn't support oneTimeOnly parameter
  8178. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8179. }
  8180. img.src = blobURL;
  8181. }
  8182. catch (e) {
  8183. img.src = "";
  8184. }
  8185. return img;
  8186. }
  8187. }
  8188. noIndexedDB();
  8189. }
  8190. return img;
  8191. };
  8192. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8193. url = Tools.CleanUrl(url);
  8194. url = Tools.PreprocessUrl(url);
  8195. // If file and file input are set
  8196. if (url.indexOf("file:") !== -1) {
  8197. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8198. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8199. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8200. }
  8201. }
  8202. var loadUrl = Tools.BaseUrl + url;
  8203. var aborted = false;
  8204. var fileRequest = {
  8205. onCompleteObservable: new BABYLON.Observable(),
  8206. abort: function () { return aborted = true; },
  8207. };
  8208. var requestFile = function () {
  8209. var request = new XMLHttpRequest();
  8210. var retryHandle = null;
  8211. fileRequest.abort = function () {
  8212. aborted = true;
  8213. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8214. request.abort();
  8215. }
  8216. if (retryHandle !== null) {
  8217. clearTimeout(retryHandle);
  8218. retryHandle = null;
  8219. }
  8220. };
  8221. var retryLoop = function (retryIndex) {
  8222. request.open('GET', loadUrl, true);
  8223. if (useArrayBuffer) {
  8224. request.responseType = "arraybuffer";
  8225. }
  8226. if (onProgress) {
  8227. request.addEventListener("progress", onProgress);
  8228. }
  8229. var onLoadEnd = function () {
  8230. request.removeEventListener("loadend", onLoadEnd);
  8231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8232. fileRequest.onCompleteObservable.clear();
  8233. };
  8234. request.addEventListener("loadend", onLoadEnd);
  8235. var onReadyStateChange = function () {
  8236. if (aborted) {
  8237. return;
  8238. }
  8239. // In case of undefined state in some browsers.
  8240. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8241. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8242. request.removeEventListener("readystatechange", onReadyStateChange);
  8243. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8244. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8245. return;
  8246. }
  8247. var retryStrategy = Tools.DefaultRetryStrategy;
  8248. if (retryStrategy) {
  8249. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8250. if (waitTime !== -1) {
  8251. // Prevent the request from completing for retry.
  8252. request.removeEventListener("loadend", onLoadEnd);
  8253. request = new XMLHttpRequest();
  8254. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8255. return;
  8256. }
  8257. }
  8258. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8259. if (onError) {
  8260. onError(request, e);
  8261. }
  8262. else {
  8263. throw e;
  8264. }
  8265. }
  8266. };
  8267. request.addEventListener("readystatechange", onReadyStateChange);
  8268. request.send();
  8269. };
  8270. retryLoop(0);
  8271. };
  8272. // Caching all files
  8273. if (database && database.enableSceneOffline) {
  8274. var noIndexedDB_1 = function () {
  8275. if (!aborted) {
  8276. requestFile();
  8277. }
  8278. };
  8279. var loadFromIndexedDB = function () {
  8280. // TODO: database needs to support aborting and should return a IFileRequest
  8281. if (aborted) {
  8282. return;
  8283. }
  8284. if (database) {
  8285. database.loadFileFromDB(url, function (data) {
  8286. if (!aborted) {
  8287. onSuccess(data);
  8288. }
  8289. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8290. }, onProgress ? function (event) {
  8291. if (!aborted) {
  8292. onProgress(event);
  8293. }
  8294. } : undefined, noIndexedDB_1, useArrayBuffer);
  8295. }
  8296. };
  8297. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8298. }
  8299. else {
  8300. requestFile();
  8301. }
  8302. return fileRequest;
  8303. };
  8304. /**
  8305. * Load a script (identified by an url). When the url returns, the
  8306. * content of this file is added into a new script element, attached to the DOM (body element)
  8307. */
  8308. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8309. var head = document.getElementsByTagName('head')[0];
  8310. var script = document.createElement('script');
  8311. script.type = 'text/javascript';
  8312. script.src = scriptUrl;
  8313. script.onload = function () {
  8314. if (onSuccess) {
  8315. onSuccess();
  8316. }
  8317. };
  8318. script.onerror = function (e) {
  8319. if (onError) {
  8320. onError("Unable to load script", e);
  8321. }
  8322. };
  8323. head.appendChild(script);
  8324. };
  8325. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8326. var reader = new FileReader();
  8327. var request = {
  8328. onCompleteObservable: new BABYLON.Observable(),
  8329. abort: function () { return reader.abort(); },
  8330. };
  8331. reader.onloadend = function (e) {
  8332. request.onCompleteObservable.notifyObservers(request);
  8333. };
  8334. reader.onload = function (e) {
  8335. //target doesn't have result from ts 1.3
  8336. callback(e.target['result']);
  8337. };
  8338. reader.onprogress = progressCallback;
  8339. reader.readAsDataURL(fileToLoad);
  8340. return request;
  8341. };
  8342. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8343. var reader = new FileReader();
  8344. var request = {
  8345. onCompleteObservable: new BABYLON.Observable(),
  8346. abort: function () { return reader.abort(); },
  8347. };
  8348. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8349. reader.onerror = function (e) {
  8350. Tools.Log("Error while reading file: " + fileToLoad.name);
  8351. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8352. };
  8353. reader.onload = function (e) {
  8354. //target doesn't have result from ts 1.3
  8355. callback(e.target['result']);
  8356. };
  8357. if (progressCallBack) {
  8358. reader.onprogress = progressCallBack;
  8359. }
  8360. if (!useArrayBuffer) {
  8361. // Asynchronous read
  8362. reader.readAsText(fileToLoad);
  8363. }
  8364. else {
  8365. reader.readAsArrayBuffer(fileToLoad);
  8366. }
  8367. return request;
  8368. };
  8369. //returns a downloadable url to a file content.
  8370. Tools.FileAsURL = function (content) {
  8371. var fileBlob = new Blob([content]);
  8372. var url = window.URL || window.webkitURL;
  8373. var link = url.createObjectURL(fileBlob);
  8374. return link;
  8375. };
  8376. // Misc.
  8377. Tools.Format = function (value, decimals) {
  8378. if (decimals === void 0) { decimals = 2; }
  8379. return value.toFixed(decimals);
  8380. };
  8381. Tools.CheckExtends = function (v, min, max) {
  8382. if (v.x < min.x)
  8383. min.x = v.x;
  8384. if (v.y < min.y)
  8385. min.y = v.y;
  8386. if (v.z < min.z)
  8387. min.z = v.z;
  8388. if (v.x > max.x)
  8389. max.x = v.x;
  8390. if (v.y > max.y)
  8391. max.y = v.y;
  8392. if (v.z > max.z)
  8393. max.z = v.z;
  8394. };
  8395. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8396. for (var prop in source) {
  8397. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8398. continue;
  8399. }
  8400. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8401. continue;
  8402. }
  8403. var sourceValue = source[prop];
  8404. var typeOfSourceValue = typeof sourceValue;
  8405. if (typeOfSourceValue === "function") {
  8406. continue;
  8407. }
  8408. if (typeOfSourceValue === "object") {
  8409. if (sourceValue instanceof Array) {
  8410. destination[prop] = [];
  8411. if (sourceValue.length > 0) {
  8412. if (typeof sourceValue[0] == "object") {
  8413. for (var index = 0; index < sourceValue.length; index++) {
  8414. var clonedValue = cloneValue(sourceValue[index], destination);
  8415. if (destination[prop].indexOf(clonedValue) === -1) {
  8416. destination[prop].push(clonedValue);
  8417. }
  8418. }
  8419. }
  8420. else {
  8421. destination[prop] = sourceValue.slice(0);
  8422. }
  8423. }
  8424. }
  8425. else {
  8426. destination[prop] = cloneValue(sourceValue, destination);
  8427. }
  8428. }
  8429. else {
  8430. destination[prop] = sourceValue;
  8431. }
  8432. }
  8433. };
  8434. Tools.IsEmpty = function (obj) {
  8435. for (var i in obj) {
  8436. if (obj.hasOwnProperty(i)) {
  8437. return false;
  8438. }
  8439. }
  8440. return true;
  8441. };
  8442. Tools.RegisterTopRootEvents = function (events) {
  8443. for (var index = 0; index < events.length; index++) {
  8444. var event = events[index];
  8445. window.addEventListener(event.name, event.handler, false);
  8446. try {
  8447. if (window.parent) {
  8448. window.parent.addEventListener(event.name, event.handler, false);
  8449. }
  8450. }
  8451. catch (e) {
  8452. // Silently fails...
  8453. }
  8454. }
  8455. };
  8456. Tools.UnregisterTopRootEvents = function (events) {
  8457. for (var index = 0; index < events.length; index++) {
  8458. var event = events[index];
  8459. window.removeEventListener(event.name, event.handler);
  8460. try {
  8461. if (window.parent) {
  8462. window.parent.removeEventListener(event.name, event.handler);
  8463. }
  8464. }
  8465. catch (e) {
  8466. // Silently fails...
  8467. }
  8468. }
  8469. };
  8470. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8471. if (mimeType === void 0) { mimeType = "image/png"; }
  8472. // Read the contents of the framebuffer
  8473. var numberOfChannelsByLine = width * 4;
  8474. var halfHeight = height / 2;
  8475. //Reading datas from WebGL
  8476. var data = engine.readPixels(0, 0, width, height);
  8477. //To flip image on Y axis.
  8478. for (var i = 0; i < halfHeight; i++) {
  8479. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8480. var currentCell = j + i * numberOfChannelsByLine;
  8481. var targetLine = height - i - 1;
  8482. var targetCell = j + targetLine * numberOfChannelsByLine;
  8483. var temp = data[currentCell];
  8484. data[currentCell] = data[targetCell];
  8485. data[targetCell] = temp;
  8486. }
  8487. }
  8488. // Create a 2D canvas to store the result
  8489. if (!screenshotCanvas) {
  8490. screenshotCanvas = document.createElement('canvas');
  8491. }
  8492. screenshotCanvas.width = width;
  8493. screenshotCanvas.height = height;
  8494. var context = screenshotCanvas.getContext('2d');
  8495. if (context) {
  8496. // Copy the pixels to a 2D canvas
  8497. var imageData = context.createImageData(width, height);
  8498. var castData = (imageData.data);
  8499. castData.set(data);
  8500. context.putImageData(imageData, 0, 0);
  8501. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8502. }
  8503. };
  8504. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8505. if (mimeType === void 0) { mimeType = "image/png"; }
  8506. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8507. if (successCallback) {
  8508. successCallback(base64Image);
  8509. }
  8510. else {
  8511. // We need HTMLCanvasElement.toBlob for HD screenshots
  8512. if (!screenshotCanvas.toBlob) {
  8513. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8514. screenshotCanvas.toBlob = function (callback, type, quality) {
  8515. var _this = this;
  8516. setTimeout(function () {
  8517. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8518. for (var i = 0; i < len; i++) {
  8519. arr[i] = binStr.charCodeAt(i);
  8520. }
  8521. callback(new Blob([arr], { type: type || 'image/png' }));
  8522. });
  8523. };
  8524. }
  8525. screenshotCanvas.toBlob(function (blob) {
  8526. var url = URL.createObjectURL(blob);
  8527. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8528. if (("download" in document.createElement("a"))) {
  8529. var a = window.document.createElement("a");
  8530. a.href = url;
  8531. if (fileName) {
  8532. a.setAttribute("download", fileName);
  8533. }
  8534. else {
  8535. var date = new Date();
  8536. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8537. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8538. }
  8539. window.document.body.appendChild(a);
  8540. a.addEventListener("click", function () {
  8541. if (a.parentElement) {
  8542. a.parentElement.removeChild(a);
  8543. }
  8544. });
  8545. a.click();
  8546. }
  8547. else {
  8548. var newWindow = window.open("");
  8549. if (!newWindow)
  8550. return;
  8551. var img = newWindow.document.createElement("img");
  8552. img.onload = function () {
  8553. // no longer need to read the blob so it's revoked
  8554. URL.revokeObjectURL(url);
  8555. };
  8556. img.src = url;
  8557. newWindow.document.body.appendChild(img);
  8558. }
  8559. });
  8560. }
  8561. };
  8562. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8563. if (mimeType === void 0) { mimeType = "image/png"; }
  8564. var width;
  8565. var height;
  8566. // If a precision value is specified
  8567. if (size.precision) {
  8568. width = Math.round(engine.getRenderWidth() * size.precision);
  8569. height = Math.round(width / engine.getAspectRatio(camera));
  8570. }
  8571. else if (size.width && size.height) {
  8572. width = size.width;
  8573. height = size.height;
  8574. }
  8575. else if (size.width && !size.height) {
  8576. width = size.width;
  8577. height = Math.round(width / engine.getAspectRatio(camera));
  8578. }
  8579. else if (size.height && !size.width) {
  8580. height = size.height;
  8581. width = Math.round(height * engine.getAspectRatio(camera));
  8582. }
  8583. else if (!isNaN(size)) {
  8584. height = size;
  8585. width = size;
  8586. }
  8587. else {
  8588. Tools.Error("Invalid 'size' parameter !");
  8589. return;
  8590. }
  8591. if (!screenshotCanvas) {
  8592. screenshotCanvas = document.createElement('canvas');
  8593. }
  8594. screenshotCanvas.width = width;
  8595. screenshotCanvas.height = height;
  8596. var renderContext = screenshotCanvas.getContext("2d");
  8597. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8598. var newWidth = width;
  8599. var newHeight = newWidth / ratio;
  8600. if (newHeight > height) {
  8601. newHeight = height;
  8602. newWidth = newHeight * ratio;
  8603. }
  8604. var offsetX = Math.max(0, width - newWidth) / 2;
  8605. var offsetY = Math.max(0, height - newHeight) / 2;
  8606. var renderingCanvas = engine.getRenderingCanvas();
  8607. if (renderContext && renderingCanvas) {
  8608. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8609. }
  8610. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8611. };
  8612. /**
  8613. * Generates an image screenshot from the specified camera.
  8614. *
  8615. * @param engine The engine to use for rendering
  8616. * @param camera The camera to use for rendering
  8617. * @param size This parameter can be set to a single number or to an object with the
  8618. * following (optional) properties: precision, width, height. If a single number is passed,
  8619. * it will be used for both width and height. If an object is passed, the screenshot size
  8620. * will be derived from the parameters. The precision property is a multiplier allowing
  8621. * rendering at a higher or lower resolution.
  8622. * @param successCallback The callback receives a single parameter which contains the
  8623. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8624. * src parameter of an <img> to display it.
  8625. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8626. * Check your browser for supported MIME types.
  8627. * @param samples Texture samples (default: 1)
  8628. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8629. * @param fileName A name for for the downloaded file.
  8630. * @constructor
  8631. */
  8632. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8633. if (mimeType === void 0) { mimeType = "image/png"; }
  8634. if (samples === void 0) { samples = 1; }
  8635. if (antialiasing === void 0) { antialiasing = false; }
  8636. var width;
  8637. var height;
  8638. //If a precision value is specified
  8639. if (size.precision) {
  8640. width = Math.round(engine.getRenderWidth() * size.precision);
  8641. height = Math.round(width / engine.getAspectRatio(camera));
  8642. size = { width: width, height: height };
  8643. }
  8644. else if (size.width && size.height) {
  8645. width = size.width;
  8646. height = size.height;
  8647. }
  8648. else if (size.width && !size.height) {
  8649. width = size.width;
  8650. height = Math.round(width / engine.getAspectRatio(camera));
  8651. size = { width: width, height: height };
  8652. }
  8653. else if (size.height && !size.width) {
  8654. height = size.height;
  8655. width = Math.round(height * engine.getAspectRatio(camera));
  8656. size = { width: width, height: height };
  8657. }
  8658. else if (!isNaN(size)) {
  8659. height = size;
  8660. width = size;
  8661. }
  8662. else {
  8663. Tools.Error("Invalid 'size' parameter !");
  8664. return;
  8665. }
  8666. var scene = camera.getScene();
  8667. var previousCamera = null;
  8668. if (scene.activeCamera !== camera) {
  8669. previousCamera = scene.activeCamera;
  8670. scene.activeCamera = camera;
  8671. }
  8672. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8673. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8674. texture.renderList = null;
  8675. texture.samples = samples;
  8676. if (antialiasing) {
  8677. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8678. }
  8679. texture.onAfterRenderObservable.add(function () {
  8680. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8681. });
  8682. scene.incrementRenderId();
  8683. scene.resetCachedMaterial();
  8684. texture.render(true);
  8685. texture.dispose();
  8686. if (previousCamera) {
  8687. scene.activeCamera = previousCamera;
  8688. }
  8689. camera.getProjectionMatrix(true); // Force cache refresh;
  8690. };
  8691. // XHR response validator for local file scenario
  8692. Tools.ValidateXHRData = function (xhr, dataType) {
  8693. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8694. if (dataType === void 0) { dataType = 7; }
  8695. try {
  8696. if (dataType & 1) {
  8697. if (xhr.responseText && xhr.responseText.length > 0) {
  8698. return true;
  8699. }
  8700. else if (dataType === 1) {
  8701. return false;
  8702. }
  8703. }
  8704. if (dataType & 2) {
  8705. // Check header width and height since there is no "TGA" magic number
  8706. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8707. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8708. return true;
  8709. }
  8710. else if (dataType === 2) {
  8711. return false;
  8712. }
  8713. }
  8714. if (dataType & 4) {
  8715. // Check for the "DDS" magic number
  8716. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8717. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8718. return true;
  8719. }
  8720. else {
  8721. return false;
  8722. }
  8723. }
  8724. }
  8725. catch (e) {
  8726. // Global protection
  8727. }
  8728. return false;
  8729. };
  8730. /**
  8731. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8732. * Be aware Math.random() could cause collisions, but:
  8733. * "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"
  8734. */
  8735. Tools.RandomId = function () {
  8736. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8737. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8738. return v.toString(16);
  8739. });
  8740. };
  8741. /**
  8742. * Test if the given uri is a base64 string.
  8743. * @param uri The uri to test
  8744. * @return True if the uri is a base64 string or false otherwise.
  8745. */
  8746. Tools.IsBase64 = function (uri) {
  8747. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8748. };
  8749. /**
  8750. * Decode the given base64 uri.
  8751. * @param uri The uri to decode
  8752. * @return The decoded base64 data.
  8753. */
  8754. Tools.DecodeBase64 = function (uri) {
  8755. var decodedString = atob(uri.split(",")[1]);
  8756. var bufferLength = decodedString.length;
  8757. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8758. for (var i = 0; i < bufferLength; i++) {
  8759. bufferView[i] = decodedString.charCodeAt(i);
  8760. }
  8761. return bufferView.buffer;
  8762. };
  8763. Object.defineProperty(Tools, "NoneLogLevel", {
  8764. get: function () {
  8765. return Tools._NoneLogLevel;
  8766. },
  8767. enumerable: true,
  8768. configurable: true
  8769. });
  8770. Object.defineProperty(Tools, "MessageLogLevel", {
  8771. get: function () {
  8772. return Tools._MessageLogLevel;
  8773. },
  8774. enumerable: true,
  8775. configurable: true
  8776. });
  8777. Object.defineProperty(Tools, "WarningLogLevel", {
  8778. get: function () {
  8779. return Tools._WarningLogLevel;
  8780. },
  8781. enumerable: true,
  8782. configurable: true
  8783. });
  8784. Object.defineProperty(Tools, "ErrorLogLevel", {
  8785. get: function () {
  8786. return Tools._ErrorLogLevel;
  8787. },
  8788. enumerable: true,
  8789. configurable: true
  8790. });
  8791. Object.defineProperty(Tools, "AllLogLevel", {
  8792. get: function () {
  8793. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8794. },
  8795. enumerable: true,
  8796. configurable: true
  8797. });
  8798. Tools._AddLogEntry = function (entry) {
  8799. Tools._LogCache = entry + Tools._LogCache;
  8800. if (Tools.OnNewCacheEntry) {
  8801. Tools.OnNewCacheEntry(entry);
  8802. }
  8803. };
  8804. Tools._FormatMessage = function (message) {
  8805. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8806. var date = new Date();
  8807. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8808. };
  8809. Tools._LogDisabled = function (message) {
  8810. // nothing to do
  8811. };
  8812. Tools._LogEnabled = function (message) {
  8813. var formattedMessage = Tools._FormatMessage(message);
  8814. console.log("BJS - " + formattedMessage);
  8815. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8816. Tools._AddLogEntry(entry);
  8817. };
  8818. Tools._WarnDisabled = function (message) {
  8819. // nothing to do
  8820. };
  8821. Tools._WarnEnabled = function (message) {
  8822. var formattedMessage = Tools._FormatMessage(message);
  8823. console.warn("BJS - " + formattedMessage);
  8824. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8825. Tools._AddLogEntry(entry);
  8826. };
  8827. Tools._ErrorDisabled = function (message) {
  8828. // nothing to do
  8829. };
  8830. Tools._ErrorEnabled = function (message) {
  8831. Tools.errorsCount++;
  8832. var formattedMessage = Tools._FormatMessage(message);
  8833. console.error("BJS - " + formattedMessage);
  8834. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8835. Tools._AddLogEntry(entry);
  8836. };
  8837. Object.defineProperty(Tools, "LogCache", {
  8838. get: function () {
  8839. return Tools._LogCache;
  8840. },
  8841. enumerable: true,
  8842. configurable: true
  8843. });
  8844. Tools.ClearLogCache = function () {
  8845. Tools._LogCache = "";
  8846. Tools.errorsCount = 0;
  8847. };
  8848. Object.defineProperty(Tools, "LogLevels", {
  8849. set: function (level) {
  8850. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8851. Tools.Log = Tools._LogEnabled;
  8852. }
  8853. else {
  8854. Tools.Log = Tools._LogDisabled;
  8855. }
  8856. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8857. Tools.Warn = Tools._WarnEnabled;
  8858. }
  8859. else {
  8860. Tools.Warn = Tools._WarnDisabled;
  8861. }
  8862. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8863. Tools.Error = Tools._ErrorEnabled;
  8864. }
  8865. else {
  8866. Tools.Error = Tools._ErrorDisabled;
  8867. }
  8868. },
  8869. enumerable: true,
  8870. configurable: true
  8871. });
  8872. Tools.IsWindowObjectExist = function () {
  8873. return (typeof window) !== "undefined";
  8874. };
  8875. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8876. get: function () {
  8877. return Tools._PerformanceNoneLogLevel;
  8878. },
  8879. enumerable: true,
  8880. configurable: true
  8881. });
  8882. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8883. get: function () {
  8884. return Tools._PerformanceUserMarkLogLevel;
  8885. },
  8886. enumerable: true,
  8887. configurable: true
  8888. });
  8889. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8890. get: function () {
  8891. return Tools._PerformanceConsoleLogLevel;
  8892. },
  8893. enumerable: true,
  8894. configurable: true
  8895. });
  8896. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8897. set: function (level) {
  8898. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8899. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8900. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8901. return;
  8902. }
  8903. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8904. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8905. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8906. return;
  8907. }
  8908. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8909. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8910. },
  8911. enumerable: true,
  8912. configurable: true
  8913. });
  8914. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8915. };
  8916. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8917. };
  8918. Tools._StartUserMark = function (counterName, condition) {
  8919. if (condition === void 0) { condition = true; }
  8920. if (!Tools._performance) {
  8921. if (!Tools.IsWindowObjectExist()) {
  8922. return;
  8923. }
  8924. Tools._performance = window.performance;
  8925. }
  8926. if (!condition || !Tools._performance.mark) {
  8927. return;
  8928. }
  8929. Tools._performance.mark(counterName + "-Begin");
  8930. };
  8931. Tools._EndUserMark = function (counterName, condition) {
  8932. if (condition === void 0) { condition = true; }
  8933. if (!condition || !Tools._performance.mark) {
  8934. return;
  8935. }
  8936. Tools._performance.mark(counterName + "-End");
  8937. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8938. };
  8939. Tools._StartPerformanceConsole = function (counterName, condition) {
  8940. if (condition === void 0) { condition = true; }
  8941. if (!condition) {
  8942. return;
  8943. }
  8944. Tools._StartUserMark(counterName, condition);
  8945. if (console.time) {
  8946. console.time(counterName);
  8947. }
  8948. };
  8949. Tools._EndPerformanceConsole = function (counterName, condition) {
  8950. if (condition === void 0) { condition = true; }
  8951. if (!condition) {
  8952. return;
  8953. }
  8954. Tools._EndUserMark(counterName, condition);
  8955. if (console.time) {
  8956. console.timeEnd(counterName);
  8957. }
  8958. };
  8959. Object.defineProperty(Tools, "Now", {
  8960. get: function () {
  8961. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8962. return window.performance.now();
  8963. }
  8964. return new Date().getTime();
  8965. },
  8966. enumerable: true,
  8967. configurable: true
  8968. });
  8969. /**
  8970. * This method will return the name of the class used to create the instance of the given object.
  8971. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8972. * @param object the object to get the class name from
  8973. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8974. */
  8975. Tools.GetClassName = function (object, isType) {
  8976. if (isType === void 0) { isType = false; }
  8977. var name = null;
  8978. if (!isType && object.getClassName) {
  8979. name = object.getClassName();
  8980. }
  8981. else {
  8982. if (object instanceof Object) {
  8983. var classObj = isType ? object : Object.getPrototypeOf(object);
  8984. name = classObj.constructor["__bjsclassName__"];
  8985. }
  8986. if (!name) {
  8987. name = typeof object;
  8988. }
  8989. }
  8990. return name;
  8991. };
  8992. Tools.First = function (array, predicate) {
  8993. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8994. var el = array_1[_i];
  8995. if (predicate(el)) {
  8996. return el;
  8997. }
  8998. }
  8999. return null;
  9000. };
  9001. /**
  9002. * This method will return the name of the full name of the class, including its owning module (if any).
  9003. * 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).
  9004. * @param object the object to get the class name from
  9005. * @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.
  9006. */
  9007. Tools.getFullClassName = function (object, isType) {
  9008. if (isType === void 0) { isType = false; }
  9009. var className = null;
  9010. var moduleName = null;
  9011. if (!isType && object.getClassName) {
  9012. className = object.getClassName();
  9013. }
  9014. else {
  9015. if (object instanceof Object) {
  9016. var classObj = isType ? object : Object.getPrototypeOf(object);
  9017. className = classObj.constructor["__bjsclassName__"];
  9018. moduleName = classObj.constructor["__bjsmoduleName__"];
  9019. }
  9020. if (!className) {
  9021. className = typeof object;
  9022. }
  9023. }
  9024. if (!className) {
  9025. return null;
  9026. }
  9027. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9028. };
  9029. /**
  9030. * 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.
  9031. * @param array
  9032. */
  9033. Tools.arrayOrStringFeeder = function (array) {
  9034. return function (index) {
  9035. if (index >= array.length) {
  9036. return null;
  9037. }
  9038. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9039. if (val && val.getHashCode) {
  9040. val = val.getHashCode();
  9041. }
  9042. if (typeof val === "string") {
  9043. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9044. }
  9045. return val;
  9046. };
  9047. };
  9048. /**
  9049. * Compute the hashCode of a stream of number
  9050. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9051. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9052. * @return the hash code computed
  9053. */
  9054. Tools.hashCodeFromStream = function (feeder) {
  9055. // Based from here: http://stackoverflow.com/a/7616484/802124
  9056. var hash = 0;
  9057. var index = 0;
  9058. var chr = feeder(index++);
  9059. while (chr != null) {
  9060. hash = ((hash << 5) - hash) + chr;
  9061. hash |= 0; // Convert to 32bit integer
  9062. chr = feeder(index++);
  9063. }
  9064. return hash;
  9065. };
  9066. /**
  9067. * Returns a promise that resolves after the given amount of time.
  9068. * @param delay Number of milliseconds to delay
  9069. * @returns Promise that resolves after the given amount of time
  9070. */
  9071. Tools.DelayAsync = function (delay) {
  9072. return new Promise(function (resolve) {
  9073. setTimeout(function () {
  9074. resolve();
  9075. }, delay);
  9076. });
  9077. };
  9078. Tools.BaseUrl = "";
  9079. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9080. /**
  9081. * Default behaviour for cors in the application.
  9082. * It can be a string if the expected behavior is identical in the entire app.
  9083. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9084. */
  9085. Tools.CorsBehavior = "anonymous";
  9086. Tools.UseFallbackTexture = true;
  9087. /**
  9088. * Use this object to register external classes like custom textures or material
  9089. * to allow the laoders to instantiate them
  9090. */
  9091. Tools.RegisteredExternalClasses = {};
  9092. // Used in case of a texture loading problem
  9093. 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";
  9094. Tools.PreprocessUrl = function (url) {
  9095. return url;
  9096. };
  9097. // Logs
  9098. Tools._NoneLogLevel = 0;
  9099. Tools._MessageLogLevel = 1;
  9100. Tools._WarningLogLevel = 2;
  9101. Tools._ErrorLogLevel = 4;
  9102. Tools._LogCache = "";
  9103. Tools.errorsCount = 0;
  9104. Tools.Log = Tools._LogEnabled;
  9105. Tools.Warn = Tools._WarnEnabled;
  9106. Tools.Error = Tools._ErrorEnabled;
  9107. // Performances
  9108. Tools._PerformanceNoneLogLevel = 0;
  9109. Tools._PerformanceUserMarkLogLevel = 1;
  9110. Tools._PerformanceConsoleLogLevel = 2;
  9111. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9112. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9113. return Tools;
  9114. }());
  9115. BABYLON.Tools = Tools;
  9116. /**
  9117. * This class is used to track a performance counter which is number based.
  9118. * The user has access to many properties which give statistics of different nature
  9119. *
  9120. * The implementer can track two kinds of Performance Counter: time and count
  9121. * 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.
  9122. * 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.
  9123. */
  9124. var PerfCounter = /** @class */ (function () {
  9125. function PerfCounter() {
  9126. this._startMonitoringTime = 0;
  9127. this._min = 0;
  9128. this._max = 0;
  9129. this._average = 0;
  9130. this._lastSecAverage = 0;
  9131. this._current = 0;
  9132. this._totalValueCount = 0;
  9133. this._totalAccumulated = 0;
  9134. this._lastSecAccumulated = 0;
  9135. this._lastSecTime = 0;
  9136. this._lastSecValueCount = 0;
  9137. }
  9138. Object.defineProperty(PerfCounter.prototype, "min", {
  9139. /**
  9140. * Returns the smallest value ever
  9141. */
  9142. get: function () {
  9143. return this._min;
  9144. },
  9145. enumerable: true,
  9146. configurable: true
  9147. });
  9148. Object.defineProperty(PerfCounter.prototype, "max", {
  9149. /**
  9150. * Returns the biggest value ever
  9151. */
  9152. get: function () {
  9153. return this._max;
  9154. },
  9155. enumerable: true,
  9156. configurable: true
  9157. });
  9158. Object.defineProperty(PerfCounter.prototype, "average", {
  9159. /**
  9160. * Returns the average value since the performance counter is running
  9161. */
  9162. get: function () {
  9163. return this._average;
  9164. },
  9165. enumerable: true,
  9166. configurable: true
  9167. });
  9168. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9169. /**
  9170. * Returns the average value of the last second the counter was monitored
  9171. */
  9172. get: function () {
  9173. return this._lastSecAverage;
  9174. },
  9175. enumerable: true,
  9176. configurable: true
  9177. });
  9178. Object.defineProperty(PerfCounter.prototype, "current", {
  9179. /**
  9180. * Returns the current value
  9181. */
  9182. get: function () {
  9183. return this._current;
  9184. },
  9185. enumerable: true,
  9186. configurable: true
  9187. });
  9188. Object.defineProperty(PerfCounter.prototype, "total", {
  9189. get: function () {
  9190. return this._totalAccumulated;
  9191. },
  9192. enumerable: true,
  9193. configurable: true
  9194. });
  9195. Object.defineProperty(PerfCounter.prototype, "count", {
  9196. get: function () {
  9197. return this._totalValueCount;
  9198. },
  9199. enumerable: true,
  9200. configurable: true
  9201. });
  9202. /**
  9203. * Call this method to start monitoring a new frame.
  9204. * 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.
  9205. */
  9206. PerfCounter.prototype.fetchNewFrame = function () {
  9207. this._totalValueCount++;
  9208. this._current = 0;
  9209. this._lastSecValueCount++;
  9210. };
  9211. /**
  9212. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9213. * @param newCount the count value to add to the monitored count
  9214. * @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.
  9215. */
  9216. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9217. if (!PerfCounter.Enabled) {
  9218. return;
  9219. }
  9220. this._current += newCount;
  9221. if (fetchResult) {
  9222. this._fetchResult();
  9223. }
  9224. };
  9225. /**
  9226. * Start monitoring this performance counter
  9227. */
  9228. PerfCounter.prototype.beginMonitoring = function () {
  9229. if (!PerfCounter.Enabled) {
  9230. return;
  9231. }
  9232. this._startMonitoringTime = Tools.Now;
  9233. };
  9234. /**
  9235. * Compute the time lapsed since the previous beginMonitoring() call.
  9236. * @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
  9237. */
  9238. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9239. if (newFrame === void 0) { newFrame = true; }
  9240. if (!PerfCounter.Enabled) {
  9241. return;
  9242. }
  9243. if (newFrame) {
  9244. this.fetchNewFrame();
  9245. }
  9246. var currentTime = Tools.Now;
  9247. this._current = currentTime - this._startMonitoringTime;
  9248. if (newFrame) {
  9249. this._fetchResult();
  9250. }
  9251. };
  9252. PerfCounter.prototype._fetchResult = function () {
  9253. this._totalAccumulated += this._current;
  9254. this._lastSecAccumulated += this._current;
  9255. // Min/Max update
  9256. this._min = Math.min(this._min, this._current);
  9257. this._max = Math.max(this._max, this._current);
  9258. this._average = this._totalAccumulated / this._totalValueCount;
  9259. // Reset last sec?
  9260. var now = Tools.Now;
  9261. if ((now - this._lastSecTime) > 1000) {
  9262. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9263. this._lastSecTime = now;
  9264. this._lastSecAccumulated = 0;
  9265. this._lastSecValueCount = 0;
  9266. }
  9267. };
  9268. PerfCounter.Enabled = true;
  9269. return PerfCounter;
  9270. }());
  9271. BABYLON.PerfCounter = PerfCounter;
  9272. /**
  9273. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9274. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9275. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9276. * @param name The name of the class, case should be preserved
  9277. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9278. */
  9279. function className(name, module) {
  9280. return function (target) {
  9281. target["__bjsclassName__"] = name;
  9282. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9283. };
  9284. }
  9285. BABYLON.className = className;
  9286. /**
  9287. * An implementation of a loop for asynchronous functions.
  9288. */
  9289. var AsyncLoop = /** @class */ (function () {
  9290. /**
  9291. * Constroctor.
  9292. * @param iterations the number of iterations.
  9293. * @param _fn the function to run each iteration
  9294. * @param _successCallback the callback that will be called upon succesful execution
  9295. * @param offset starting offset.
  9296. */
  9297. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9298. if (offset === void 0) { offset = 0; }
  9299. this.iterations = iterations;
  9300. this._fn = _fn;
  9301. this._successCallback = _successCallback;
  9302. this.index = offset - 1;
  9303. this._done = false;
  9304. }
  9305. /**
  9306. * Execute the next iteration. Must be called after the last iteration was finished.
  9307. */
  9308. AsyncLoop.prototype.executeNext = function () {
  9309. if (!this._done) {
  9310. if (this.index + 1 < this.iterations) {
  9311. ++this.index;
  9312. this._fn(this);
  9313. }
  9314. else {
  9315. this.breakLoop();
  9316. }
  9317. }
  9318. };
  9319. /**
  9320. * Break the loop and run the success callback.
  9321. */
  9322. AsyncLoop.prototype.breakLoop = function () {
  9323. this._done = true;
  9324. this._successCallback();
  9325. };
  9326. /**
  9327. * Helper function
  9328. */
  9329. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9330. if (offset === void 0) { offset = 0; }
  9331. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9332. loop.executeNext();
  9333. return loop;
  9334. };
  9335. /**
  9336. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9337. * @param iterations total number of iterations
  9338. * @param syncedIterations number of synchronous iterations in each async iteration.
  9339. * @param fn the function to call each iteration.
  9340. * @param callback a success call back that will be called when iterating stops.
  9341. * @param breakFunction a break condition (optional)
  9342. * @param timeout timeout settings for the setTimeout function. default - 0.
  9343. * @constructor
  9344. */
  9345. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9346. if (timeout === void 0) { timeout = 0; }
  9347. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9348. if (breakFunction && breakFunction())
  9349. loop.breakLoop();
  9350. else {
  9351. setTimeout(function () {
  9352. for (var i = 0; i < syncedIterations; ++i) {
  9353. var iteration = (loop.index * syncedIterations) + i;
  9354. if (iteration >= iterations)
  9355. break;
  9356. fn(iteration);
  9357. if (breakFunction && breakFunction()) {
  9358. loop.breakLoop();
  9359. break;
  9360. }
  9361. }
  9362. loop.executeNext();
  9363. }, timeout);
  9364. }
  9365. }, callback);
  9366. };
  9367. return AsyncLoop;
  9368. }());
  9369. BABYLON.AsyncLoop = AsyncLoop;
  9370. })(BABYLON || (BABYLON = {}));
  9371. //# sourceMappingURL=babylon.tools.js.map
  9372. var BABYLON;
  9373. (function (BABYLON) {
  9374. var PromiseStates;
  9375. (function (PromiseStates) {
  9376. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9377. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9378. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9379. })(PromiseStates || (PromiseStates = {}));
  9380. var FulFillmentAgregator = /** @class */ (function () {
  9381. function FulFillmentAgregator() {
  9382. this.count = 0;
  9383. this.target = 0;
  9384. this.results = [];
  9385. }
  9386. return FulFillmentAgregator;
  9387. }());
  9388. var InternalPromise = /** @class */ (function () {
  9389. function InternalPromise(resolver) {
  9390. var _this = this;
  9391. this._state = PromiseStates.Pending;
  9392. this._children = new Array();
  9393. this._rejectWasConsumed = false;
  9394. if (!resolver) {
  9395. return;
  9396. }
  9397. try {
  9398. resolver(function (value) {
  9399. _this._resolve(value);
  9400. }, function (reason) {
  9401. _this._reject(reason);
  9402. });
  9403. }
  9404. catch (e) {
  9405. this._reject(e);
  9406. }
  9407. }
  9408. InternalPromise.prototype.catch = function (onRejected) {
  9409. return this.then(undefined, onRejected);
  9410. };
  9411. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9412. var _this = this;
  9413. var newPromise = new InternalPromise();
  9414. newPromise._onFulfilled = onFulfilled;
  9415. newPromise._onRejected = onRejected;
  9416. // Composition
  9417. this._children.push(newPromise);
  9418. if (this._state !== PromiseStates.Pending) {
  9419. BABYLON.Tools.SetImmediate(function () {
  9420. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9421. var returnedValue = newPromise._resolve(_this._result);
  9422. if (returnedValue !== undefined && returnedValue !== null) {
  9423. if (returnedValue._state !== undefined) {
  9424. var returnedPromise = returnedValue;
  9425. newPromise._children.push(returnedPromise);
  9426. newPromise = returnedPromise;
  9427. }
  9428. else {
  9429. newPromise._result = returnedValue;
  9430. }
  9431. }
  9432. }
  9433. else {
  9434. newPromise._reject(_this._reason);
  9435. }
  9436. });
  9437. }
  9438. return newPromise;
  9439. };
  9440. InternalPromise.prototype._moveChildren = function (children) {
  9441. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9442. if (this._state === PromiseStates.Fulfilled) {
  9443. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9444. var child = _b[_i];
  9445. child._resolve(this._result);
  9446. }
  9447. }
  9448. else if (this._state === PromiseStates.Rejected) {
  9449. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9450. var child = _d[_c];
  9451. child._reject(this._reason);
  9452. }
  9453. }
  9454. var _a;
  9455. };
  9456. InternalPromise.prototype._resolve = function (value) {
  9457. try {
  9458. this._state = PromiseStates.Fulfilled;
  9459. this._result = value;
  9460. var returnedValue = null;
  9461. if (this._onFulfilled) {
  9462. returnedValue = this._onFulfilled(value);
  9463. }
  9464. if (returnedValue !== undefined && returnedValue !== null) {
  9465. if (returnedValue._state !== undefined) {
  9466. // Transmit children
  9467. var returnedPromise = returnedValue;
  9468. returnedPromise._moveChildren(this._children);
  9469. }
  9470. else {
  9471. value = returnedValue;
  9472. }
  9473. }
  9474. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9475. var child = _a[_i];
  9476. child._resolve(value);
  9477. }
  9478. this._children.length = 0;
  9479. delete this._onFulfilled;
  9480. delete this._onRejected;
  9481. return returnedValue;
  9482. }
  9483. catch (e) {
  9484. this._reject(e, true);
  9485. }
  9486. return null;
  9487. };
  9488. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9489. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9490. this._state = PromiseStates.Rejected;
  9491. this._reason = reason;
  9492. if (this._onRejected && !onLocalThrow) {
  9493. try {
  9494. this._onRejected(reason);
  9495. this._rejectWasConsumed = true;
  9496. }
  9497. catch (e) {
  9498. reason = e;
  9499. }
  9500. }
  9501. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9502. var child = _a[_i];
  9503. if (this._rejectWasConsumed) {
  9504. child._resolve(null);
  9505. }
  9506. else {
  9507. child._reject(reason);
  9508. }
  9509. }
  9510. this._children.length = 0;
  9511. delete this._onFulfilled;
  9512. delete this._onRejected;
  9513. };
  9514. InternalPromise.resolve = function (value) {
  9515. var newPromise = new InternalPromise();
  9516. newPromise._resolve(value);
  9517. return newPromise;
  9518. };
  9519. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9520. promise.then(function (value) {
  9521. agregator.results[index] = value;
  9522. agregator.count++;
  9523. if (agregator.count === agregator.target) {
  9524. agregator.rootPromise._resolve(agregator.results);
  9525. }
  9526. return null;
  9527. }, function (reason) {
  9528. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9529. agregator.rootPromise._reject(reason);
  9530. }
  9531. });
  9532. };
  9533. InternalPromise.all = function (promises) {
  9534. var newPromise = new InternalPromise();
  9535. var agregator = new FulFillmentAgregator();
  9536. agregator.target = promises.length;
  9537. agregator.rootPromise = newPromise;
  9538. if (promises.length) {
  9539. for (var index = 0; index < promises.length; index++) {
  9540. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9541. }
  9542. }
  9543. else {
  9544. newPromise._resolve([]);
  9545. }
  9546. return newPromise;
  9547. };
  9548. return InternalPromise;
  9549. }());
  9550. /**
  9551. * Helper class that provides a small promise polyfill
  9552. */
  9553. var PromisePolyfill = /** @class */ (function () {
  9554. function PromisePolyfill() {
  9555. }
  9556. /**
  9557. * Static function used to check if the polyfill is required
  9558. * If this is the case then the function will inject the polyfill to window.Promise
  9559. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9560. */
  9561. PromisePolyfill.Apply = function (force) {
  9562. if (force === void 0) { force = false; }
  9563. if (force || typeof Promise === 'undefined') {
  9564. var root = window;
  9565. root.Promise = InternalPromise;
  9566. }
  9567. };
  9568. return PromisePolyfill;
  9569. }());
  9570. BABYLON.PromisePolyfill = PromisePolyfill;
  9571. })(BABYLON || (BABYLON = {}));
  9572. //# sourceMappingURL=babylon.promise.js.map
  9573. var BABYLON;
  9574. (function (BABYLON) {
  9575. var _AlphaState = /** @class */ (function () {
  9576. /**
  9577. * Initializes the state.
  9578. */
  9579. function _AlphaState() {
  9580. this._isAlphaBlendDirty = false;
  9581. this._isBlendFunctionParametersDirty = false;
  9582. this._isBlendEquationParametersDirty = false;
  9583. this._isBlendConstantsDirty = false;
  9584. this._alphaBlend = false;
  9585. this._blendFunctionParameters = new Array(4);
  9586. this._blendEquationParameters = new Array(2);
  9587. this._blendConstants = new Array(4);
  9588. this.reset();
  9589. }
  9590. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9591. get: function () {
  9592. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9598. get: function () {
  9599. return this._alphaBlend;
  9600. },
  9601. set: function (value) {
  9602. if (this._alphaBlend === value) {
  9603. return;
  9604. }
  9605. this._alphaBlend = value;
  9606. this._isAlphaBlendDirty = true;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9612. if (this._blendConstants[0] === r &&
  9613. this._blendConstants[1] === g &&
  9614. this._blendConstants[2] === b &&
  9615. this._blendConstants[3] === a) {
  9616. return;
  9617. }
  9618. this._blendConstants[0] = r;
  9619. this._blendConstants[1] = g;
  9620. this._blendConstants[2] = b;
  9621. this._blendConstants[3] = a;
  9622. this._isBlendConstantsDirty = true;
  9623. };
  9624. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9625. if (this._blendFunctionParameters[0] === value0 &&
  9626. this._blendFunctionParameters[1] === value1 &&
  9627. this._blendFunctionParameters[2] === value2 &&
  9628. this._blendFunctionParameters[3] === value3) {
  9629. return;
  9630. }
  9631. this._blendFunctionParameters[0] = value0;
  9632. this._blendFunctionParameters[1] = value1;
  9633. this._blendFunctionParameters[2] = value2;
  9634. this._blendFunctionParameters[3] = value3;
  9635. this._isBlendFunctionParametersDirty = true;
  9636. };
  9637. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9638. if (this._blendEquationParameters[0] === rgb &&
  9639. this._blendEquationParameters[1] === alpha) {
  9640. return;
  9641. }
  9642. this._blendEquationParameters[0] = rgb;
  9643. this._blendEquationParameters[1] = alpha;
  9644. this._isBlendEquationParametersDirty = true;
  9645. };
  9646. _AlphaState.prototype.reset = function () {
  9647. this._alphaBlend = false;
  9648. this._blendFunctionParameters[0] = null;
  9649. this._blendFunctionParameters[1] = null;
  9650. this._blendFunctionParameters[2] = null;
  9651. this._blendFunctionParameters[3] = null;
  9652. this._blendEquationParameters[0] = null;
  9653. this._blendEquationParameters[1] = null;
  9654. this._blendConstants[0] = null;
  9655. this._blendConstants[1] = null;
  9656. this._blendConstants[2] = null;
  9657. this._blendConstants[3] = null;
  9658. this._isAlphaBlendDirty = true;
  9659. this._isBlendFunctionParametersDirty = false;
  9660. this._isBlendEquationParametersDirty = false;
  9661. this._isBlendConstantsDirty = false;
  9662. };
  9663. _AlphaState.prototype.apply = function (gl) {
  9664. if (!this.isDirty) {
  9665. return;
  9666. }
  9667. // Alpha blend
  9668. if (this._isAlphaBlendDirty) {
  9669. if (this._alphaBlend) {
  9670. gl.enable(gl.BLEND);
  9671. }
  9672. else {
  9673. gl.disable(gl.BLEND);
  9674. }
  9675. this._isAlphaBlendDirty = false;
  9676. }
  9677. // Alpha function
  9678. if (this._isBlendFunctionParametersDirty) {
  9679. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9680. this._isBlendFunctionParametersDirty = false;
  9681. }
  9682. // Alpha equation
  9683. if (this._isBlendEquationParametersDirty) {
  9684. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9685. this._isBlendEquationParametersDirty = false;
  9686. }
  9687. // Constants
  9688. if (this._isBlendConstantsDirty) {
  9689. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9690. this._isBlendConstantsDirty = false;
  9691. }
  9692. };
  9693. return _AlphaState;
  9694. }());
  9695. BABYLON._AlphaState = _AlphaState;
  9696. })(BABYLON || (BABYLON = {}));
  9697. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9698. var BABYLON;
  9699. (function (BABYLON) {
  9700. var _DepthCullingState = /** @class */ (function () {
  9701. /**
  9702. * Initializes the state.
  9703. */
  9704. function _DepthCullingState() {
  9705. this._isDepthTestDirty = false;
  9706. this._isDepthMaskDirty = false;
  9707. this._isDepthFuncDirty = false;
  9708. this._isCullFaceDirty = false;
  9709. this._isCullDirty = false;
  9710. this._isZOffsetDirty = false;
  9711. this._isFrontFaceDirty = false;
  9712. this.reset();
  9713. }
  9714. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9715. get: function () {
  9716. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9717. },
  9718. enumerable: true,
  9719. configurable: true
  9720. });
  9721. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9722. get: function () {
  9723. return this._zOffset;
  9724. },
  9725. set: function (value) {
  9726. if (this._zOffset === value) {
  9727. return;
  9728. }
  9729. this._zOffset = value;
  9730. this._isZOffsetDirty = true;
  9731. },
  9732. enumerable: true,
  9733. configurable: true
  9734. });
  9735. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9736. get: function () {
  9737. return this._cullFace;
  9738. },
  9739. set: function (value) {
  9740. if (this._cullFace === value) {
  9741. return;
  9742. }
  9743. this._cullFace = value;
  9744. this._isCullFaceDirty = true;
  9745. },
  9746. enumerable: true,
  9747. configurable: true
  9748. });
  9749. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9750. get: function () {
  9751. return this._cull;
  9752. },
  9753. set: function (value) {
  9754. if (this._cull === value) {
  9755. return;
  9756. }
  9757. this._cull = value;
  9758. this._isCullDirty = true;
  9759. },
  9760. enumerable: true,
  9761. configurable: true
  9762. });
  9763. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9764. get: function () {
  9765. return this._depthFunc;
  9766. },
  9767. set: function (value) {
  9768. if (this._depthFunc === value) {
  9769. return;
  9770. }
  9771. this._depthFunc = value;
  9772. this._isDepthFuncDirty = true;
  9773. },
  9774. enumerable: true,
  9775. configurable: true
  9776. });
  9777. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9778. get: function () {
  9779. return this._depthMask;
  9780. },
  9781. set: function (value) {
  9782. if (this._depthMask === value) {
  9783. return;
  9784. }
  9785. this._depthMask = value;
  9786. this._isDepthMaskDirty = true;
  9787. },
  9788. enumerable: true,
  9789. configurable: true
  9790. });
  9791. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9792. get: function () {
  9793. return this._depthTest;
  9794. },
  9795. set: function (value) {
  9796. if (this._depthTest === value) {
  9797. return;
  9798. }
  9799. this._depthTest = value;
  9800. this._isDepthTestDirty = true;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9806. get: function () {
  9807. return this._frontFace;
  9808. },
  9809. set: function (value) {
  9810. if (this._frontFace === value) {
  9811. return;
  9812. }
  9813. this._frontFace = value;
  9814. this._isFrontFaceDirty = true;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. _DepthCullingState.prototype.reset = function () {
  9820. this._depthMask = true;
  9821. this._depthTest = true;
  9822. this._depthFunc = null;
  9823. this._cullFace = null;
  9824. this._cull = null;
  9825. this._zOffset = 0;
  9826. this._frontFace = null;
  9827. this._isDepthTestDirty = true;
  9828. this._isDepthMaskDirty = true;
  9829. this._isDepthFuncDirty = false;
  9830. this._isCullFaceDirty = false;
  9831. this._isCullDirty = false;
  9832. this._isZOffsetDirty = false;
  9833. this._isFrontFaceDirty = false;
  9834. };
  9835. _DepthCullingState.prototype.apply = function (gl) {
  9836. if (!this.isDirty) {
  9837. return;
  9838. }
  9839. // Cull
  9840. if (this._isCullDirty) {
  9841. if (this.cull) {
  9842. gl.enable(gl.CULL_FACE);
  9843. }
  9844. else {
  9845. gl.disable(gl.CULL_FACE);
  9846. }
  9847. this._isCullDirty = false;
  9848. }
  9849. // Cull face
  9850. if (this._isCullFaceDirty) {
  9851. gl.cullFace(this.cullFace);
  9852. this._isCullFaceDirty = false;
  9853. }
  9854. // Depth mask
  9855. if (this._isDepthMaskDirty) {
  9856. gl.depthMask(this.depthMask);
  9857. this._isDepthMaskDirty = false;
  9858. }
  9859. // Depth test
  9860. if (this._isDepthTestDirty) {
  9861. if (this.depthTest) {
  9862. gl.enable(gl.DEPTH_TEST);
  9863. }
  9864. else {
  9865. gl.disable(gl.DEPTH_TEST);
  9866. }
  9867. this._isDepthTestDirty = false;
  9868. }
  9869. // Depth func
  9870. if (this._isDepthFuncDirty) {
  9871. gl.depthFunc(this.depthFunc);
  9872. this._isDepthFuncDirty = false;
  9873. }
  9874. // zOffset
  9875. if (this._isZOffsetDirty) {
  9876. if (this.zOffset) {
  9877. gl.enable(gl.POLYGON_OFFSET_FILL);
  9878. gl.polygonOffset(this.zOffset, 0);
  9879. }
  9880. else {
  9881. gl.disable(gl.POLYGON_OFFSET_FILL);
  9882. }
  9883. this._isZOffsetDirty = false;
  9884. }
  9885. // Front face
  9886. if (this._isFrontFaceDirty) {
  9887. gl.frontFace(this.frontFace);
  9888. this._isFrontFaceDirty = false;
  9889. }
  9890. };
  9891. return _DepthCullingState;
  9892. }());
  9893. BABYLON._DepthCullingState = _DepthCullingState;
  9894. })(BABYLON || (BABYLON = {}));
  9895. //# sourceMappingURL=babylon.depthCullingState.js.map
  9896. var BABYLON;
  9897. (function (BABYLON) {
  9898. var _StencilState = /** @class */ (function () {
  9899. function _StencilState() {
  9900. this._isStencilTestDirty = false;
  9901. this._isStencilMaskDirty = false;
  9902. this._isStencilFuncDirty = false;
  9903. this._isStencilOpDirty = false;
  9904. this.reset();
  9905. }
  9906. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9907. get: function () {
  9908. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9909. },
  9910. enumerable: true,
  9911. configurable: true
  9912. });
  9913. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9914. get: function () {
  9915. return this._stencilFunc;
  9916. },
  9917. set: function (value) {
  9918. if (this._stencilFunc === value) {
  9919. return;
  9920. }
  9921. this._stencilFunc = value;
  9922. this._isStencilFuncDirty = true;
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9928. get: function () {
  9929. return this._stencilFuncRef;
  9930. },
  9931. set: function (value) {
  9932. if (this._stencilFuncRef === value) {
  9933. return;
  9934. }
  9935. this._stencilFuncRef = value;
  9936. this._isStencilFuncDirty = true;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9942. get: function () {
  9943. return this._stencilFuncMask;
  9944. },
  9945. set: function (value) {
  9946. if (this._stencilFuncMask === value) {
  9947. return;
  9948. }
  9949. this._stencilFuncMask = value;
  9950. this._isStencilFuncDirty = true;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9956. get: function () {
  9957. return this._stencilOpStencilFail;
  9958. },
  9959. set: function (value) {
  9960. if (this._stencilOpStencilFail === value) {
  9961. return;
  9962. }
  9963. this._stencilOpStencilFail = value;
  9964. this._isStencilOpDirty = true;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9970. get: function () {
  9971. return this._stencilOpDepthFail;
  9972. },
  9973. set: function (value) {
  9974. if (this._stencilOpDepthFail === value) {
  9975. return;
  9976. }
  9977. this._stencilOpDepthFail = value;
  9978. this._isStencilOpDirty = true;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9984. get: function () {
  9985. return this._stencilOpStencilDepthPass;
  9986. },
  9987. set: function (value) {
  9988. if (this._stencilOpStencilDepthPass === value) {
  9989. return;
  9990. }
  9991. this._stencilOpStencilDepthPass = value;
  9992. this._isStencilOpDirty = true;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9998. get: function () {
  9999. return this._stencilMask;
  10000. },
  10001. set: function (value) {
  10002. if (this._stencilMask === value) {
  10003. return;
  10004. }
  10005. this._stencilMask = value;
  10006. this._isStencilMaskDirty = true;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10012. get: function () {
  10013. return this._stencilTest;
  10014. },
  10015. set: function (value) {
  10016. if (this._stencilTest === value) {
  10017. return;
  10018. }
  10019. this._stencilTest = value;
  10020. this._isStencilTestDirty = true;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. _StencilState.prototype.reset = function () {
  10026. this._stencilTest = false;
  10027. this._stencilMask = 0xFF;
  10028. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10029. this._stencilFuncRef = 1;
  10030. this._stencilFuncMask = 0xFF;
  10031. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10032. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10033. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10034. this._isStencilTestDirty = true;
  10035. this._isStencilMaskDirty = true;
  10036. this._isStencilFuncDirty = true;
  10037. this._isStencilOpDirty = true;
  10038. };
  10039. _StencilState.prototype.apply = function (gl) {
  10040. if (!this.isDirty) {
  10041. return;
  10042. }
  10043. // Stencil test
  10044. if (this._isStencilTestDirty) {
  10045. if (this.stencilTest) {
  10046. gl.enable(gl.STENCIL_TEST);
  10047. }
  10048. else {
  10049. gl.disable(gl.STENCIL_TEST);
  10050. }
  10051. this._isStencilTestDirty = false;
  10052. }
  10053. // Stencil mask
  10054. if (this._isStencilMaskDirty) {
  10055. gl.stencilMask(this.stencilMask);
  10056. this._isStencilMaskDirty = false;
  10057. }
  10058. // Stencil func
  10059. if (this._isStencilFuncDirty) {
  10060. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10061. this._isStencilFuncDirty = false;
  10062. }
  10063. // Stencil op
  10064. if (this._isStencilOpDirty) {
  10065. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10066. this._isStencilOpDirty = false;
  10067. }
  10068. };
  10069. return _StencilState;
  10070. }());
  10071. BABYLON._StencilState = _StencilState;
  10072. })(BABYLON || (BABYLON = {}));
  10073. //# sourceMappingURL=babylon.stencilState.js.map
  10074. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10075. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10076. s = arguments[i];
  10077. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10078. t[p] = s[p];
  10079. }
  10080. return t;
  10081. };
  10082. var BABYLON;
  10083. (function (BABYLON) {
  10084. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10085. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10086. };
  10087. var compileRawShader = function (gl, source, type) {
  10088. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10089. gl.shaderSource(shader, source);
  10090. gl.compileShader(shader);
  10091. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10092. var log = gl.getShaderInfoLog(shader);
  10093. if (log) {
  10094. throw new Error(log);
  10095. }
  10096. }
  10097. if (!shader) {
  10098. throw new Error("Something went wrong while compile the shader.");
  10099. }
  10100. return shader;
  10101. };
  10102. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10103. var magFilter = gl.NEAREST;
  10104. var minFilter = gl.NEAREST;
  10105. switch (samplingMode) {
  10106. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10107. magFilter = gl.LINEAR;
  10108. if (generateMipMaps) {
  10109. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10110. }
  10111. else {
  10112. minFilter = gl.LINEAR;
  10113. }
  10114. break;
  10115. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10116. magFilter = gl.LINEAR;
  10117. if (generateMipMaps) {
  10118. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10119. }
  10120. else {
  10121. minFilter = gl.LINEAR;
  10122. }
  10123. break;
  10124. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10125. magFilter = gl.NEAREST;
  10126. if (generateMipMaps) {
  10127. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10128. }
  10129. else {
  10130. minFilter = gl.NEAREST;
  10131. }
  10132. break;
  10133. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10134. magFilter = gl.NEAREST;
  10135. if (generateMipMaps) {
  10136. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10137. }
  10138. else {
  10139. minFilter = gl.NEAREST;
  10140. }
  10141. break;
  10142. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10143. magFilter = gl.NEAREST;
  10144. if (generateMipMaps) {
  10145. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10146. }
  10147. else {
  10148. minFilter = gl.LINEAR;
  10149. }
  10150. break;
  10151. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10152. magFilter = gl.NEAREST;
  10153. if (generateMipMaps) {
  10154. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10155. }
  10156. else {
  10157. minFilter = gl.LINEAR;
  10158. }
  10159. break;
  10160. case BABYLON.Texture.NEAREST_LINEAR:
  10161. magFilter = gl.NEAREST;
  10162. minFilter = gl.LINEAR;
  10163. break;
  10164. case BABYLON.Texture.NEAREST_NEAREST:
  10165. magFilter = gl.NEAREST;
  10166. minFilter = gl.NEAREST;
  10167. break;
  10168. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10169. magFilter = gl.LINEAR;
  10170. if (generateMipMaps) {
  10171. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10172. }
  10173. else {
  10174. minFilter = gl.NEAREST;
  10175. }
  10176. break;
  10177. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10178. magFilter = gl.LINEAR;
  10179. if (generateMipMaps) {
  10180. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10181. }
  10182. else {
  10183. minFilter = gl.NEAREST;
  10184. }
  10185. break;
  10186. case BABYLON.Texture.LINEAR_LINEAR:
  10187. magFilter = gl.LINEAR;
  10188. minFilter = gl.LINEAR;
  10189. break;
  10190. case BABYLON.Texture.LINEAR_NEAREST:
  10191. magFilter = gl.LINEAR;
  10192. minFilter = gl.NEAREST;
  10193. break;
  10194. }
  10195. return {
  10196. min: minFilter,
  10197. mag: magFilter
  10198. };
  10199. };
  10200. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10201. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10202. var img;
  10203. var onload = function () {
  10204. loadedImages[index] = img;
  10205. loadedImages._internalCount++;
  10206. if (scene) {
  10207. scene._removePendingData(img);
  10208. }
  10209. if (loadedImages._internalCount === 6) {
  10210. onfinish(loadedImages);
  10211. }
  10212. };
  10213. var onerror = function (message, exception) {
  10214. if (scene) {
  10215. scene._removePendingData(img);
  10216. }
  10217. if (onErrorCallBack) {
  10218. onErrorCallBack(message, exception);
  10219. }
  10220. };
  10221. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10222. if (scene) {
  10223. scene._addPendingData(img);
  10224. }
  10225. };
  10226. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10227. if (onError === void 0) { onError = null; }
  10228. var loadedImages = [];
  10229. loadedImages._internalCount = 0;
  10230. for (var index = 0; index < 6; index++) {
  10231. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10232. }
  10233. };
  10234. var BufferPointer = /** @class */ (function () {
  10235. function BufferPointer() {
  10236. }
  10237. return BufferPointer;
  10238. }());
  10239. var InstancingAttributeInfo = /** @class */ (function () {
  10240. function InstancingAttributeInfo() {
  10241. }
  10242. return InstancingAttributeInfo;
  10243. }());
  10244. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10245. /**
  10246. * Define options used to create a render target texture
  10247. */
  10248. var RenderTargetCreationOptions = /** @class */ (function () {
  10249. function RenderTargetCreationOptions() {
  10250. }
  10251. return RenderTargetCreationOptions;
  10252. }());
  10253. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10254. /**
  10255. * Regroup several parameters relative to the browser in use
  10256. */
  10257. var EngineCapabilities = /** @class */ (function () {
  10258. function EngineCapabilities() {
  10259. }
  10260. return EngineCapabilities;
  10261. }());
  10262. BABYLON.EngineCapabilities = EngineCapabilities;
  10263. /**
  10264. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10265. */
  10266. var Engine = /** @class */ (function () {
  10267. /**
  10268. * @constructor
  10269. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10270. * @param antialias defines enable antialiasing (default: false)
  10271. * @param options defines further options to be sent to the getContext() function
  10272. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10273. */
  10274. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10275. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10276. var _this = this;
  10277. // Public members
  10278. this.forcePOTTextures = false;
  10279. this.isFullscreen = false;
  10280. this.isPointerLock = false;
  10281. this.cullBackFaces = true;
  10282. this.renderEvenInBackground = true;
  10283. this.preventCacheWipeBetweenFrames = false;
  10284. // To enable/disable IDB support and avoid XHR on .manifest
  10285. this.enableOfflineSupport = false;
  10286. this.scenes = new Array();
  10287. this.postProcesses = new Array();
  10288. // Observables
  10289. /**
  10290. * Observable event triggered each time the rendering canvas is resized
  10291. */
  10292. this.onResizeObservable = new BABYLON.Observable();
  10293. /**
  10294. * Observable event triggered each time the canvas loses focus
  10295. */
  10296. this.onCanvasBlurObservable = new BABYLON.Observable();
  10297. /**
  10298. * Observable event triggered each time the canvas gains focus
  10299. */
  10300. this.onCanvasFocusObservable = new BABYLON.Observable();
  10301. /**
  10302. * Observable event triggered each time the canvas receives pointerout event
  10303. */
  10304. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10305. /**
  10306. * Observable event triggered before each texture is initialized
  10307. */
  10308. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10309. //WebVR
  10310. this._vrDisplay = undefined;
  10311. this._vrSupported = false;
  10312. this._vrExclusivePointerMode = false;
  10313. // Uniform buffers list
  10314. this.disableUniformBuffers = false;
  10315. this._uniformBuffers = new Array();
  10316. // Observables
  10317. /**
  10318. * Observable raised when the engine begins a new frame
  10319. */
  10320. this.onBeginFrameObservable = new BABYLON.Observable();
  10321. /**
  10322. * Observable raised when the engine ends the current frame
  10323. */
  10324. this.onEndFrameObservable = new BABYLON.Observable();
  10325. /**
  10326. * Observable raised when the engine is about to compile a shader
  10327. */
  10328. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10329. /**
  10330. * Observable raised when the engine has jsut compiled a shader
  10331. */
  10332. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10333. this._windowIsBackground = false;
  10334. this._webGLVersion = 1.0;
  10335. this._badOS = false;
  10336. this._badDesktopOS = false;
  10337. /**
  10338. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10339. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10340. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10341. */
  10342. this.disableTextureBindingOptimization = false;
  10343. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10344. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10345. this.onVRRequestPresentStart = new BABYLON.Observable();
  10346. this._colorWrite = true;
  10347. this._drawCalls = new BABYLON.PerfCounter();
  10348. this._textureCollisions = new BABYLON.PerfCounter();
  10349. this._renderingQueueLaunched = false;
  10350. this._activeRenderLoops = new Array();
  10351. // Deterministic lockstepMaxSteps
  10352. this._deterministicLockstep = false;
  10353. this._lockstepMaxSteps = 4;
  10354. // Lost context
  10355. this.onContextLostObservable = new BABYLON.Observable();
  10356. this.onContextRestoredObservable = new BABYLON.Observable();
  10357. this._contextWasLost = false;
  10358. this._doNotHandleContextLost = false;
  10359. // FPS
  10360. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10361. this._fps = 60;
  10362. this._deltaTime = 0;
  10363. /**
  10364. * Turn this value on if you want to pause FPS computation when in background
  10365. */
  10366. this.disablePerformanceMonitorInBackground = false;
  10367. // States
  10368. this._depthCullingState = new BABYLON._DepthCullingState();
  10369. this._stencilState = new BABYLON._StencilState();
  10370. this._alphaState = new BABYLON._AlphaState();
  10371. this._alphaMode = Engine.ALPHA_DISABLE;
  10372. // Cache
  10373. this._internalTexturesCache = new Array();
  10374. this._activeChannel = 0;
  10375. this._currentTextureChannel = -1;
  10376. this._boundTexturesCache = {};
  10377. this._compiledEffects = {};
  10378. this._vertexAttribArraysEnabled = [];
  10379. this._uintIndicesCurrentlySet = false;
  10380. this._currentBoundBuffer = new Array();
  10381. this._currentBufferPointers = new Array();
  10382. this._currentInstanceLocations = new Array();
  10383. this._currentInstanceBuffers = new Array();
  10384. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10385. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10386. this._vaoRecordInProgress = false;
  10387. this._mustWipeVertexAttributes = false;
  10388. this._nextFreeTextureSlots = new Array();
  10389. this._maxSimultaneousTextures = 0;
  10390. this._activeRequests = new Array();
  10391. // Hardware supported Compressed Textures
  10392. this._texturesSupported = new Array();
  10393. this._onVRFullScreenTriggered = function () {
  10394. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10395. //get the old size before we change
  10396. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10397. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10398. //get the width and height, change the render size
  10399. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10400. _this.setHardwareScalingLevel(1);
  10401. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10402. }
  10403. else {
  10404. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10405. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10406. }
  10407. };
  10408. this._boundUniforms = {};
  10409. // Register promises
  10410. BABYLON.PromisePolyfill.Apply();
  10411. var canvas = null;
  10412. Engine.Instances.push(this);
  10413. if (!canvasOrContext) {
  10414. return;
  10415. }
  10416. options = options || {};
  10417. if (canvasOrContext.getContext) {
  10418. canvas = canvasOrContext;
  10419. this._renderingCanvas = canvas;
  10420. if (antialias != null) {
  10421. options.antialias = antialias;
  10422. }
  10423. if (options.deterministicLockstep === undefined) {
  10424. options.deterministicLockstep = false;
  10425. }
  10426. if (options.lockstepMaxSteps === undefined) {
  10427. options.lockstepMaxSteps = 4;
  10428. }
  10429. if (options.preserveDrawingBuffer === undefined) {
  10430. options.preserveDrawingBuffer = false;
  10431. }
  10432. if (options.audioEngine === undefined) {
  10433. options.audioEngine = true;
  10434. }
  10435. if (options.stencil === undefined) {
  10436. options.stencil = true;
  10437. }
  10438. this._deterministicLockstep = options.deterministicLockstep;
  10439. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10440. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10441. // Exceptions
  10442. if (navigator && navigator.userAgent) {
  10443. var ua = navigator.userAgent;
  10444. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10445. var exception = _a[_i];
  10446. var key = exception.key;
  10447. var targets = exception.targets;
  10448. if (ua.indexOf(key) > -1) {
  10449. if (exception.capture && exception.captureConstraint) {
  10450. var capture = exception.capture;
  10451. var constraint = exception.captureConstraint;
  10452. var regex = new RegExp(capture);
  10453. var matches = regex.exec(ua);
  10454. if (matches && matches.length > 0) {
  10455. var capturedValue = parseInt(matches[matches.length - 1]);
  10456. if (capturedValue >= constraint) {
  10457. continue;
  10458. }
  10459. }
  10460. }
  10461. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10462. var target = targets_1[_b];
  10463. switch (target) {
  10464. case "uniformBuffer":
  10465. this.disableUniformBuffers = true;
  10466. break;
  10467. case "textureBindingOptimization":
  10468. this.disableTextureBindingOptimization = true;
  10469. break;
  10470. }
  10471. }
  10472. break;
  10473. }
  10474. }
  10475. }
  10476. // GL
  10477. if (!options.disableWebGL2Support) {
  10478. try {
  10479. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10480. if (this._gl) {
  10481. this._webGLVersion = 2.0;
  10482. }
  10483. }
  10484. catch (e) {
  10485. // Do nothing
  10486. }
  10487. }
  10488. if (!this._gl) {
  10489. if (!canvas) {
  10490. throw new Error("The provided canvas is null or undefined.");
  10491. }
  10492. try {
  10493. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10494. }
  10495. catch (e) {
  10496. throw new Error("WebGL not supported");
  10497. }
  10498. }
  10499. if (!this._gl) {
  10500. throw new Error("WebGL not supported");
  10501. }
  10502. this._onCanvasFocus = function () {
  10503. _this.onCanvasFocusObservable.notifyObservers(_this);
  10504. };
  10505. this._onCanvasBlur = function () {
  10506. _this.onCanvasBlurObservable.notifyObservers(_this);
  10507. };
  10508. canvas.addEventListener("focus", this._onCanvasFocus);
  10509. canvas.addEventListener("blur", this._onCanvasBlur);
  10510. this._onBlur = function () {
  10511. if (_this.disablePerformanceMonitorInBackground) {
  10512. _this._performanceMonitor.disable();
  10513. }
  10514. _this._windowIsBackground = true;
  10515. };
  10516. this._onFocus = function () {
  10517. if (_this.disablePerformanceMonitorInBackground) {
  10518. _this._performanceMonitor.enable();
  10519. }
  10520. _this._windowIsBackground = false;
  10521. };
  10522. this._onCanvasPointerOut = function () {
  10523. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10524. };
  10525. window.addEventListener("blur", this._onBlur);
  10526. window.addEventListener("focus", this._onFocus);
  10527. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10528. // Context lost
  10529. if (!this._doNotHandleContextLost) {
  10530. this._onContextLost = function (evt) {
  10531. evt.preventDefault();
  10532. _this._contextWasLost = true;
  10533. BABYLON.Tools.Warn("WebGL context lost.");
  10534. _this.onContextLostObservable.notifyObservers(_this);
  10535. };
  10536. this._onContextRestored = function (evt) {
  10537. // Adding a timeout to avoid race condition at browser level
  10538. setTimeout(function () {
  10539. // Rebuild gl context
  10540. _this._initGLContext();
  10541. // Rebuild effects
  10542. _this._rebuildEffects();
  10543. // Rebuild textures
  10544. _this._rebuildInternalTextures();
  10545. // Rebuild buffers
  10546. _this._rebuildBuffers();
  10547. // Cache
  10548. _this.wipeCaches(true);
  10549. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10550. _this.onContextRestoredObservable.notifyObservers(_this);
  10551. _this._contextWasLost = false;
  10552. }, 0);
  10553. };
  10554. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10555. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10556. }
  10557. }
  10558. else {
  10559. this._gl = canvasOrContext;
  10560. this._renderingCanvas = this._gl.canvas;
  10561. if (this._gl.renderbufferStorageMultisample) {
  10562. this._webGLVersion = 2.0;
  10563. }
  10564. options.stencil = this._gl.getContextAttributes().stencil;
  10565. }
  10566. // Viewport
  10567. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10568. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10569. this.resize();
  10570. this._isStencilEnable = options.stencil ? true : false;
  10571. this._initGLContext();
  10572. if (canvas) {
  10573. // Fullscreen
  10574. this._onFullscreenChange = function () {
  10575. if (document.fullscreen !== undefined) {
  10576. _this.isFullscreen = document.fullscreen;
  10577. }
  10578. else if (document.mozFullScreen !== undefined) {
  10579. _this.isFullscreen = document.mozFullScreen;
  10580. }
  10581. else if (document.webkitIsFullScreen !== undefined) {
  10582. _this.isFullscreen = document.webkitIsFullScreen;
  10583. }
  10584. else if (document.msIsFullScreen !== undefined) {
  10585. _this.isFullscreen = document.msIsFullScreen;
  10586. }
  10587. // Pointer lock
  10588. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10589. canvas.requestPointerLock = canvas.requestPointerLock ||
  10590. canvas.msRequestPointerLock ||
  10591. canvas.mozRequestPointerLock ||
  10592. canvas.webkitRequestPointerLock;
  10593. if (canvas.requestPointerLock) {
  10594. canvas.requestPointerLock();
  10595. }
  10596. }
  10597. };
  10598. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10599. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10600. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10601. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10602. // Pointer lock
  10603. this._onPointerLockChange = function () {
  10604. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10605. document.webkitPointerLockElement === canvas ||
  10606. document.msPointerLockElement === canvas ||
  10607. document.pointerLockElement === canvas);
  10608. };
  10609. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10610. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10611. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10612. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10613. this._onVRDisplayPointerRestricted = function () {
  10614. if (canvas) {
  10615. canvas.requestPointerLock();
  10616. }
  10617. };
  10618. this._onVRDisplayPointerUnrestricted = function () {
  10619. document.exitPointerLock();
  10620. };
  10621. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10622. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10623. }
  10624. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10625. Engine.audioEngine = new BABYLON.AudioEngine();
  10626. }
  10627. // Prepare buffer pointers
  10628. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10629. this._currentBufferPointers[i] = new BufferPointer();
  10630. }
  10631. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10632. // Load WebVR Devices
  10633. if (options.autoEnableWebVR) {
  10634. this.initWebVR();
  10635. }
  10636. // Detect if we are running on a faulty buggy OS.
  10637. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10638. // Detect if we are running on a faulty buggy desktop OS.
  10639. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10640. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10641. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10642. }
  10643. Object.defineProperty(Engine, "LastCreatedEngine", {
  10644. get: function () {
  10645. if (Engine.Instances.length === 0) {
  10646. return null;
  10647. }
  10648. return Engine.Instances[Engine.Instances.length - 1];
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(Engine, "LastCreatedScene", {
  10654. get: function () {
  10655. var lastCreatedEngine = Engine.LastCreatedEngine;
  10656. if (!lastCreatedEngine) {
  10657. return null;
  10658. }
  10659. if (lastCreatedEngine.scenes.length === 0) {
  10660. return null;
  10661. }
  10662. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. /**
  10668. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10669. */
  10670. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10671. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10672. var engine = Engine.Instances[engineIndex];
  10673. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10674. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10675. }
  10676. }
  10677. };
  10678. Object.defineProperty(Engine, "NEVER", {
  10679. get: function () {
  10680. return Engine._NEVER;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(Engine, "ALWAYS", {
  10686. get: function () {
  10687. return Engine._ALWAYS;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(Engine, "LESS", {
  10693. get: function () {
  10694. return Engine._LESS;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(Engine, "EQUAL", {
  10700. get: function () {
  10701. return Engine._EQUAL;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(Engine, "LEQUAL", {
  10707. get: function () {
  10708. return Engine._LEQUAL;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. Object.defineProperty(Engine, "GREATER", {
  10714. get: function () {
  10715. return Engine._GREATER;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(Engine, "GEQUAL", {
  10721. get: function () {
  10722. return Engine._GEQUAL;
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. Object.defineProperty(Engine, "NOTEQUAL", {
  10728. get: function () {
  10729. return Engine._NOTEQUAL;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(Engine, "KEEP", {
  10735. get: function () {
  10736. return Engine._KEEP;
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Object.defineProperty(Engine, "REPLACE", {
  10742. get: function () {
  10743. return Engine._REPLACE;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(Engine, "INCR", {
  10749. get: function () {
  10750. return Engine._INCR;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. Object.defineProperty(Engine, "DECR", {
  10756. get: function () {
  10757. return Engine._DECR;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(Engine, "INVERT", {
  10763. get: function () {
  10764. return Engine._INVERT;
  10765. },
  10766. enumerable: true,
  10767. configurable: true
  10768. });
  10769. Object.defineProperty(Engine, "INCR_WRAP", {
  10770. get: function () {
  10771. return Engine._INCR_WRAP;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(Engine, "DECR_WRAP", {
  10777. get: function () {
  10778. return Engine._DECR_WRAP;
  10779. },
  10780. enumerable: true,
  10781. configurable: true
  10782. });
  10783. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10784. get: function () {
  10785. return Engine._ALPHA_DISABLE;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10791. get: function () {
  10792. return Engine._ALPHA_ONEONE;
  10793. },
  10794. enumerable: true,
  10795. configurable: true
  10796. });
  10797. Object.defineProperty(Engine, "ALPHA_ADD", {
  10798. get: function () {
  10799. return Engine._ALPHA_ADD;
  10800. },
  10801. enumerable: true,
  10802. configurable: true
  10803. });
  10804. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10805. get: function () {
  10806. return Engine._ALPHA_COMBINE;
  10807. },
  10808. enumerable: true,
  10809. configurable: true
  10810. });
  10811. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10812. get: function () {
  10813. return Engine._ALPHA_SUBTRACT;
  10814. },
  10815. enumerable: true,
  10816. configurable: true
  10817. });
  10818. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10819. get: function () {
  10820. return Engine._ALPHA_MULTIPLY;
  10821. },
  10822. enumerable: true,
  10823. configurable: true
  10824. });
  10825. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10826. get: function () {
  10827. return Engine._ALPHA_MAXIMIZED;
  10828. },
  10829. enumerable: true,
  10830. configurable: true
  10831. });
  10832. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10833. get: function () {
  10834. return Engine._ALPHA_PREMULTIPLIED;
  10835. },
  10836. enumerable: true,
  10837. configurable: true
  10838. });
  10839. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10840. get: function () {
  10841. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10842. },
  10843. enumerable: true,
  10844. configurable: true
  10845. });
  10846. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10847. get: function () {
  10848. return Engine._ALPHA_INTERPOLATE;
  10849. },
  10850. enumerable: true,
  10851. configurable: true
  10852. });
  10853. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10854. get: function () {
  10855. return Engine._ALPHA_SCREENMODE;
  10856. },
  10857. enumerable: true,
  10858. configurable: true
  10859. });
  10860. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10861. get: function () {
  10862. return Engine._DELAYLOADSTATE_NONE;
  10863. },
  10864. enumerable: true,
  10865. configurable: true
  10866. });
  10867. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10868. get: function () {
  10869. return Engine._DELAYLOADSTATE_LOADED;
  10870. },
  10871. enumerable: true,
  10872. configurable: true
  10873. });
  10874. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10875. get: function () {
  10876. return Engine._DELAYLOADSTATE_LOADING;
  10877. },
  10878. enumerable: true,
  10879. configurable: true
  10880. });
  10881. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10882. get: function () {
  10883. return Engine._DELAYLOADSTATE_NOTLOADED;
  10884. },
  10885. enumerable: true,
  10886. configurable: true
  10887. });
  10888. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10889. get: function () {
  10890. return Engine._TEXTUREFORMAT_ALPHA;
  10891. },
  10892. enumerable: true,
  10893. configurable: true
  10894. });
  10895. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10896. get: function () {
  10897. return Engine._TEXTUREFORMAT_LUMINANCE;
  10898. },
  10899. enumerable: true,
  10900. configurable: true
  10901. });
  10902. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10903. /**
  10904. * R32F
  10905. */
  10906. get: function () {
  10907. return Engine._TEXTUREFORMAT_R32F;
  10908. },
  10909. enumerable: true,
  10910. configurable: true
  10911. });
  10912. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10913. /**
  10914. * RG32F
  10915. */
  10916. get: function () {
  10917. return Engine._TEXTUREFORMAT_RG32F;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10923. /**
  10924. * RGB32F
  10925. */
  10926. get: function () {
  10927. return Engine._TEXTUREFORMAT_RGB32F;
  10928. },
  10929. enumerable: true,
  10930. configurable: true
  10931. });
  10932. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10933. get: function () {
  10934. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10935. },
  10936. enumerable: true,
  10937. configurable: true
  10938. });
  10939. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10940. get: function () {
  10941. return Engine._TEXTUREFORMAT_RGB;
  10942. },
  10943. enumerable: true,
  10944. configurable: true
  10945. });
  10946. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10947. get: function () {
  10948. return Engine._TEXTUREFORMAT_RGBA;
  10949. },
  10950. enumerable: true,
  10951. configurable: true
  10952. });
  10953. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10954. get: function () {
  10955. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10956. },
  10957. enumerable: true,
  10958. configurable: true
  10959. });
  10960. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10961. get: function () {
  10962. return Engine._TEXTURETYPE_FLOAT;
  10963. },
  10964. enumerable: true,
  10965. configurable: true
  10966. });
  10967. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10968. get: function () {
  10969. return Engine._TEXTURETYPE_HALF_FLOAT;
  10970. },
  10971. enumerable: true,
  10972. configurable: true
  10973. });
  10974. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10975. get: function () {
  10976. return Engine._SCALEMODE_FLOOR;
  10977. },
  10978. enumerable: true,
  10979. configurable: true
  10980. });
  10981. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10982. get: function () {
  10983. return Engine._SCALEMODE_NEAREST;
  10984. },
  10985. enumerable: true,
  10986. configurable: true
  10987. });
  10988. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10989. get: function () {
  10990. return Engine._SCALEMODE_CEILING;
  10991. },
  10992. enumerable: true,
  10993. configurable: true
  10994. });
  10995. Object.defineProperty(Engine, "Version", {
  10996. get: function () {
  10997. return "3.2.0-alpha7";
  10998. },
  10999. enumerable: true,
  11000. configurable: true
  11001. });
  11002. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11003. get: function () {
  11004. return this._vrExclusivePointerMode;
  11005. },
  11006. enumerable: true,
  11007. configurable: true
  11008. });
  11009. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11010. get: function () {
  11011. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11017. get: function () {
  11018. return this._webGLVersion < 2 || this.forcePOTTextures;
  11019. },
  11020. enumerable: true,
  11021. configurable: true
  11022. });
  11023. Object.defineProperty(Engine.prototype, "badOS", {
  11024. get: function () {
  11025. return this._badOS;
  11026. },
  11027. enumerable: true,
  11028. configurable: true
  11029. });
  11030. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11031. get: function () {
  11032. return this._badDesktopOS;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11038. get: function () {
  11039. return this._performanceMonitor;
  11040. },
  11041. enumerable: true,
  11042. configurable: true
  11043. });
  11044. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11045. get: function () {
  11046. return this._texturesSupported;
  11047. },
  11048. enumerable: true,
  11049. configurable: true
  11050. });
  11051. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11052. get: function () {
  11053. return this._textureFormatInUse;
  11054. },
  11055. enumerable: true,
  11056. configurable: true
  11057. });
  11058. Object.defineProperty(Engine.prototype, "currentViewport", {
  11059. get: function () {
  11060. return this._cachedViewport;
  11061. },
  11062. enumerable: true,
  11063. configurable: true
  11064. });
  11065. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11066. // Empty texture
  11067. get: function () {
  11068. if (!this._emptyTexture) {
  11069. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11070. }
  11071. return this._emptyTexture;
  11072. },
  11073. enumerable: true,
  11074. configurable: true
  11075. });
  11076. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11077. get: function () {
  11078. if (!this._emptyTexture3D) {
  11079. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11080. }
  11081. return this._emptyTexture3D;
  11082. },
  11083. enumerable: true,
  11084. configurable: true
  11085. });
  11086. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11087. get: function () {
  11088. if (!this._emptyCubeTexture) {
  11089. var faceData = new Uint8Array(4);
  11090. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11091. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11092. }
  11093. return this._emptyCubeTexture;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Engine.prototype._rebuildInternalTextures = function () {
  11099. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11100. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11101. var internalTexture = currentState_1[_i];
  11102. internalTexture._rebuild();
  11103. }
  11104. };
  11105. Engine.prototype._rebuildEffects = function () {
  11106. for (var key in this._compiledEffects) {
  11107. var effect = this._compiledEffects[key];
  11108. effect._prepareEffect();
  11109. }
  11110. BABYLON.Effect.ResetCache();
  11111. };
  11112. Engine.prototype._rebuildBuffers = function () {
  11113. // Index / Vertex
  11114. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11115. var scene = _a[_i];
  11116. scene.resetCachedMaterial();
  11117. scene._rebuildGeometries();
  11118. scene._rebuildTextures();
  11119. }
  11120. // Uniforms
  11121. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11122. var uniformBuffer = _c[_b];
  11123. uniformBuffer._rebuild();
  11124. }
  11125. };
  11126. Engine.prototype._initGLContext = function () {
  11127. // Caps
  11128. this._caps = new EngineCapabilities();
  11129. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11130. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11131. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11132. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11133. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11134. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11135. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11136. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11137. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11138. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11139. // Infos
  11140. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11141. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11142. if (rendererInfo != null) {
  11143. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11144. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11145. }
  11146. if (!this._glVendor) {
  11147. this._glVendor = "Unknown vendor";
  11148. }
  11149. if (!this._glRenderer) {
  11150. this._glRenderer = "Unknown renderer";
  11151. }
  11152. // Constants
  11153. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11154. if (this._gl.RGBA16F !== 0x881A) {
  11155. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11156. }
  11157. if (this._gl.RGBA32F !== 0x8814) {
  11158. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11159. }
  11160. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11161. this._gl.DEPTH24_STENCIL8 = 35056;
  11162. }
  11163. // Extensions
  11164. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11165. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11166. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11167. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11168. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11169. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11170. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11171. 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');
  11172. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11173. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11174. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11175. this._caps.highPrecisionShaderSupported = true;
  11176. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11177. if (this._caps.timerQuery) {
  11178. if (this._webGLVersion === 1) {
  11179. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11180. }
  11181. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11182. }
  11183. // Checks if some of the format renders first to allow the use of webgl inspector.
  11184. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11185. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11186. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11187. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11188. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11189. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11190. if (this._webGLVersion > 1) {
  11191. this._gl.HALF_FLOAT_OES = 0x140B;
  11192. }
  11193. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11194. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11195. // Draw buffers
  11196. if (this._webGLVersion > 1) {
  11197. this._caps.drawBuffersExtension = true;
  11198. }
  11199. else {
  11200. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11201. if (drawBuffersExtension !== null) {
  11202. this._caps.drawBuffersExtension = true;
  11203. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11204. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11205. for (var i = 0; i < 16; i++) {
  11206. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11207. }
  11208. }
  11209. else {
  11210. this._caps.drawBuffersExtension = false;
  11211. }
  11212. }
  11213. // Depth Texture
  11214. if (this._webGLVersion > 1) {
  11215. this._caps.depthTextureExtension = true;
  11216. }
  11217. else {
  11218. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11219. if (depthTextureExtension != null) {
  11220. this._caps.depthTextureExtension = true;
  11221. }
  11222. }
  11223. // Vertex array object
  11224. if (this._webGLVersion > 1) {
  11225. this._caps.vertexArrayObject = true;
  11226. }
  11227. else {
  11228. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11229. if (vertexArrayObjectExtension != null) {
  11230. this._caps.vertexArrayObject = true;
  11231. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11232. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11233. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11234. }
  11235. else {
  11236. this._caps.vertexArrayObject = false;
  11237. }
  11238. }
  11239. // Instances count
  11240. if (this._webGLVersion > 1) {
  11241. this._caps.instancedArrays = true;
  11242. }
  11243. else {
  11244. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11245. if (instanceExtension != null) {
  11246. this._caps.instancedArrays = true;
  11247. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11248. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11249. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11250. }
  11251. else {
  11252. this._caps.instancedArrays = false;
  11253. }
  11254. }
  11255. // Intelligently add supported compressed formats in order to check for.
  11256. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11257. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11258. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11259. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11260. if (this._caps.astc)
  11261. this.texturesSupported.push('-astc.ktx');
  11262. if (this._caps.s3tc)
  11263. this.texturesSupported.push('-dxt.ktx');
  11264. if (this._caps.pvrtc)
  11265. this.texturesSupported.push('-pvrtc.ktx');
  11266. if (this._caps.etc2)
  11267. this.texturesSupported.push('-etc2.ktx');
  11268. if (this._caps.etc1)
  11269. this.texturesSupported.push('-etc1.ktx');
  11270. if (this._gl.getShaderPrecisionFormat) {
  11271. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11272. if (highp) {
  11273. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11274. }
  11275. }
  11276. // Depth buffer
  11277. this.setDepthBuffer(true);
  11278. this.setDepthFunctionToLessOrEqual();
  11279. this.setDepthWrite(true);
  11280. // Texture maps
  11281. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11282. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11283. this._nextFreeTextureSlots.push(slot);
  11284. }
  11285. };
  11286. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11287. get: function () {
  11288. return this._webGLVersion;
  11289. },
  11290. enumerable: true,
  11291. configurable: true
  11292. });
  11293. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11294. /**
  11295. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11296. */
  11297. get: function () {
  11298. return this._isStencilEnable;
  11299. },
  11300. enumerable: true,
  11301. configurable: true
  11302. });
  11303. Engine.prototype._prepareWorkingCanvas = function () {
  11304. if (this._workingCanvas) {
  11305. return;
  11306. }
  11307. this._workingCanvas = document.createElement("canvas");
  11308. var context = this._workingCanvas.getContext("2d");
  11309. if (context) {
  11310. this._workingContext = context;
  11311. }
  11312. };
  11313. Engine.prototype.resetTextureCache = function () {
  11314. for (var key in this._boundTexturesCache) {
  11315. var boundTexture = this._boundTexturesCache[key];
  11316. if (boundTexture) {
  11317. this._removeDesignatedSlot(boundTexture);
  11318. }
  11319. this._boundTexturesCache[key] = null;
  11320. }
  11321. if (!this.disableTextureBindingOptimization) {
  11322. this._nextFreeTextureSlots = [];
  11323. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11324. this._nextFreeTextureSlots.push(slot);
  11325. }
  11326. }
  11327. this._currentTextureChannel = -1;
  11328. };
  11329. Engine.prototype.isDeterministicLockStep = function () {
  11330. return this._deterministicLockstep;
  11331. };
  11332. Engine.prototype.getLockstepMaxSteps = function () {
  11333. return this._lockstepMaxSteps;
  11334. };
  11335. Engine.prototype.getGlInfo = function () {
  11336. return {
  11337. vendor: this._glVendor,
  11338. renderer: this._glRenderer,
  11339. version: this._glVersion
  11340. };
  11341. };
  11342. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11343. if (useScreen === void 0) { useScreen = false; }
  11344. var viewport = camera.viewport;
  11345. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11346. };
  11347. Engine.prototype.getRenderWidth = function (useScreen) {
  11348. if (useScreen === void 0) { useScreen = false; }
  11349. if (!useScreen && this._currentRenderTarget) {
  11350. return this._currentRenderTarget.width;
  11351. }
  11352. return this._gl.drawingBufferWidth;
  11353. };
  11354. Engine.prototype.getRenderHeight = function (useScreen) {
  11355. if (useScreen === void 0) { useScreen = false; }
  11356. if (!useScreen && this._currentRenderTarget) {
  11357. return this._currentRenderTarget.height;
  11358. }
  11359. return this._gl.drawingBufferHeight;
  11360. };
  11361. Engine.prototype.getRenderingCanvas = function () {
  11362. return this._renderingCanvas;
  11363. };
  11364. Engine.prototype.getRenderingCanvasClientRect = function () {
  11365. if (!this._renderingCanvas) {
  11366. return null;
  11367. }
  11368. return this._renderingCanvas.getBoundingClientRect();
  11369. };
  11370. Engine.prototype.setHardwareScalingLevel = function (level) {
  11371. this._hardwareScalingLevel = level;
  11372. this.resize();
  11373. };
  11374. Engine.prototype.getHardwareScalingLevel = function () {
  11375. return this._hardwareScalingLevel;
  11376. };
  11377. Engine.prototype.getLoadedTexturesCache = function () {
  11378. return this._internalTexturesCache;
  11379. };
  11380. Engine.prototype.getCaps = function () {
  11381. return this._caps;
  11382. };
  11383. Object.defineProperty(Engine.prototype, "drawCalls", {
  11384. /** The number of draw calls submitted last frame */
  11385. get: function () {
  11386. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11387. return 0;
  11388. },
  11389. enumerable: true,
  11390. configurable: true
  11391. });
  11392. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11393. get: function () {
  11394. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11395. return null;
  11396. },
  11397. enumerable: true,
  11398. configurable: true
  11399. });
  11400. Engine.prototype.getDepthFunction = function () {
  11401. return this._depthCullingState.depthFunc;
  11402. };
  11403. Engine.prototype.setDepthFunction = function (depthFunc) {
  11404. this._depthCullingState.depthFunc = depthFunc;
  11405. };
  11406. Engine.prototype.setDepthFunctionToGreater = function () {
  11407. this._depthCullingState.depthFunc = this._gl.GREATER;
  11408. };
  11409. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11410. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11411. };
  11412. Engine.prototype.setDepthFunctionToLess = function () {
  11413. this._depthCullingState.depthFunc = this._gl.LESS;
  11414. };
  11415. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11416. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11417. };
  11418. Engine.prototype.getStencilBuffer = function () {
  11419. return this._stencilState.stencilTest;
  11420. };
  11421. Engine.prototype.setStencilBuffer = function (enable) {
  11422. this._stencilState.stencilTest = enable;
  11423. };
  11424. Engine.prototype.getStencilMask = function () {
  11425. return this._stencilState.stencilMask;
  11426. };
  11427. Engine.prototype.setStencilMask = function (mask) {
  11428. this._stencilState.stencilMask = mask;
  11429. };
  11430. Engine.prototype.getStencilFunction = function () {
  11431. return this._stencilState.stencilFunc;
  11432. };
  11433. Engine.prototype.getStencilFunctionReference = function () {
  11434. return this._stencilState.stencilFuncRef;
  11435. };
  11436. Engine.prototype.getStencilFunctionMask = function () {
  11437. return this._stencilState.stencilFuncMask;
  11438. };
  11439. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11440. this._stencilState.stencilFunc = stencilFunc;
  11441. };
  11442. Engine.prototype.setStencilFunctionReference = function (reference) {
  11443. this._stencilState.stencilFuncRef = reference;
  11444. };
  11445. Engine.prototype.setStencilFunctionMask = function (mask) {
  11446. this._stencilState.stencilFuncMask = mask;
  11447. };
  11448. Engine.prototype.getStencilOperationFail = function () {
  11449. return this._stencilState.stencilOpStencilFail;
  11450. };
  11451. Engine.prototype.getStencilOperationDepthFail = function () {
  11452. return this._stencilState.stencilOpDepthFail;
  11453. };
  11454. Engine.prototype.getStencilOperationPass = function () {
  11455. return this._stencilState.stencilOpStencilDepthPass;
  11456. };
  11457. Engine.prototype.setStencilOperationFail = function (operation) {
  11458. this._stencilState.stencilOpStencilFail = operation;
  11459. };
  11460. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11461. this._stencilState.stencilOpDepthFail = operation;
  11462. };
  11463. Engine.prototype.setStencilOperationPass = function (operation) {
  11464. this._stencilState.stencilOpStencilDepthPass = operation;
  11465. };
  11466. Engine.prototype.setDitheringState = function (value) {
  11467. if (value) {
  11468. this._gl.enable(this._gl.DITHER);
  11469. }
  11470. else {
  11471. this._gl.disable(this._gl.DITHER);
  11472. }
  11473. };
  11474. Engine.prototype.setRasterizerState = function (value) {
  11475. if (value) {
  11476. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11477. }
  11478. else {
  11479. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11480. }
  11481. };
  11482. /**
  11483. * stop executing a render loop function and remove it from the execution array
  11484. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11485. */
  11486. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11487. if (!renderFunction) {
  11488. this._activeRenderLoops = [];
  11489. return;
  11490. }
  11491. var index = this._activeRenderLoops.indexOf(renderFunction);
  11492. if (index >= 0) {
  11493. this._activeRenderLoops.splice(index, 1);
  11494. }
  11495. };
  11496. Engine.prototype._renderLoop = function () {
  11497. if (!this._contextWasLost) {
  11498. var shouldRender = true;
  11499. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11500. shouldRender = false;
  11501. }
  11502. if (shouldRender) {
  11503. // Start new frame
  11504. this.beginFrame();
  11505. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11506. var renderFunction = this._activeRenderLoops[index];
  11507. renderFunction();
  11508. }
  11509. // Present
  11510. this.endFrame();
  11511. }
  11512. }
  11513. if (this._activeRenderLoops.length > 0) {
  11514. // Register new frame
  11515. var requester = null;
  11516. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11517. requester = this._vrDisplay;
  11518. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11519. }
  11520. else {
  11521. this._renderingQueueLaunched = false;
  11522. }
  11523. };
  11524. /**
  11525. * Register and execute a render loop. The engine can have more than one render function.
  11526. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11527. * @example
  11528. * engine.runRenderLoop(function () {
  11529. * scene.render()
  11530. * })
  11531. */
  11532. Engine.prototype.runRenderLoop = function (renderFunction) {
  11533. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11534. return;
  11535. }
  11536. this._activeRenderLoops.push(renderFunction);
  11537. if (!this._renderingQueueLaunched) {
  11538. this._renderingQueueLaunched = true;
  11539. this._bindedRenderFunction = this._renderLoop.bind(this);
  11540. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11541. }
  11542. };
  11543. /**
  11544. * Toggle full screen mode.
  11545. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11546. * @param {any} options - an options object to be sent to the requestFullscreen function
  11547. */
  11548. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11549. if (this.isFullscreen) {
  11550. BABYLON.Tools.ExitFullscreen();
  11551. }
  11552. else {
  11553. this._pointerLockRequested = requestPointerLock;
  11554. if (this._renderingCanvas) {
  11555. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11556. }
  11557. }
  11558. };
  11559. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11560. if (stencil === void 0) { stencil = false; }
  11561. this.applyStates();
  11562. var mode = 0;
  11563. if (backBuffer && color) {
  11564. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11565. mode |= this._gl.COLOR_BUFFER_BIT;
  11566. }
  11567. if (depth) {
  11568. this._gl.clearDepth(1.0);
  11569. mode |= this._gl.DEPTH_BUFFER_BIT;
  11570. }
  11571. if (stencil) {
  11572. this._gl.clearStencil(0);
  11573. mode |= this._gl.STENCIL_BUFFER_BIT;
  11574. }
  11575. this._gl.clear(mode);
  11576. };
  11577. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11578. var gl = this._gl;
  11579. // Save state
  11580. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11581. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11582. // Change state
  11583. gl.enable(gl.SCISSOR_TEST);
  11584. gl.scissor(x, y, width, height);
  11585. // Clear
  11586. this.clear(clearColor, true, true, true);
  11587. // Restore state
  11588. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11589. if (curScissor === true) {
  11590. gl.enable(gl.SCISSOR_TEST);
  11591. }
  11592. else {
  11593. gl.disable(gl.SCISSOR_TEST);
  11594. }
  11595. };
  11596. /**
  11597. * Set the WebGL's viewport
  11598. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11599. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11600. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11601. */
  11602. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11603. var width = requiredWidth || this.getRenderWidth();
  11604. var height = requiredHeight || this.getRenderHeight();
  11605. var x = viewport.x || 0;
  11606. var y = viewport.y || 0;
  11607. this._cachedViewport = viewport;
  11608. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11609. };
  11610. /**
  11611. * Directly set the WebGL Viewport
  11612. * The x, y, width & height are directly passed to the WebGL call
  11613. * @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.
  11614. */
  11615. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11616. var currentViewport = this._cachedViewport;
  11617. this._cachedViewport = null;
  11618. this._gl.viewport(x, y, width, height);
  11619. return currentViewport;
  11620. };
  11621. Engine.prototype.beginFrame = function () {
  11622. this.onBeginFrameObservable.notifyObservers(this);
  11623. this._measureFps();
  11624. };
  11625. Engine.prototype.endFrame = function () {
  11626. //force a flush in case we are using a bad OS.
  11627. if (this._badOS) {
  11628. this.flushFramebuffer();
  11629. }
  11630. //submit frame to the vr device, if enabled
  11631. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11632. // TODO: We should only submit the frame if we read frameData successfully.
  11633. this._vrDisplay.submitFrame();
  11634. }
  11635. this.onEndFrameObservable.notifyObservers(this);
  11636. };
  11637. /**
  11638. * resize the view according to the canvas' size.
  11639. * @example
  11640. * window.addEventListener("resize", function () {
  11641. * engine.resize();
  11642. * });
  11643. */
  11644. Engine.prototype.resize = function () {
  11645. // We're not resizing the size of the canvas while in VR mode & presenting
  11646. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11647. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11648. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11649. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11650. }
  11651. };
  11652. /**
  11653. * force a specific size of the canvas
  11654. * @param {number} width - the new canvas' width
  11655. * @param {number} height - the new canvas' height
  11656. */
  11657. Engine.prototype.setSize = function (width, height) {
  11658. if (!this._renderingCanvas) {
  11659. return;
  11660. }
  11661. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11662. return;
  11663. }
  11664. this._renderingCanvas.width = width;
  11665. this._renderingCanvas.height = height;
  11666. for (var index = 0; index < this.scenes.length; index++) {
  11667. var scene = this.scenes[index];
  11668. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11669. var cam = scene.cameras[camIndex];
  11670. cam._currentRenderId = 0;
  11671. }
  11672. }
  11673. if (this.onResizeObservable.hasObservers) {
  11674. this.onResizeObservable.notifyObservers(this);
  11675. }
  11676. };
  11677. // WebVR functions
  11678. Engine.prototype.isVRDevicePresent = function () {
  11679. return !!this._vrDisplay;
  11680. };
  11681. Engine.prototype.getVRDevice = function () {
  11682. return this._vrDisplay;
  11683. };
  11684. /**
  11685. * Initializes a webVR display and starts listening to display change events.
  11686. * The onVRDisplayChangedObservable will be notified upon these changes.
  11687. * @returns The onVRDisplayChangedObservable.
  11688. */
  11689. Engine.prototype.initWebVR = function () {
  11690. this.initWebVRAsync();
  11691. return this.onVRDisplayChangedObservable;
  11692. };
  11693. /**
  11694. * Initializes a webVR display and starts listening to display change events.
  11695. * The onVRDisplayChangedObservable will be notified upon these changes.
  11696. * @returns A promise containing a VRDisplay and if vr is supported.
  11697. */
  11698. Engine.prototype.initWebVRAsync = function () {
  11699. var _this = this;
  11700. var notifyObservers = function () {
  11701. var eventArgs = {
  11702. vrDisplay: _this._vrDisplay,
  11703. vrSupported: _this._vrSupported
  11704. };
  11705. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11706. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11707. };
  11708. if (!this._onVrDisplayConnect) {
  11709. this._onVrDisplayConnect = function (event) {
  11710. _this._vrDisplay = event.display;
  11711. notifyObservers();
  11712. };
  11713. this._onVrDisplayDisconnect = function () {
  11714. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11715. _this._vrDisplay = undefined;
  11716. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11717. notifyObservers();
  11718. };
  11719. this._onVrDisplayPresentChange = function () {
  11720. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11721. };
  11722. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11723. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11724. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11725. }
  11726. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11727. this._webVRInitPromise.then(notifyObservers);
  11728. return this._webVRInitPromise;
  11729. };
  11730. Engine.prototype.enableVR = function () {
  11731. var _this = this;
  11732. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11733. var onResolved = function () {
  11734. _this.onVRRequestPresentComplete.notifyObservers(true);
  11735. _this._onVRFullScreenTriggered();
  11736. };
  11737. var onRejected = function () {
  11738. _this.onVRRequestPresentComplete.notifyObservers(false);
  11739. };
  11740. this.onVRRequestPresentStart.notifyObservers(this);
  11741. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11742. }
  11743. };
  11744. Engine.prototype.disableVR = function () {
  11745. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11746. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11747. }
  11748. };
  11749. Engine.prototype._getVRDisplaysAsync = function () {
  11750. var _this = this;
  11751. return new Promise(function (res, rej) {
  11752. if (navigator.getVRDisplays) {
  11753. navigator.getVRDisplays().then(function (devices) {
  11754. _this._vrSupported = true;
  11755. // note that devices may actually be an empty array. This is fine;
  11756. // we expect this._vrDisplay to be undefined in this case.
  11757. _this._vrDisplay = devices[0];
  11758. res({
  11759. vrDisplay: _this._vrDisplay,
  11760. vrSupported: _this._vrSupported
  11761. });
  11762. });
  11763. }
  11764. else {
  11765. _this._vrDisplay = undefined;
  11766. _this._vrSupported = false;
  11767. res({
  11768. vrDisplay: _this._vrDisplay,
  11769. vrSupported: _this._vrSupported
  11770. });
  11771. }
  11772. });
  11773. };
  11774. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11775. if (this._currentRenderTarget) {
  11776. this.unBindFramebuffer(this._currentRenderTarget);
  11777. }
  11778. this._currentRenderTarget = texture;
  11779. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11780. var gl = this._gl;
  11781. if (texture.isCube) {
  11782. if (faceIndex === undefined) {
  11783. faceIndex = 0;
  11784. }
  11785. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11786. }
  11787. if (this._cachedViewport && !forceFullscreenViewport) {
  11788. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11789. }
  11790. else {
  11791. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11792. }
  11793. this.wipeCaches();
  11794. };
  11795. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11796. if (this._currentFramebuffer !== framebuffer) {
  11797. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11798. this._currentFramebuffer = framebuffer;
  11799. }
  11800. };
  11801. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11802. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11803. this._currentRenderTarget = null;
  11804. // If MSAA, we need to bitblt back to main texture
  11805. var gl = this._gl;
  11806. if (texture._MSAAFramebuffer) {
  11807. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11808. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11809. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11810. }
  11811. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11812. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11813. gl.generateMipmap(gl.TEXTURE_2D);
  11814. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11815. }
  11816. if (onBeforeUnbind) {
  11817. if (texture._MSAAFramebuffer) {
  11818. // Bind the correct framebuffer
  11819. this.bindUnboundFramebuffer(texture._framebuffer);
  11820. }
  11821. onBeforeUnbind();
  11822. }
  11823. this.bindUnboundFramebuffer(null);
  11824. };
  11825. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11826. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11827. this._currentRenderTarget = null;
  11828. // If MSAA, we need to bitblt back to main texture
  11829. var gl = this._gl;
  11830. if (textures[0]._MSAAFramebuffer) {
  11831. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11832. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11833. var attachments = textures[0]._attachments;
  11834. if (!attachments) {
  11835. attachments = new Array(textures.length);
  11836. textures[0]._attachments = attachments;
  11837. }
  11838. for (var i = 0; i < textures.length; i++) {
  11839. var texture = textures[i];
  11840. for (var j = 0; j < attachments.length; j++) {
  11841. attachments[j] = gl.NONE;
  11842. }
  11843. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11844. gl.readBuffer(attachments[i]);
  11845. gl.drawBuffers(attachments);
  11846. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11847. }
  11848. for (var i = 0; i < attachments.length; i++) {
  11849. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11850. }
  11851. gl.drawBuffers(attachments);
  11852. }
  11853. for (var i = 0; i < textures.length; i++) {
  11854. var texture = textures[i];
  11855. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11856. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11857. gl.generateMipmap(gl.TEXTURE_2D);
  11858. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11859. }
  11860. }
  11861. if (onBeforeUnbind) {
  11862. if (textures[0]._MSAAFramebuffer) {
  11863. // Bind the correct framebuffer
  11864. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11865. }
  11866. onBeforeUnbind();
  11867. }
  11868. this.bindUnboundFramebuffer(null);
  11869. };
  11870. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11871. if (texture.generateMipMaps) {
  11872. var gl = this._gl;
  11873. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11874. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11875. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11876. }
  11877. };
  11878. Engine.prototype.flushFramebuffer = function () {
  11879. this._gl.flush();
  11880. };
  11881. Engine.prototype.restoreDefaultFramebuffer = function () {
  11882. if (this._currentRenderTarget) {
  11883. this.unBindFramebuffer(this._currentRenderTarget);
  11884. }
  11885. else {
  11886. this.bindUnboundFramebuffer(null);
  11887. }
  11888. if (this._cachedViewport) {
  11889. this.setViewport(this._cachedViewport);
  11890. }
  11891. this.wipeCaches();
  11892. };
  11893. // UBOs
  11894. Engine.prototype.createUniformBuffer = function (elements) {
  11895. var ubo = this._gl.createBuffer();
  11896. if (!ubo) {
  11897. throw new Error("Unable to create uniform buffer");
  11898. }
  11899. this.bindUniformBuffer(ubo);
  11900. if (elements instanceof Float32Array) {
  11901. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11902. }
  11903. else {
  11904. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11905. }
  11906. this.bindUniformBuffer(null);
  11907. ubo.references = 1;
  11908. return ubo;
  11909. };
  11910. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11911. var ubo = this._gl.createBuffer();
  11912. if (!ubo) {
  11913. throw new Error("Unable to create dynamic uniform buffer");
  11914. }
  11915. this.bindUniformBuffer(ubo);
  11916. if (elements instanceof Float32Array) {
  11917. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11918. }
  11919. else {
  11920. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11921. }
  11922. this.bindUniformBuffer(null);
  11923. ubo.references = 1;
  11924. return ubo;
  11925. };
  11926. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11927. this.bindUniformBuffer(uniformBuffer);
  11928. if (offset === undefined) {
  11929. offset = 0;
  11930. }
  11931. if (count === undefined) {
  11932. if (elements instanceof Float32Array) {
  11933. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11934. }
  11935. else {
  11936. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11937. }
  11938. }
  11939. else {
  11940. if (elements instanceof Float32Array) {
  11941. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11942. }
  11943. else {
  11944. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11945. }
  11946. }
  11947. this.bindUniformBuffer(null);
  11948. };
  11949. // VBOs
  11950. Engine.prototype._resetVertexBufferBinding = function () {
  11951. this.bindArrayBuffer(null);
  11952. this._cachedVertexBuffers = null;
  11953. };
  11954. Engine.prototype.createVertexBuffer = function (vertices) {
  11955. var vbo = this._gl.createBuffer();
  11956. if (!vbo) {
  11957. throw new Error("Unable to create vertex buffer");
  11958. }
  11959. this.bindArrayBuffer(vbo);
  11960. if (vertices instanceof Float32Array) {
  11961. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11962. }
  11963. else {
  11964. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11965. }
  11966. this._resetVertexBufferBinding();
  11967. vbo.references = 1;
  11968. return vbo;
  11969. };
  11970. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11971. var vbo = this._gl.createBuffer();
  11972. if (!vbo) {
  11973. throw new Error("Unable to create dynamic vertex buffer");
  11974. }
  11975. this.bindArrayBuffer(vbo);
  11976. if (vertices instanceof Float32Array) {
  11977. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11978. }
  11979. else {
  11980. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11981. }
  11982. this._resetVertexBufferBinding();
  11983. vbo.references = 1;
  11984. return vbo;
  11985. };
  11986. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11987. if (offset === void 0) { offset = 0; }
  11988. // Force cache update
  11989. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11990. this.bindIndexBuffer(indexBuffer);
  11991. var arrayBuffer;
  11992. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11993. arrayBuffer = indices;
  11994. }
  11995. else {
  11996. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11997. }
  11998. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11999. this._resetIndexBufferBinding();
  12000. };
  12001. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12002. this.bindArrayBuffer(vertexBuffer);
  12003. if (offset === undefined) {
  12004. offset = 0;
  12005. }
  12006. if (count === undefined) {
  12007. if (vertices instanceof Float32Array) {
  12008. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12009. }
  12010. else {
  12011. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12012. }
  12013. }
  12014. else {
  12015. if (vertices instanceof Float32Array) {
  12016. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12017. }
  12018. else {
  12019. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12020. }
  12021. }
  12022. this._resetVertexBufferBinding();
  12023. };
  12024. Engine.prototype._resetIndexBufferBinding = function () {
  12025. this.bindIndexBuffer(null);
  12026. this._cachedIndexBuffer = null;
  12027. };
  12028. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12029. var vbo = this._gl.createBuffer();
  12030. if (!vbo) {
  12031. throw new Error("Unable to create index buffer");
  12032. }
  12033. this.bindIndexBuffer(vbo);
  12034. // Check for 32 bits indices
  12035. var arrayBuffer;
  12036. var need32Bits = false;
  12037. if (indices instanceof Uint16Array) {
  12038. arrayBuffer = indices;
  12039. }
  12040. else {
  12041. //check 32 bit support
  12042. if (this._caps.uintIndices) {
  12043. if (indices instanceof Uint32Array) {
  12044. arrayBuffer = indices;
  12045. need32Bits = true;
  12046. }
  12047. else {
  12048. //number[] or Int32Array, check if 32 bit is necessary
  12049. for (var index = 0; index < indices.length; index++) {
  12050. if (indices[index] > 65535) {
  12051. need32Bits = true;
  12052. break;
  12053. }
  12054. }
  12055. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12056. }
  12057. }
  12058. else {
  12059. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12060. arrayBuffer = new Uint16Array(indices);
  12061. }
  12062. }
  12063. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12064. this._resetIndexBufferBinding();
  12065. vbo.references = 1;
  12066. vbo.is32Bits = need32Bits;
  12067. return vbo;
  12068. };
  12069. Engine.prototype.bindArrayBuffer = function (buffer) {
  12070. if (!this._vaoRecordInProgress) {
  12071. this._unbindVertexArrayObject();
  12072. }
  12073. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12074. };
  12075. Engine.prototype.bindUniformBuffer = function (buffer) {
  12076. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12077. };
  12078. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12079. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12080. };
  12081. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12082. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12083. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12084. };
  12085. ;
  12086. Engine.prototype.bindIndexBuffer = function (buffer) {
  12087. if (!this._vaoRecordInProgress) {
  12088. this._unbindVertexArrayObject();
  12089. }
  12090. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12091. };
  12092. Engine.prototype.bindBuffer = function (buffer, target) {
  12093. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12094. this._gl.bindBuffer(target, buffer);
  12095. this._currentBoundBuffer[target] = buffer;
  12096. }
  12097. };
  12098. Engine.prototype.updateArrayBuffer = function (data) {
  12099. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12100. };
  12101. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12102. var pointer = this._currentBufferPointers[indx];
  12103. var changed = false;
  12104. if (!pointer.active) {
  12105. changed = true;
  12106. pointer.active = true;
  12107. pointer.index = indx;
  12108. pointer.size = size;
  12109. pointer.type = type;
  12110. pointer.normalized = normalized;
  12111. pointer.stride = stride;
  12112. pointer.offset = offset;
  12113. pointer.buffer = buffer;
  12114. }
  12115. else {
  12116. if (pointer.buffer !== buffer) {
  12117. pointer.buffer = buffer;
  12118. changed = true;
  12119. }
  12120. if (pointer.size !== size) {
  12121. pointer.size = size;
  12122. changed = true;
  12123. }
  12124. if (pointer.type !== type) {
  12125. pointer.type = type;
  12126. changed = true;
  12127. }
  12128. if (pointer.normalized !== normalized) {
  12129. pointer.normalized = normalized;
  12130. changed = true;
  12131. }
  12132. if (pointer.stride !== stride) {
  12133. pointer.stride = stride;
  12134. changed = true;
  12135. }
  12136. if (pointer.offset !== offset) {
  12137. pointer.offset = offset;
  12138. changed = true;
  12139. }
  12140. }
  12141. if (changed || this._vaoRecordInProgress) {
  12142. this.bindArrayBuffer(buffer);
  12143. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12144. }
  12145. };
  12146. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12147. if (indexBuffer == null) {
  12148. return;
  12149. }
  12150. if (this._cachedIndexBuffer !== indexBuffer) {
  12151. this._cachedIndexBuffer = indexBuffer;
  12152. this.bindIndexBuffer(indexBuffer);
  12153. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12154. }
  12155. };
  12156. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12157. var attributes = effect.getAttributesNames();
  12158. if (!this._vaoRecordInProgress) {
  12159. this._unbindVertexArrayObject();
  12160. }
  12161. this.unbindAllAttributes();
  12162. for (var index = 0; index < attributes.length; index++) {
  12163. var order = effect.getAttributeLocation(index);
  12164. if (order >= 0) {
  12165. var vertexBuffer = vertexBuffers[attributes[index]];
  12166. if (!vertexBuffer) {
  12167. continue;
  12168. }
  12169. this._gl.enableVertexAttribArray(order);
  12170. if (!this._vaoRecordInProgress) {
  12171. this._vertexAttribArraysEnabled[order] = true;
  12172. }
  12173. var buffer = vertexBuffer.getBuffer();
  12174. if (buffer) {
  12175. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12176. if (vertexBuffer.getIsInstanced()) {
  12177. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12178. if (!this._vaoRecordInProgress) {
  12179. this._currentInstanceLocations.push(order);
  12180. this._currentInstanceBuffers.push(buffer);
  12181. }
  12182. }
  12183. }
  12184. }
  12185. }
  12186. };
  12187. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12188. var vao = this._gl.createVertexArray();
  12189. this._vaoRecordInProgress = true;
  12190. this._gl.bindVertexArray(vao);
  12191. this._mustWipeVertexAttributes = true;
  12192. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12193. this.bindIndexBuffer(indexBuffer);
  12194. this._vaoRecordInProgress = false;
  12195. this._gl.bindVertexArray(null);
  12196. return vao;
  12197. };
  12198. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12199. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12200. this._cachedVertexArrayObject = vertexArrayObject;
  12201. this._gl.bindVertexArray(vertexArrayObject);
  12202. this._cachedVertexBuffers = null;
  12203. this._cachedIndexBuffer = null;
  12204. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12205. this._mustWipeVertexAttributes = true;
  12206. }
  12207. };
  12208. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12209. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12210. this._cachedVertexBuffers = vertexBuffer;
  12211. this._cachedEffectForVertexBuffers = effect;
  12212. var attributesCount = effect.getAttributesCount();
  12213. this._unbindVertexArrayObject();
  12214. this.unbindAllAttributes();
  12215. var offset = 0;
  12216. for (var index = 0; index < attributesCount; index++) {
  12217. if (index < vertexDeclaration.length) {
  12218. var order = effect.getAttributeLocation(index);
  12219. if (order >= 0) {
  12220. this._gl.enableVertexAttribArray(order);
  12221. this._vertexAttribArraysEnabled[order] = true;
  12222. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12223. }
  12224. offset += vertexDeclaration[index] * 4;
  12225. }
  12226. }
  12227. }
  12228. this._bindIndexBufferWithCache(indexBuffer);
  12229. };
  12230. Engine.prototype._unbindVertexArrayObject = function () {
  12231. if (!this._cachedVertexArrayObject) {
  12232. return;
  12233. }
  12234. this._cachedVertexArrayObject = null;
  12235. this._gl.bindVertexArray(null);
  12236. };
  12237. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12238. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12239. this._cachedVertexBuffers = vertexBuffers;
  12240. this._cachedEffectForVertexBuffers = effect;
  12241. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12242. }
  12243. this._bindIndexBufferWithCache(indexBuffer);
  12244. };
  12245. Engine.prototype.unbindInstanceAttributes = function () {
  12246. var boundBuffer;
  12247. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12248. var instancesBuffer = this._currentInstanceBuffers[i];
  12249. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12250. boundBuffer = instancesBuffer;
  12251. this.bindArrayBuffer(instancesBuffer);
  12252. }
  12253. var offsetLocation = this._currentInstanceLocations[i];
  12254. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12255. }
  12256. this._currentInstanceBuffers.length = 0;
  12257. this._currentInstanceLocations.length = 0;
  12258. };
  12259. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12260. this._gl.deleteVertexArray(vao);
  12261. };
  12262. Engine.prototype._releaseBuffer = function (buffer) {
  12263. buffer.references--;
  12264. if (buffer.references === 0) {
  12265. this._gl.deleteBuffer(buffer);
  12266. return true;
  12267. }
  12268. return false;
  12269. };
  12270. Engine.prototype.createInstancesBuffer = function (capacity) {
  12271. var buffer = this._gl.createBuffer();
  12272. if (!buffer) {
  12273. throw new Error("Unable to create instance buffer");
  12274. }
  12275. buffer.capacity = capacity;
  12276. this.bindArrayBuffer(buffer);
  12277. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12278. return buffer;
  12279. };
  12280. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12281. this._gl.deleteBuffer(buffer);
  12282. };
  12283. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12284. this.bindArrayBuffer(instancesBuffer);
  12285. if (data) {
  12286. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12287. }
  12288. if (offsetLocations[0].index !== undefined) {
  12289. var stride = 0;
  12290. for (var i = 0; i < offsetLocations.length; i++) {
  12291. var ai = offsetLocations[i];
  12292. stride += ai.attributeSize * 4;
  12293. }
  12294. for (var i = 0; i < offsetLocations.length; i++) {
  12295. var ai = offsetLocations[i];
  12296. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12297. this._gl.enableVertexAttribArray(ai.index);
  12298. this._vertexAttribArraysEnabled[ai.index] = true;
  12299. }
  12300. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12301. this._gl.vertexAttribDivisor(ai.index, 1);
  12302. this._currentInstanceLocations.push(ai.index);
  12303. this._currentInstanceBuffers.push(instancesBuffer);
  12304. }
  12305. }
  12306. else {
  12307. for (var index = 0; index < 4; index++) {
  12308. var offsetLocation = offsetLocations[index];
  12309. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12310. this._gl.enableVertexAttribArray(offsetLocation);
  12311. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12312. }
  12313. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12314. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12315. this._currentInstanceLocations.push(offsetLocation);
  12316. this._currentInstanceBuffers.push(instancesBuffer);
  12317. }
  12318. }
  12319. };
  12320. Engine.prototype.applyStates = function () {
  12321. this._depthCullingState.apply(this._gl);
  12322. this._stencilState.apply(this._gl);
  12323. this._alphaState.apply(this._gl);
  12324. };
  12325. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12326. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12327. };
  12328. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12329. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12330. };
  12331. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12332. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12333. };
  12334. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12335. // Apply states
  12336. this.applyStates();
  12337. this._drawCalls.addCount(1, false);
  12338. // Render
  12339. var drawMode = this.DrawMode(fillMode);
  12340. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12341. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12342. if (instancesCount) {
  12343. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12344. }
  12345. else {
  12346. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12347. }
  12348. };
  12349. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12350. // Apply states
  12351. this.applyStates();
  12352. this._drawCalls.addCount(1, false);
  12353. var drawMode = this.DrawMode(fillMode);
  12354. if (instancesCount) {
  12355. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12356. }
  12357. else {
  12358. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12359. }
  12360. };
  12361. Engine.prototype.DrawMode = function (fillMode) {
  12362. switch (fillMode) {
  12363. // Triangle views
  12364. case BABYLON.Material.TriangleFillMode:
  12365. return this._gl.TRIANGLES;
  12366. case BABYLON.Material.PointFillMode:
  12367. return this._gl.POINTS;
  12368. case BABYLON.Material.WireFrameFillMode:
  12369. return this._gl.LINES;
  12370. // Draw modes
  12371. case BABYLON.Material.PointListDrawMode:
  12372. return this._gl.POINTS;
  12373. case BABYLON.Material.LineListDrawMode:
  12374. return this._gl.LINES;
  12375. case BABYLON.Material.LineLoopDrawMode:
  12376. return this._gl.LINE_LOOP;
  12377. case BABYLON.Material.LineStripDrawMode:
  12378. return this._gl.LINE_STRIP;
  12379. case BABYLON.Material.TriangleStripDrawMode:
  12380. return this._gl.TRIANGLE_STRIP;
  12381. case BABYLON.Material.TriangleFanDrawMode:
  12382. return this._gl.TRIANGLE_FAN;
  12383. default:
  12384. return this._gl.TRIANGLES;
  12385. }
  12386. };
  12387. // Shaders
  12388. Engine.prototype._releaseEffect = function (effect) {
  12389. if (this._compiledEffects[effect._key]) {
  12390. delete this._compiledEffects[effect._key];
  12391. this._deleteProgram(effect.getProgram());
  12392. }
  12393. };
  12394. Engine.prototype._deleteProgram = function (program) {
  12395. if (program) {
  12396. program.__SPECTOR_rebuildProgram = null;
  12397. if (program.transformFeedback) {
  12398. this.deleteTransformFeedback(program.transformFeedback);
  12399. program.transformFeedback = null;
  12400. }
  12401. this._gl.deleteProgram(program);
  12402. }
  12403. };
  12404. /**
  12405. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12406. * @param samplers An array of string used to represent textures
  12407. */
  12408. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12409. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12410. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12411. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12412. if (this._compiledEffects[name]) {
  12413. var compiledEffect = this._compiledEffects[name];
  12414. if (onCompiled && compiledEffect.isReady()) {
  12415. onCompiled(compiledEffect);
  12416. }
  12417. return compiledEffect;
  12418. }
  12419. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12420. effect._key = name;
  12421. this._compiledEffects[name] = effect;
  12422. return effect;
  12423. };
  12424. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12425. if (uniformsNames === void 0) { uniformsNames = []; }
  12426. if (samplers === void 0) { samplers = []; }
  12427. if (defines === void 0) { defines = ""; }
  12428. return this.createEffect({
  12429. vertex: "particles",
  12430. fragmentElement: fragmentName
  12431. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12432. };
  12433. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12434. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12435. context = context || this._gl;
  12436. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12437. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12438. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12439. };
  12440. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12441. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12442. context = context || this._gl;
  12443. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12444. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12445. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12446. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12447. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12448. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12449. return program;
  12450. };
  12451. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12452. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12453. var shaderProgram = context.createProgram();
  12454. if (!shaderProgram) {
  12455. throw new Error("Unable to create program");
  12456. }
  12457. context.attachShader(shaderProgram, vertexShader);
  12458. context.attachShader(shaderProgram, fragmentShader);
  12459. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12460. var transformFeedback = this.createTransformFeedback();
  12461. this.bindTransformFeedback(transformFeedback);
  12462. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12463. shaderProgram.transformFeedback = transformFeedback;
  12464. }
  12465. context.linkProgram(shaderProgram);
  12466. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12467. this.bindTransformFeedback(null);
  12468. }
  12469. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12470. if (!linked) {
  12471. context.validateProgram(shaderProgram);
  12472. var error = context.getProgramInfoLog(shaderProgram);
  12473. if (error) {
  12474. throw new Error(error);
  12475. }
  12476. }
  12477. context.deleteShader(vertexShader);
  12478. context.deleteShader(fragmentShader);
  12479. return shaderProgram;
  12480. };
  12481. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12482. var results = new Array();
  12483. for (var index = 0; index < uniformsNames.length; index++) {
  12484. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12485. }
  12486. return results;
  12487. };
  12488. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12489. var results = [];
  12490. for (var index = 0; index < attributesNames.length; index++) {
  12491. try {
  12492. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12493. }
  12494. catch (e) {
  12495. results.push(-1);
  12496. }
  12497. }
  12498. return results;
  12499. };
  12500. Engine.prototype.enableEffect = function (effect) {
  12501. if (!effect) {
  12502. return;
  12503. }
  12504. // Use program
  12505. this.bindSamplers(effect);
  12506. this._currentEffect = effect;
  12507. if (effect.onBind) {
  12508. effect.onBind(effect);
  12509. }
  12510. effect.onBindObservable.notifyObservers(effect);
  12511. };
  12512. Engine.prototype.setIntArray = function (uniform, array) {
  12513. if (!uniform)
  12514. return;
  12515. this._gl.uniform1iv(uniform, array);
  12516. };
  12517. Engine.prototype.setIntArray2 = function (uniform, array) {
  12518. if (!uniform || array.length % 2 !== 0)
  12519. return;
  12520. this._gl.uniform2iv(uniform, array);
  12521. };
  12522. Engine.prototype.setIntArray3 = function (uniform, array) {
  12523. if (!uniform || array.length % 3 !== 0)
  12524. return;
  12525. this._gl.uniform3iv(uniform, array);
  12526. };
  12527. Engine.prototype.setIntArray4 = function (uniform, array) {
  12528. if (!uniform || array.length % 4 !== 0)
  12529. return;
  12530. this._gl.uniform4iv(uniform, array);
  12531. };
  12532. Engine.prototype.setFloatArray = function (uniform, array) {
  12533. if (!uniform)
  12534. return;
  12535. this._gl.uniform1fv(uniform, array);
  12536. };
  12537. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12538. if (!uniform || array.length % 2 !== 0)
  12539. return;
  12540. this._gl.uniform2fv(uniform, array);
  12541. };
  12542. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12543. if (!uniform || array.length % 3 !== 0)
  12544. return;
  12545. this._gl.uniform3fv(uniform, array);
  12546. };
  12547. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12548. if (!uniform || array.length % 4 !== 0)
  12549. return;
  12550. this._gl.uniform4fv(uniform, array);
  12551. };
  12552. Engine.prototype.setArray = function (uniform, array) {
  12553. if (!uniform)
  12554. return;
  12555. this._gl.uniform1fv(uniform, array);
  12556. };
  12557. Engine.prototype.setArray2 = function (uniform, array) {
  12558. if (!uniform || array.length % 2 !== 0)
  12559. return;
  12560. this._gl.uniform2fv(uniform, array);
  12561. };
  12562. Engine.prototype.setArray3 = function (uniform, array) {
  12563. if (!uniform || array.length % 3 !== 0)
  12564. return;
  12565. this._gl.uniform3fv(uniform, array);
  12566. };
  12567. Engine.prototype.setArray4 = function (uniform, array) {
  12568. if (!uniform || array.length % 4 !== 0)
  12569. return;
  12570. this._gl.uniform4fv(uniform, array);
  12571. };
  12572. Engine.prototype.setMatrices = function (uniform, matrices) {
  12573. if (!uniform)
  12574. return;
  12575. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12576. };
  12577. Engine.prototype.setMatrix = function (uniform, matrix) {
  12578. if (!uniform)
  12579. return;
  12580. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12581. };
  12582. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12583. if (!uniform)
  12584. return;
  12585. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12586. };
  12587. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12588. if (!uniform)
  12589. return;
  12590. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12591. };
  12592. Engine.prototype.setInt = function (uniform, value) {
  12593. if (!uniform)
  12594. return;
  12595. this._gl.uniform1i(uniform, value);
  12596. };
  12597. Engine.prototype.setFloat = function (uniform, value) {
  12598. if (!uniform)
  12599. return;
  12600. this._gl.uniform1f(uniform, value);
  12601. };
  12602. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12603. if (!uniform)
  12604. return;
  12605. this._gl.uniform2f(uniform, x, y);
  12606. };
  12607. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12608. if (!uniform)
  12609. return;
  12610. this._gl.uniform3f(uniform, x, y, z);
  12611. };
  12612. Engine.prototype.setBool = function (uniform, bool) {
  12613. if (!uniform)
  12614. return;
  12615. this._gl.uniform1i(uniform, bool);
  12616. };
  12617. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12618. if (!uniform)
  12619. return;
  12620. this._gl.uniform4f(uniform, x, y, z, w);
  12621. };
  12622. Engine.prototype.setColor3 = function (uniform, color3) {
  12623. if (!uniform)
  12624. return;
  12625. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12626. };
  12627. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12628. if (!uniform)
  12629. return;
  12630. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12631. };
  12632. /**
  12633. * Sets a Color4 on a uniform variable
  12634. * @param uniform defines the uniform location
  12635. * @param color4 defines the value to be set
  12636. */
  12637. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12638. if (!uniform)
  12639. return;
  12640. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12641. };
  12642. // States
  12643. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12644. if (zOffset === void 0) { zOffset = 0; }
  12645. if (reverseSide === void 0) { reverseSide = false; }
  12646. // Culling
  12647. if (this._depthCullingState.cull !== culling || force) {
  12648. this._depthCullingState.cull = culling;
  12649. }
  12650. // Cull face
  12651. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12652. if (this._depthCullingState.cullFace !== cullFace || force) {
  12653. this._depthCullingState.cullFace = cullFace;
  12654. }
  12655. // Z offset
  12656. this.setZOffset(zOffset);
  12657. // Front face
  12658. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12659. if (this._depthCullingState.frontFace !== frontFace || force) {
  12660. this._depthCullingState.frontFace = frontFace;
  12661. }
  12662. };
  12663. Engine.prototype.setZOffset = function (value) {
  12664. this._depthCullingState.zOffset = value;
  12665. };
  12666. Engine.prototype.getZOffset = function () {
  12667. return this._depthCullingState.zOffset;
  12668. };
  12669. Engine.prototype.setDepthBuffer = function (enable) {
  12670. this._depthCullingState.depthTest = enable;
  12671. };
  12672. Engine.prototype.getDepthWrite = function () {
  12673. return this._depthCullingState.depthMask;
  12674. };
  12675. Engine.prototype.setDepthWrite = function (enable) {
  12676. this._depthCullingState.depthMask = enable;
  12677. };
  12678. Engine.prototype.setColorWrite = function (enable) {
  12679. this._gl.colorMask(enable, enable, enable, enable);
  12680. this._colorWrite = enable;
  12681. };
  12682. Engine.prototype.getColorWrite = function () {
  12683. return this._colorWrite;
  12684. };
  12685. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12686. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12687. };
  12688. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12689. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12690. if (this._alphaMode === mode) {
  12691. return;
  12692. }
  12693. switch (mode) {
  12694. case Engine.ALPHA_DISABLE:
  12695. this._alphaState.alphaBlend = false;
  12696. break;
  12697. case Engine.ALPHA_PREMULTIPLIED:
  12698. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12699. this._alphaState.alphaBlend = true;
  12700. break;
  12701. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12702. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12703. this._alphaState.alphaBlend = true;
  12704. break;
  12705. case Engine.ALPHA_COMBINE:
  12706. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12707. this._alphaState.alphaBlend = true;
  12708. break;
  12709. case Engine.ALPHA_ONEONE:
  12710. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12711. this._alphaState.alphaBlend = true;
  12712. break;
  12713. case Engine.ALPHA_ADD:
  12714. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12715. this._alphaState.alphaBlend = true;
  12716. break;
  12717. case Engine.ALPHA_SUBTRACT:
  12718. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12719. this._alphaState.alphaBlend = true;
  12720. break;
  12721. case Engine.ALPHA_MULTIPLY:
  12722. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12723. this._alphaState.alphaBlend = true;
  12724. break;
  12725. case Engine.ALPHA_MAXIMIZED:
  12726. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12727. this._alphaState.alphaBlend = true;
  12728. break;
  12729. case Engine.ALPHA_INTERPOLATE:
  12730. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12731. this._alphaState.alphaBlend = true;
  12732. break;
  12733. case Engine.ALPHA_SCREENMODE:
  12734. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12735. this._alphaState.alphaBlend = true;
  12736. break;
  12737. }
  12738. if (!noDepthWriteChange) {
  12739. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12740. }
  12741. this._alphaMode = mode;
  12742. };
  12743. Engine.prototype.getAlphaMode = function () {
  12744. return this._alphaMode;
  12745. };
  12746. // Textures
  12747. Engine.prototype.wipeCaches = function (bruteForce) {
  12748. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12749. return;
  12750. }
  12751. this._currentEffect = null;
  12752. // 6/8/2017: deltakosh: Should not be required anymore.
  12753. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12754. if (bruteForce) {
  12755. this.resetTextureCache();
  12756. this._currentProgram = null;
  12757. this._stencilState.reset();
  12758. this._depthCullingState.reset();
  12759. this.setDepthFunctionToLessOrEqual();
  12760. this._alphaState.reset();
  12761. }
  12762. this._resetVertexBufferBinding();
  12763. this._cachedIndexBuffer = null;
  12764. this._cachedEffectForVertexBuffers = null;
  12765. this._unbindVertexArrayObject();
  12766. this.bindIndexBuffer(null);
  12767. };
  12768. /**
  12769. * Set the compressed texture format to use, based on the formats you have, and the formats
  12770. * supported by the hardware / browser.
  12771. *
  12772. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12773. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12774. * to API arguments needed to compressed textures. This puts the burden on the container
  12775. * generator to house the arcane code for determining these for current & future formats.
  12776. *
  12777. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12778. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12779. *
  12780. * Note: The result of this call is not taken into account when a texture is base64.
  12781. *
  12782. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12783. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12784. *
  12785. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12786. * @returns The extension selected.
  12787. */
  12788. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12789. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12790. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12791. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12792. return this._textureFormatInUse = this._texturesSupported[i];
  12793. }
  12794. }
  12795. }
  12796. // actively set format to nothing, to allow this to be called more than once
  12797. // and possibly fail the 2nd time
  12798. this._textureFormatInUse = null;
  12799. return null;
  12800. };
  12801. Engine.prototype._createTexture = function () {
  12802. var texture = this._gl.createTexture();
  12803. if (!texture) {
  12804. throw new Error("Unable to create texture");
  12805. }
  12806. return texture;
  12807. };
  12808. /**
  12809. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12810. * @param {string} urlArg- This contains one of the following:
  12811. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12812. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12813. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12814. *
  12815. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12816. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12817. * @param {Scene} scene- Needed for loading to the correct scene.
  12818. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12819. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12820. * @param {callback} onError- Optional callback to be called upon failure.
  12821. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12822. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12823. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12824. *
  12825. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12826. */
  12827. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12828. var _this = this;
  12829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12830. if (onLoad === void 0) { onLoad = null; }
  12831. if (onError === void 0) { onError = null; }
  12832. if (buffer === void 0) { buffer = null; }
  12833. if (fallBack === void 0) { fallBack = null; }
  12834. if (format === void 0) { format = null; }
  12835. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12836. var fromData = url.substr(0, 5) === "data:";
  12837. var fromBlob = url.substr(0, 5) === "blob:";
  12838. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12839. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12840. // establish the file extension, if possible
  12841. var lastDot = url.lastIndexOf('.');
  12842. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12843. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12844. var isTGA = (extension.indexOf(".tga") === 0);
  12845. // determine if a ktx file should be substituted
  12846. var isKTX = false;
  12847. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12848. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12849. isKTX = true;
  12850. }
  12851. if (scene) {
  12852. scene._addPendingData(texture);
  12853. }
  12854. texture.url = url;
  12855. texture.generateMipMaps = !noMipmap;
  12856. texture.samplingMode = samplingMode;
  12857. texture.invertY = invertY;
  12858. if (!this._doNotHandleContextLost) {
  12859. // Keep a link to the buffer only if we plan to handle context lost
  12860. texture._buffer = buffer;
  12861. }
  12862. var onLoadObserver = null;
  12863. if (onLoad && !fallBack) {
  12864. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12865. }
  12866. if (!fallBack)
  12867. this._internalTexturesCache.push(texture);
  12868. var onerror = function (message, exception) {
  12869. if (scene) {
  12870. scene._removePendingData(texture);
  12871. }
  12872. if (onLoadObserver) {
  12873. texture.onLoadedObservable.remove(onLoadObserver);
  12874. }
  12875. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12876. if (isKTX) {
  12877. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12878. }
  12879. else if (BABYLON.Tools.UseFallbackTexture) {
  12880. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12881. }
  12882. if (onError) {
  12883. onError(message || "Unknown error", exception);
  12884. }
  12885. };
  12886. var callback = null;
  12887. // processing for non-image formats
  12888. if (isKTX || isTGA || isDDS) {
  12889. if (isKTX) {
  12890. callback = function (data) {
  12891. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12892. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12893. ktx.uploadLevels(_this._gl, !noMipmap);
  12894. return false;
  12895. }, samplingMode);
  12896. };
  12897. }
  12898. else if (isTGA) {
  12899. callback = function (arrayBuffer) {
  12900. var data = new Uint8Array(arrayBuffer);
  12901. var header = BABYLON.TGATools.GetTGAHeader(data);
  12902. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12903. BABYLON.TGATools.UploadContent(_this._gl, data);
  12904. return false;
  12905. }, samplingMode);
  12906. };
  12907. }
  12908. else if (isDDS) {
  12909. callback = function (data) {
  12910. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12911. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12912. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12913. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12914. return false;
  12915. }, samplingMode);
  12916. };
  12917. }
  12918. if (!buffer) {
  12919. this._loadFile(url, function (data) {
  12920. if (callback) {
  12921. callback(data);
  12922. }
  12923. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12924. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12925. });
  12926. }
  12927. else {
  12928. if (callback) {
  12929. callback(buffer);
  12930. }
  12931. }
  12932. // image format processing
  12933. }
  12934. else {
  12935. var onload = function (img) {
  12936. if (fromBlob && !_this._doNotHandleContextLost) {
  12937. // We need to store the image if we need to rebuild the texture
  12938. // in case of a webgl context lost
  12939. texture._buffer = img;
  12940. }
  12941. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12942. var gl = _this._gl;
  12943. var isPot = (img.width === potWidth && img.height === potHeight);
  12944. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12945. if (isPot) {
  12946. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12947. return false;
  12948. }
  12949. // Using shaders to rescale because canvas.drawImage is lossy
  12950. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12951. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12952. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12953. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12954. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12955. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12956. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12957. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12958. _this._releaseTexture(source);
  12959. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12960. continuationCallback();
  12961. });
  12962. return true;
  12963. }, samplingMode);
  12964. };
  12965. if (!fromData || isBase64)
  12966. if (buffer instanceof HTMLImageElement) {
  12967. onload(buffer);
  12968. }
  12969. else {
  12970. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12971. }
  12972. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12973. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12974. else
  12975. onload(buffer);
  12976. }
  12977. return texture;
  12978. };
  12979. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12980. var _this = this;
  12981. var rtt = this.createRenderTargetTexture({
  12982. width: destination.width,
  12983. height: destination.height,
  12984. }, {
  12985. generateMipMaps: false,
  12986. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12987. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12988. generateDepthBuffer: false,
  12989. generateStencilBuffer: false
  12990. });
  12991. if (!this._rescalePostProcess) {
  12992. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12993. }
  12994. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12995. _this._rescalePostProcess.onApply = function (effect) {
  12996. effect._bindTexture("textureSampler", source);
  12997. };
  12998. var hostingScene = scene;
  12999. if (!hostingScene) {
  13000. hostingScene = _this.scenes[_this.scenes.length - 1];
  13001. }
  13002. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13003. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13004. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13005. _this.unBindFramebuffer(rtt);
  13006. _this._releaseTexture(rtt);
  13007. if (onComplete) {
  13008. onComplete();
  13009. }
  13010. });
  13011. };
  13012. Engine.prototype._getInternalFormat = function (format) {
  13013. var internalFormat = this._gl.RGBA;
  13014. switch (format) {
  13015. case Engine.TEXTUREFORMAT_ALPHA:
  13016. internalFormat = this._gl.ALPHA;
  13017. break;
  13018. case Engine.TEXTUREFORMAT_LUMINANCE:
  13019. internalFormat = this._gl.LUMINANCE;
  13020. break;
  13021. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  13022. internalFormat = this._gl.LUMINANCE_ALPHA;
  13023. break;
  13024. case Engine.TEXTUREFORMAT_RGB:
  13025. case Engine.TEXTUREFORMAT_RGB32F:
  13026. internalFormat = this._gl.RGB;
  13027. break;
  13028. case Engine.TEXTUREFORMAT_RGBA:
  13029. internalFormat = this._gl.RGBA;
  13030. break;
  13031. case Engine.TEXTUREFORMAT_R32F:
  13032. internalFormat = this._gl.RED;
  13033. break;
  13034. case Engine.TEXTUREFORMAT_RG32F:
  13035. internalFormat = this._gl.RG;
  13036. break;
  13037. }
  13038. return internalFormat;
  13039. };
  13040. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13041. if (compression === void 0) { compression = null; }
  13042. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13043. if (!texture) {
  13044. return;
  13045. }
  13046. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13047. var internalFormat = this._getInternalFormat(format);
  13048. var textureType = this._getWebGLTextureType(type);
  13049. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13050. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13051. if (!this._doNotHandleContextLost) {
  13052. texture._bufferView = data;
  13053. texture.format = format;
  13054. texture.type = type;
  13055. texture.invertY = invertY;
  13056. texture._compression = compression;
  13057. }
  13058. if (texture.width % 4 !== 0) {
  13059. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13060. }
  13061. if (compression && data) {
  13062. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13063. }
  13064. else {
  13065. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13066. }
  13067. if (texture.generateMipMaps) {
  13068. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13069. }
  13070. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13071. // this.resetTextureCache();
  13072. texture.isReady = true;
  13073. };
  13074. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13075. if (compression === void 0) { compression = null; }
  13076. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13077. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13078. texture.baseWidth = width;
  13079. texture.baseHeight = height;
  13080. texture.width = width;
  13081. texture.height = height;
  13082. texture.format = format;
  13083. texture.generateMipMaps = generateMipMaps;
  13084. texture.samplingMode = samplingMode;
  13085. texture.invertY = invertY;
  13086. texture._compression = compression;
  13087. texture.type = type;
  13088. if (!this._doNotHandleContextLost) {
  13089. texture._bufferView = data;
  13090. }
  13091. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13092. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13093. // Filters
  13094. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13095. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13096. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13097. if (generateMipMaps) {
  13098. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13099. }
  13100. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13101. this._internalTexturesCache.push(texture);
  13102. return texture;
  13103. };
  13104. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13105. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13106. texture.baseWidth = width;
  13107. texture.baseHeight = height;
  13108. if (generateMipMaps) {
  13109. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13110. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13111. }
  13112. // this.resetTextureCache();
  13113. texture.width = width;
  13114. texture.height = height;
  13115. texture.isReady = false;
  13116. texture.generateMipMaps = generateMipMaps;
  13117. texture.samplingMode = samplingMode;
  13118. this.updateTextureSamplingMode(samplingMode, texture);
  13119. this._internalTexturesCache.push(texture);
  13120. return texture;
  13121. };
  13122. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13123. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13124. if (texture.isCube) {
  13125. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13126. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13127. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13128. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13129. }
  13130. else if (texture.is3D) {
  13131. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13132. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13133. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13134. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13135. }
  13136. else {
  13137. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13138. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13139. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13140. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13141. }
  13142. texture.samplingMode = samplingMode;
  13143. };
  13144. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13145. if (premulAlpha === void 0) { premulAlpha = false; }
  13146. if (!texture) {
  13147. return;
  13148. }
  13149. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13150. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13151. if (premulAlpha) {
  13152. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13153. }
  13154. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13155. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13156. if (texture.generateMipMaps) {
  13157. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13158. }
  13159. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13160. if (premulAlpha) {
  13161. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13162. }
  13163. texture.isReady = true;
  13164. };
  13165. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13166. if (!texture || texture._isDisabled) {
  13167. return;
  13168. }
  13169. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13170. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13171. try {
  13172. // Testing video texture support
  13173. if (this._videoTextureSupported === undefined) {
  13174. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13175. if (this._gl.getError() !== 0) {
  13176. this._videoTextureSupported = false;
  13177. }
  13178. else {
  13179. this._videoTextureSupported = true;
  13180. }
  13181. }
  13182. // Copy video through the current working canvas if video texture is not supported
  13183. if (!this._videoTextureSupported) {
  13184. if (!texture._workingCanvas) {
  13185. texture._workingCanvas = document.createElement("canvas");
  13186. var context = texture._workingCanvas.getContext("2d");
  13187. if (!context) {
  13188. throw new Error("Unable to get 2d context");
  13189. }
  13190. texture._workingContext = context;
  13191. texture._workingCanvas.width = texture.width;
  13192. texture._workingCanvas.height = texture.height;
  13193. }
  13194. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13195. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13196. }
  13197. else {
  13198. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13199. }
  13200. if (texture.generateMipMaps) {
  13201. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13202. }
  13203. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13204. // this.resetTextureCache();
  13205. texture.isReady = true;
  13206. }
  13207. catch (ex) {
  13208. // Something unexpected
  13209. // Let's disable the texture
  13210. texture._isDisabled = true;
  13211. }
  13212. };
  13213. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13214. var fullOptions = new RenderTargetCreationOptions();
  13215. if (options !== undefined && typeof options === "object") {
  13216. fullOptions.generateMipMaps = options.generateMipMaps;
  13217. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13218. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13219. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13220. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13221. }
  13222. else {
  13223. fullOptions.generateMipMaps = options;
  13224. fullOptions.generateDepthBuffer = true;
  13225. fullOptions.generateStencilBuffer = false;
  13226. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13227. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13228. }
  13229. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13230. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13231. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13232. }
  13233. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13234. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13235. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13236. }
  13237. var gl = this._gl;
  13238. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13239. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13240. var width = size.width || size;
  13241. var height = size.height || size;
  13242. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13243. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13244. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13245. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13246. }
  13247. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13248. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13249. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13250. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13251. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13252. // Create the framebuffer
  13253. var framebuffer = gl.createFramebuffer();
  13254. this.bindUnboundFramebuffer(framebuffer);
  13255. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13256. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13257. if (fullOptions.generateMipMaps) {
  13258. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13259. }
  13260. // Unbind
  13261. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13262. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13263. this.bindUnboundFramebuffer(null);
  13264. texture._framebuffer = framebuffer;
  13265. texture.baseWidth = width;
  13266. texture.baseHeight = height;
  13267. texture.width = width;
  13268. texture.height = height;
  13269. texture.isReady = true;
  13270. texture.samples = 1;
  13271. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13272. texture.samplingMode = fullOptions.samplingMode;
  13273. texture.type = fullOptions.type;
  13274. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13275. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13276. // this.resetTextureCache();
  13277. this._internalTexturesCache.push(texture);
  13278. return texture;
  13279. };
  13280. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13281. var generateMipMaps = false;
  13282. var generateDepthBuffer = true;
  13283. var generateStencilBuffer = false;
  13284. var generateDepthTexture = false;
  13285. var textureCount = 1;
  13286. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13287. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13288. var types = [], samplingModes = [];
  13289. if (options !== undefined) {
  13290. generateMipMaps = options.generateMipMaps;
  13291. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13292. generateStencilBuffer = options.generateStencilBuffer;
  13293. generateDepthTexture = options.generateDepthTexture;
  13294. textureCount = options.textureCount || 1;
  13295. if (options.types) {
  13296. types = options.types;
  13297. }
  13298. if (options.samplingModes) {
  13299. samplingModes = options.samplingModes;
  13300. }
  13301. }
  13302. var gl = this._gl;
  13303. // Create the framebuffer
  13304. var framebuffer = gl.createFramebuffer();
  13305. this.bindUnboundFramebuffer(framebuffer);
  13306. var width = size.width || size;
  13307. var height = size.height || size;
  13308. var textures = [];
  13309. var attachments = [];
  13310. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13311. for (var i = 0; i < textureCount; i++) {
  13312. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13313. var type = types[i] || defaultType;
  13314. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13315. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13316. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13317. }
  13318. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13319. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13320. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13321. }
  13322. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13323. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13324. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13325. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13326. }
  13327. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13328. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13329. textures.push(texture);
  13330. attachments.push(attachment);
  13331. gl.activeTexture(gl["TEXTURE" + i]);
  13332. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13333. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13334. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13335. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13337. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13338. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13339. if (generateMipMaps) {
  13340. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13341. }
  13342. // Unbind
  13343. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13344. texture._framebuffer = framebuffer;
  13345. texture._depthStencilBuffer = depthStencilBuffer;
  13346. texture.baseWidth = width;
  13347. texture.baseHeight = height;
  13348. texture.width = width;
  13349. texture.height = height;
  13350. texture.isReady = true;
  13351. texture.samples = 1;
  13352. texture.generateMipMaps = generateMipMaps;
  13353. texture.samplingMode = samplingMode;
  13354. texture.type = type;
  13355. texture._generateDepthBuffer = generateDepthBuffer;
  13356. texture._generateStencilBuffer = generateStencilBuffer;
  13357. texture._attachments = attachments;
  13358. this._internalTexturesCache.push(texture);
  13359. }
  13360. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13361. // Depth texture
  13362. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13363. gl.activeTexture(gl.TEXTURE0);
  13364. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13365. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13366. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13367. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13368. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13369. 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);
  13370. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13371. depthTexture._framebuffer = framebuffer;
  13372. depthTexture.baseWidth = width;
  13373. depthTexture.baseHeight = height;
  13374. depthTexture.width = width;
  13375. depthTexture.height = height;
  13376. depthTexture.isReady = true;
  13377. depthTexture.samples = 1;
  13378. depthTexture.generateMipMaps = generateMipMaps;
  13379. depthTexture.samplingMode = gl.NEAREST;
  13380. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13381. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13382. textures.push(depthTexture);
  13383. this._internalTexturesCache.push(depthTexture);
  13384. }
  13385. gl.drawBuffers(attachments);
  13386. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13387. this.bindUnboundFramebuffer(null);
  13388. this.resetTextureCache();
  13389. return textures;
  13390. };
  13391. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13392. if (samples === void 0) { samples = 1; }
  13393. var depthStencilBuffer = null;
  13394. var gl = this._gl;
  13395. // Create the depth/stencil buffer
  13396. if (generateStencilBuffer) {
  13397. depthStencilBuffer = gl.createRenderbuffer();
  13398. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13399. if (samples > 1) {
  13400. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13401. }
  13402. else {
  13403. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13404. }
  13405. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13406. }
  13407. else if (generateDepthBuffer) {
  13408. depthStencilBuffer = gl.createRenderbuffer();
  13409. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13410. if (samples > 1) {
  13411. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13412. }
  13413. else {
  13414. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13415. }
  13416. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13417. }
  13418. return depthStencilBuffer;
  13419. };
  13420. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13421. if (this.webGLVersion < 2 || !texture) {
  13422. return 1;
  13423. }
  13424. if (texture.samples === samples) {
  13425. return samples;
  13426. }
  13427. var gl = this._gl;
  13428. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13429. // Dispose previous render buffers
  13430. if (texture._depthStencilBuffer) {
  13431. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13432. texture._depthStencilBuffer = null;
  13433. }
  13434. if (texture._MSAAFramebuffer) {
  13435. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13436. texture._MSAAFramebuffer = null;
  13437. }
  13438. if (texture._MSAARenderBuffer) {
  13439. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13440. texture._MSAARenderBuffer = null;
  13441. }
  13442. if (samples > 1) {
  13443. var framebuffer = gl.createFramebuffer();
  13444. if (!framebuffer) {
  13445. throw new Error("Unable to create multi sampled framebuffer");
  13446. }
  13447. texture._MSAAFramebuffer = framebuffer;
  13448. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13449. var colorRenderbuffer = gl.createRenderbuffer();
  13450. if (!colorRenderbuffer) {
  13451. throw new Error("Unable to create multi sampled framebuffer");
  13452. }
  13453. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13454. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13455. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13456. texture._MSAARenderBuffer = colorRenderbuffer;
  13457. }
  13458. else {
  13459. this.bindUnboundFramebuffer(texture._framebuffer);
  13460. }
  13461. texture.samples = samples;
  13462. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13463. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13464. this.bindUnboundFramebuffer(null);
  13465. return samples;
  13466. };
  13467. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13468. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13469. return 1;
  13470. }
  13471. if (textures[0].samples === samples) {
  13472. return samples;
  13473. }
  13474. var gl = this._gl;
  13475. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13476. // Dispose previous render buffers
  13477. if (textures[0]._depthStencilBuffer) {
  13478. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13479. textures[0]._depthStencilBuffer = null;
  13480. }
  13481. if (textures[0]._MSAAFramebuffer) {
  13482. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13483. textures[0]._MSAAFramebuffer = null;
  13484. }
  13485. for (var i = 0; i < textures.length; i++) {
  13486. if (textures[i]._MSAARenderBuffer) {
  13487. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13488. textures[i]._MSAARenderBuffer = null;
  13489. }
  13490. }
  13491. if (samples > 1) {
  13492. var framebuffer = gl.createFramebuffer();
  13493. if (!framebuffer) {
  13494. throw new Error("Unable to create multi sampled framebuffer");
  13495. }
  13496. this.bindUnboundFramebuffer(framebuffer);
  13497. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13498. var attachments = [];
  13499. for (var i = 0; i < textures.length; i++) {
  13500. var texture = textures[i];
  13501. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13502. var colorRenderbuffer = gl.createRenderbuffer();
  13503. if (!colorRenderbuffer) {
  13504. throw new Error("Unable to create multi sampled framebuffer");
  13505. }
  13506. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13507. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13508. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13509. texture._MSAAFramebuffer = framebuffer;
  13510. texture._MSAARenderBuffer = colorRenderbuffer;
  13511. texture.samples = samples;
  13512. texture._depthStencilBuffer = depthStencilBuffer;
  13513. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13514. attachments.push(attachment);
  13515. }
  13516. gl.drawBuffers(attachments);
  13517. }
  13518. else {
  13519. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13520. }
  13521. this.bindUnboundFramebuffer(null);
  13522. return samples;
  13523. };
  13524. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13525. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13526. };
  13527. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13528. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13529. };
  13530. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13531. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13532. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13533. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13534. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13535. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13536. }
  13537. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13538. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13539. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13540. }
  13541. var gl = this._gl;
  13542. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13543. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13544. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13545. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13546. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13547. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13548. }
  13549. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13550. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13551. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13552. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13553. for (var face = 0; face < 6; face++) {
  13554. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13555. }
  13556. // Create the framebuffer
  13557. var framebuffer = gl.createFramebuffer();
  13558. this.bindUnboundFramebuffer(framebuffer);
  13559. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13560. // MipMaps
  13561. if (fullOptions.generateMipMaps) {
  13562. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13563. }
  13564. // Unbind
  13565. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13566. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13567. this.bindUnboundFramebuffer(null);
  13568. texture._framebuffer = framebuffer;
  13569. texture.width = size;
  13570. texture.height = size;
  13571. texture.isReady = true;
  13572. texture.isCube = true;
  13573. texture.samples = 1;
  13574. texture.generateMipMaps = fullOptions.generateMipMaps;
  13575. texture.samplingMode = fullOptions.samplingMode;
  13576. texture.type = fullOptions.type;
  13577. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13578. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13579. this._internalTexturesCache.push(texture);
  13580. return texture;
  13581. };
  13582. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13583. var _this = this;
  13584. if (onLoad === void 0) { onLoad = null; }
  13585. if (onError === void 0) { onError = null; }
  13586. if (forcedExtension === void 0) { forcedExtension = null; }
  13587. var callback = function (loadData) {
  13588. if (!loadData) {
  13589. if (onLoad) {
  13590. onLoad(null);
  13591. }
  13592. return;
  13593. }
  13594. var texture = loadData.texture;
  13595. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13596. texture._lodGenerationScale = scale;
  13597. texture._lodGenerationOffset = offset;
  13598. if (_this._caps.textureLOD) {
  13599. // Do not add extra process if texture lod is supported.
  13600. if (onLoad) {
  13601. onLoad(texture);
  13602. }
  13603. return;
  13604. }
  13605. var mipSlices = 3;
  13606. var gl = _this._gl;
  13607. var width = loadData.width;
  13608. if (!width) {
  13609. return;
  13610. }
  13611. var textures = [];
  13612. for (var i = 0; i < mipSlices; i++) {
  13613. //compute LOD from even spacing in smoothness (matching shader calculation)
  13614. var smoothness = i / (mipSlices - 1);
  13615. var roughness = 1 - smoothness;
  13616. var minLODIndex = offset; // roughness = 0
  13617. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13618. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13619. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13620. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13621. glTextureFromLod.isCube = true;
  13622. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13623. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13624. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13625. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13626. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13627. if (loadData.isDDS) {
  13628. var info = loadData.info;
  13629. var data = loadData.data;
  13630. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13631. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13632. }
  13633. else {
  13634. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13635. }
  13636. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13637. // Wrap in a base texture for easy binding.
  13638. var lodTexture = new BABYLON.BaseTexture(scene);
  13639. lodTexture.isCube = true;
  13640. lodTexture._texture = glTextureFromLod;
  13641. glTextureFromLod.isReady = true;
  13642. textures.push(lodTexture);
  13643. }
  13644. texture._lodTextureHigh = textures[2];
  13645. texture._lodTextureMid = textures[1];
  13646. texture._lodTextureLow = textures[0];
  13647. if (onLoad) {
  13648. onLoad(texture);
  13649. }
  13650. };
  13651. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13652. };
  13653. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13654. var _this = this;
  13655. if (onLoad === void 0) { onLoad = null; }
  13656. if (onError === void 0) { onError = null; }
  13657. if (forcedExtension === void 0) { forcedExtension = null; }
  13658. var gl = this._gl;
  13659. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13660. texture.isCube = true;
  13661. texture.url = rootUrl;
  13662. texture.generateMipMaps = !noMipmap;
  13663. if (!this._doNotHandleContextLost) {
  13664. texture._extension = forcedExtension;
  13665. texture._files = files;
  13666. }
  13667. var isKTX = false;
  13668. var isDDS = false;
  13669. var lastDot = rootUrl.lastIndexOf('.');
  13670. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13671. if (this._textureFormatInUse) {
  13672. extension = this._textureFormatInUse;
  13673. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13674. isKTX = true;
  13675. }
  13676. else {
  13677. isDDS = (extension === ".dds");
  13678. }
  13679. var onerror = function (request, exception) {
  13680. if (onError && request) {
  13681. onError(request.status + " " + request.statusText, exception);
  13682. }
  13683. };
  13684. if (isKTX) {
  13685. this._loadFile(rootUrl, function (data) {
  13686. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13687. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13688. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13689. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13690. ktx.uploadLevels(_this._gl, !noMipmap);
  13691. _this.setCubeMapTextureParams(gl, loadMipmap);
  13692. texture.width = ktx.pixelWidth;
  13693. texture.height = ktx.pixelHeight;
  13694. texture.isReady = true;
  13695. }, undefined, undefined, true, onerror);
  13696. }
  13697. else if (isDDS) {
  13698. if (files && files.length === 6) {
  13699. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  13700. var info;
  13701. var loadMipmap = false;
  13702. var width = 0;
  13703. for (var index = 0; index < imgs.length; index++) {
  13704. var data = imgs[index];
  13705. info = BABYLON.DDSTools.GetDDSInfo(data);
  13706. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13707. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13708. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13709. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13710. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13711. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13712. }
  13713. texture.width = info.width;
  13714. texture.height = info.height;
  13715. texture.type = info.textureType;
  13716. width = info.width;
  13717. }
  13718. _this.setCubeMapTextureParams(gl, loadMipmap);
  13719. texture.isReady = true;
  13720. if (onLoad) {
  13721. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13722. }
  13723. }, files, onError);
  13724. }
  13725. else {
  13726. this._loadFile(rootUrl, function (data) {
  13727. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13728. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13729. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13730. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13731. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13732. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13733. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13734. }
  13735. _this.setCubeMapTextureParams(gl, loadMipmap);
  13736. texture.width = info.width;
  13737. texture.height = info.height;
  13738. texture.isReady = true;
  13739. texture.type = info.textureType;
  13740. if (onLoad) {
  13741. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13742. }
  13743. }, undefined, undefined, true, onerror);
  13744. }
  13745. }
  13746. else {
  13747. if (!files) {
  13748. throw new Error("Cannot load cubemap because files were not defined");
  13749. }
  13750. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13751. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13752. var height = width;
  13753. _this._prepareWorkingCanvas();
  13754. if (!_this._workingCanvas || !_this._workingContext) {
  13755. return;
  13756. }
  13757. _this._workingCanvas.width = width;
  13758. _this._workingCanvas.height = height;
  13759. var faces = [
  13760. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13761. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13762. ];
  13763. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13764. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13765. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13766. for (var index = 0; index < faces.length; index++) {
  13767. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13768. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13769. }
  13770. if (!noMipmap) {
  13771. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13772. }
  13773. _this.setCubeMapTextureParams(gl, !noMipmap);
  13774. texture.width = width;
  13775. texture.height = height;
  13776. texture.isReady = true;
  13777. if (format) {
  13778. texture.format = format;
  13779. }
  13780. texture.onLoadedObservable.notifyObservers(texture);
  13781. texture.onLoadedObservable.clear();
  13782. if (onLoad) {
  13783. onLoad();
  13784. }
  13785. }, files, onError);
  13786. }
  13787. this._internalTexturesCache.push(texture);
  13788. return texture;
  13789. };
  13790. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13791. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13792. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13793. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13794. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13795. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13796. // this.resetTextureCache();
  13797. };
  13798. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13799. if (compression === void 0) { compression = null; }
  13800. if (level === void 0) { level = 0; }
  13801. texture._bufferViewArray = data;
  13802. texture.format = format;
  13803. texture.type = type;
  13804. texture.invertY = invertY;
  13805. texture._compression = compression;
  13806. var gl = this._gl;
  13807. var textureType = this._getWebGLTextureType(type);
  13808. var internalFormat = this._getInternalFormat(format);
  13809. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13810. var needConversion = false;
  13811. if (internalFormat === gl.RGB) {
  13812. internalFormat = gl.RGBA;
  13813. needConversion = true;
  13814. }
  13815. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13816. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13817. if (texture.width % 4 !== 0) {
  13818. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13819. }
  13820. // Data are known to be in +X +Y +Z -X -Y -Z
  13821. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13822. var faceData = data[faceIndex];
  13823. if (compression) {
  13824. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13825. }
  13826. else {
  13827. if (needConversion) {
  13828. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13829. }
  13830. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13831. }
  13832. }
  13833. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13834. if (isPot && texture.generateMipMaps && level === 0) {
  13835. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13836. }
  13837. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13838. // this.resetTextureCache();
  13839. texture.isReady = true;
  13840. };
  13841. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13842. if (compression === void 0) { compression = null; }
  13843. var gl = this._gl;
  13844. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13845. texture.isCube = true;
  13846. texture.generateMipMaps = generateMipMaps;
  13847. texture.format = format;
  13848. texture.type = type;
  13849. if (!this._doNotHandleContextLost) {
  13850. texture._bufferViewArray = data;
  13851. }
  13852. var textureType = this._getWebGLTextureType(type);
  13853. var internalFormat = this._getInternalFormat(format);
  13854. if (internalFormat === gl.RGB) {
  13855. internalFormat = gl.RGBA;
  13856. }
  13857. var width = size;
  13858. var height = width;
  13859. texture.width = width;
  13860. texture.height = height;
  13861. // Double check on POT to generate Mips.
  13862. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13863. if (!isPot) {
  13864. generateMipMaps = false;
  13865. }
  13866. // Upload data if needed. The texture won't be ready until then.
  13867. if (data) {
  13868. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13869. }
  13870. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13871. // Filters
  13872. if (data && generateMipMaps) {
  13873. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13874. }
  13875. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13878. }
  13879. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13882. }
  13883. else {
  13884. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13885. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13886. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13887. }
  13888. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13889. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13890. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13891. return texture;
  13892. };
  13893. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13894. var _this = this;
  13895. if (onLoad === void 0) { onLoad = null; }
  13896. if (onError === void 0) { onError = null; }
  13897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13898. if (invertY === void 0) { invertY = false; }
  13899. var gl = this._gl;
  13900. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13901. scene._addPendingData(texture);
  13902. texture.url = url;
  13903. this._internalTexturesCache.push(texture);
  13904. var onerror = function (request, exception) {
  13905. scene._removePendingData(texture);
  13906. if (onError && request) {
  13907. onError(request.status + " " + request.statusText, exception);
  13908. }
  13909. };
  13910. var internalCallback = function (data) {
  13911. var width = texture.width;
  13912. var faceDataArrays = callback(data);
  13913. if (!faceDataArrays) {
  13914. return;
  13915. }
  13916. if (mipmmapGenerator) {
  13917. var textureType = _this._getWebGLTextureType(type);
  13918. var internalFormat = _this._getInternalFormat(format);
  13919. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13920. var needConversion = false;
  13921. if (internalFormat === gl.RGB) {
  13922. internalFormat = gl.RGBA;
  13923. needConversion = true;
  13924. }
  13925. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13926. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13927. var mipData = mipmmapGenerator(faceDataArrays);
  13928. for (var level = 0; level < mipData.length; level++) {
  13929. var mipSize = width >> level;
  13930. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13931. var mipFaceData = mipData[level][faceIndex];
  13932. if (needConversion) {
  13933. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13934. }
  13935. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13936. }
  13937. }
  13938. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13939. }
  13940. else {
  13941. texture.generateMipMaps = !noMipmap;
  13942. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13943. }
  13944. texture.isReady = true;
  13945. // this.resetTextureCache();
  13946. scene._removePendingData(texture);
  13947. if (onLoad) {
  13948. onLoad();
  13949. }
  13950. };
  13951. this._loadFile(url, function (data) {
  13952. internalCallback(data);
  13953. }, undefined, scene.database, true, onerror);
  13954. return texture;
  13955. };
  13956. ;
  13957. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13958. if (compression === void 0) { compression = null; }
  13959. var internalFormat = this._getInternalFormat(format);
  13960. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13961. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13962. if (!this._doNotHandleContextLost) {
  13963. texture._bufferView = data;
  13964. texture.format = format;
  13965. texture.invertY = invertY;
  13966. texture._compression = compression;
  13967. }
  13968. if (texture.width % 4 !== 0) {
  13969. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13970. }
  13971. if (compression && data) {
  13972. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13973. }
  13974. else {
  13975. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13976. }
  13977. if (texture.generateMipMaps) {
  13978. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13979. }
  13980. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13981. // this.resetTextureCache();
  13982. texture.isReady = true;
  13983. };
  13984. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13985. if (compression === void 0) { compression = null; }
  13986. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13987. texture.baseWidth = width;
  13988. texture.baseHeight = height;
  13989. texture.baseDepth = depth;
  13990. texture.width = width;
  13991. texture.height = height;
  13992. texture.depth = depth;
  13993. texture.format = format;
  13994. texture.generateMipMaps = generateMipMaps;
  13995. texture.samplingMode = samplingMode;
  13996. texture.is3D = true;
  13997. if (!this._doNotHandleContextLost) {
  13998. texture._bufferView = data;
  13999. }
  14000. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14001. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14002. // Filters
  14003. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14004. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14005. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14006. if (generateMipMaps) {
  14007. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14008. }
  14009. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14010. this._internalTexturesCache.push(texture);
  14011. return texture;
  14012. };
  14013. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14014. var gl = this._gl;
  14015. if (!gl) {
  14016. return;
  14017. }
  14018. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14021. if (!noMipmap && !isCompressed) {
  14022. gl.generateMipmap(gl.TEXTURE_2D);
  14023. }
  14024. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14025. // this.resetTextureCache();
  14026. if (scene) {
  14027. scene._removePendingData(texture);
  14028. }
  14029. texture.onLoadedObservable.notifyObservers(texture);
  14030. texture.onLoadedObservable.clear();
  14031. };
  14032. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14033. var _this = this;
  14034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14035. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14036. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14037. var gl = this._gl;
  14038. if (!gl) {
  14039. return;
  14040. }
  14041. if (!texture._webGLTexture) {
  14042. // this.resetTextureCache();
  14043. if (scene) {
  14044. scene._removePendingData(texture);
  14045. }
  14046. return;
  14047. }
  14048. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14049. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14050. texture.baseWidth = width;
  14051. texture.baseHeight = height;
  14052. texture.width = potWidth;
  14053. texture.height = potHeight;
  14054. texture.isReady = true;
  14055. if (processFunction(potWidth, potHeight, function () {
  14056. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14057. })) {
  14058. // Returning as texture needs extra async steps
  14059. return;
  14060. }
  14061. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14062. };
  14063. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14064. // Create new RGBA data container.
  14065. var rgbaData;
  14066. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14067. rgbaData = new Float32Array(width * height * 4);
  14068. }
  14069. else {
  14070. rgbaData = new Uint32Array(width * height * 4);
  14071. }
  14072. // Convert each pixel.
  14073. for (var x = 0; x < width; x++) {
  14074. for (var y = 0; y < height; y++) {
  14075. var index = (y * width + x) * 3;
  14076. var newIndex = (y * width + x) * 4;
  14077. // Map Old Value to new value.
  14078. rgbaData[newIndex + 0] = rgbData[index + 0];
  14079. rgbaData[newIndex + 1] = rgbData[index + 1];
  14080. rgbaData[newIndex + 2] = rgbData[index + 2];
  14081. // Add fully opaque alpha channel.
  14082. rgbaData[newIndex + 3] = 1;
  14083. }
  14084. }
  14085. return rgbaData;
  14086. };
  14087. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14088. var gl = this._gl;
  14089. if (texture._framebuffer) {
  14090. gl.deleteFramebuffer(texture._framebuffer);
  14091. texture._framebuffer = null;
  14092. }
  14093. if (texture._depthStencilBuffer) {
  14094. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14095. texture._depthStencilBuffer = null;
  14096. }
  14097. if (texture._MSAAFramebuffer) {
  14098. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14099. texture._MSAAFramebuffer = null;
  14100. }
  14101. if (texture._MSAARenderBuffer) {
  14102. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14103. texture._MSAARenderBuffer = null;
  14104. }
  14105. };
  14106. Engine.prototype._releaseTexture = function (texture) {
  14107. var gl = this._gl;
  14108. this._releaseFramebufferObjects(texture);
  14109. gl.deleteTexture(texture._webGLTexture);
  14110. // Unbind channels
  14111. this.unbindAllTextures();
  14112. var index = this._internalTexturesCache.indexOf(texture);
  14113. if (index !== -1) {
  14114. this._internalTexturesCache.splice(index, 1);
  14115. }
  14116. // Integrated fixed lod samplers.
  14117. if (texture._lodTextureHigh) {
  14118. texture._lodTextureHigh.dispose();
  14119. }
  14120. if (texture._lodTextureMid) {
  14121. texture._lodTextureMid.dispose();
  14122. }
  14123. if (texture._lodTextureLow) {
  14124. texture._lodTextureLow.dispose();
  14125. }
  14126. };
  14127. Engine.prototype.setProgram = function (program) {
  14128. if (this._currentProgram !== program) {
  14129. this._gl.useProgram(program);
  14130. this._currentProgram = program;
  14131. }
  14132. };
  14133. Engine.prototype.bindSamplers = function (effect) {
  14134. this.setProgram(effect.getProgram());
  14135. var samplers = effect.getSamplers();
  14136. for (var index = 0; index < samplers.length; index++) {
  14137. var uniform = effect.getUniform(samplers[index]);
  14138. if (uniform) {
  14139. this._boundUniforms[index] = uniform;
  14140. }
  14141. }
  14142. this._currentEffect = null;
  14143. };
  14144. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14145. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14146. return;
  14147. }
  14148. // Remove
  14149. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14150. // Bind last to it
  14151. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14152. // Bind to dummy
  14153. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14154. };
  14155. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14156. if (!internalTexture) {
  14157. return -1;
  14158. }
  14159. internalTexture._initialSlot = channel;
  14160. if (this.disableTextureBindingOptimization) {
  14161. if (channel !== internalTexture._designatedSlot) {
  14162. this._textureCollisions.addCount(1, false);
  14163. }
  14164. }
  14165. else {
  14166. if (channel !== internalTexture._designatedSlot) {
  14167. if (internalTexture._designatedSlot > -1) {
  14168. return internalTexture._designatedSlot;
  14169. }
  14170. else {
  14171. // No slot for this texture, let's pick a new one (if we find a free slot)
  14172. if (this._nextFreeTextureSlots.length) {
  14173. return this._nextFreeTextureSlots[0];
  14174. }
  14175. // We need to recycle the oldest bound texture, sorry.
  14176. this._textureCollisions.addCount(1, false);
  14177. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14178. }
  14179. }
  14180. }
  14181. return channel;
  14182. };
  14183. Engine.prototype._linkTrackers = function (previous, next) {
  14184. previous.next = next;
  14185. next.previous = previous;
  14186. };
  14187. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14188. var currentSlot = internalTexture._designatedSlot;
  14189. if (currentSlot === -1) {
  14190. return -1;
  14191. }
  14192. internalTexture._designatedSlot = -1;
  14193. if (this.disableTextureBindingOptimization) {
  14194. return -1;
  14195. }
  14196. // Remove from bound list
  14197. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14198. // Free the slot
  14199. this._boundTexturesCache[currentSlot] = null;
  14200. this._nextFreeTextureSlots.push(currentSlot);
  14201. return currentSlot;
  14202. };
  14203. Engine.prototype._activateCurrentTexture = function () {
  14204. if (this._currentTextureChannel !== this._activeChannel) {
  14205. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14206. this._currentTextureChannel = this._activeChannel;
  14207. }
  14208. };
  14209. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14210. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14211. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14212. this._activeChannel = texture._designatedSlot;
  14213. }
  14214. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14215. var isTextureForRendering = texture && texture._initialSlot > -1;
  14216. if (currentTextureBound !== texture) {
  14217. if (currentTextureBound) {
  14218. this._removeDesignatedSlot(currentTextureBound);
  14219. }
  14220. this._activateCurrentTexture();
  14221. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14222. this._boundTexturesCache[this._activeChannel] = texture;
  14223. if (texture) {
  14224. if (!this.disableTextureBindingOptimization) {
  14225. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14226. if (slotIndex > -1) {
  14227. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14228. }
  14229. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14230. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14231. }
  14232. texture._designatedSlot = this._activeChannel;
  14233. }
  14234. }
  14235. else if (forTextureDataUpdate) {
  14236. this._activateCurrentTexture();
  14237. }
  14238. if (isTextureForRendering && !forTextureDataUpdate) {
  14239. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14240. }
  14241. };
  14242. Engine.prototype._bindTexture = function (channel, texture) {
  14243. if (channel < 0) {
  14244. return;
  14245. }
  14246. if (texture) {
  14247. channel = this._getCorrectTextureChannel(channel, texture);
  14248. }
  14249. this._activeChannel = channel;
  14250. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14251. };
  14252. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14253. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14254. };
  14255. Engine.prototype.unbindAllTextures = function () {
  14256. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14257. this._activeChannel = channel;
  14258. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14259. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14260. if (this.webGLVersion > 1) {
  14261. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14262. }
  14263. }
  14264. };
  14265. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14266. if (channel < 0) {
  14267. return;
  14268. }
  14269. if (uniform) {
  14270. this._boundUniforms[channel] = uniform;
  14271. }
  14272. this._setTexture(channel, texture);
  14273. };
  14274. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14275. var uniform = this._boundUniforms[sourceSlot];
  14276. if (uniform._currentState === destination) {
  14277. return;
  14278. }
  14279. this._gl.uniform1i(uniform, destination);
  14280. uniform._currentState = destination;
  14281. };
  14282. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14283. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14284. // Not ready?
  14285. if (!texture) {
  14286. if (this._boundTexturesCache[channel] != null) {
  14287. this._activeChannel = channel;
  14288. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14289. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14290. if (this.webGLVersion > 1) {
  14291. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14292. }
  14293. }
  14294. return false;
  14295. }
  14296. // Video
  14297. if (texture.video) {
  14298. this._activeChannel = channel;
  14299. texture.update();
  14300. }
  14301. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14302. texture.delayLoad();
  14303. return false;
  14304. }
  14305. var internalTexture;
  14306. if (texture.isReady()) {
  14307. internalTexture = texture.getInternalTexture();
  14308. }
  14309. else if (texture.isCube) {
  14310. internalTexture = this.emptyCubeTexture;
  14311. }
  14312. else if (texture.is3D) {
  14313. internalTexture = this.emptyTexture3D;
  14314. }
  14315. else {
  14316. internalTexture = this.emptyTexture;
  14317. }
  14318. if (!isPartOfTextureArray) {
  14319. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14320. }
  14321. if (this._boundTexturesCache[channel] === internalTexture) {
  14322. this._moveBoundTextureOnTop(internalTexture);
  14323. if (!isPartOfTextureArray) {
  14324. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14325. }
  14326. return false;
  14327. }
  14328. this._activeChannel = channel;
  14329. if (internalTexture && internalTexture.is3D) {
  14330. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14331. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14332. internalTexture._cachedWrapU = texture.wrapU;
  14333. switch (texture.wrapU) {
  14334. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14335. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14336. break;
  14337. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14338. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14339. break;
  14340. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14341. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14342. break;
  14343. }
  14344. }
  14345. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14346. internalTexture._cachedWrapV = texture.wrapV;
  14347. switch (texture.wrapV) {
  14348. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14349. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14350. break;
  14351. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14352. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14353. break;
  14354. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14355. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14356. break;
  14357. }
  14358. }
  14359. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14360. internalTexture._cachedWrapR = texture.wrapR;
  14361. switch (texture.wrapR) {
  14362. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14363. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14364. break;
  14365. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14366. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14367. break;
  14368. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14369. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14370. break;
  14371. }
  14372. }
  14373. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14374. }
  14375. else if (internalTexture && internalTexture.isCube) {
  14376. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14377. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14378. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14379. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14380. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14381. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14382. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14383. }
  14384. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14385. }
  14386. else {
  14387. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14388. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14389. internalTexture._cachedWrapU = texture.wrapU;
  14390. switch (texture.wrapU) {
  14391. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14392. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14393. break;
  14394. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14395. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14396. break;
  14397. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14399. break;
  14400. }
  14401. }
  14402. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14403. internalTexture._cachedWrapV = texture.wrapV;
  14404. switch (texture.wrapV) {
  14405. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14406. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14407. break;
  14408. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14409. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14410. break;
  14411. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14412. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14413. break;
  14414. }
  14415. }
  14416. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14417. }
  14418. return true;
  14419. };
  14420. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14421. if (channel < 0 || !uniform) {
  14422. return;
  14423. }
  14424. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14425. this._textureUnits = new Int32Array(textures.length);
  14426. }
  14427. for (var i = 0; i < textures.length; i++) {
  14428. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14429. }
  14430. this._gl.uniform1iv(uniform, this._textureUnits);
  14431. for (var index = 0; index < textures.length; index++) {
  14432. this._setTexture(this._textureUnits[index], textures[index], true);
  14433. }
  14434. };
  14435. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14436. var internalTexture = texture.getInternalTexture();
  14437. if (!internalTexture) {
  14438. return;
  14439. }
  14440. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14441. var value = texture.anisotropicFilteringLevel;
  14442. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14443. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14444. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14445. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14446. }
  14447. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14448. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14449. internalTexture._cachedAnisotropicFilteringLevel = value;
  14450. }
  14451. };
  14452. Engine.prototype.readPixels = function (x, y, width, height) {
  14453. var data = new Uint8Array(height * width * 4);
  14454. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14455. return data;
  14456. };
  14457. /**
  14458. * Add an externaly attached data from its key.
  14459. * This method call will fail and return false, if such key already exists.
  14460. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14461. * @param key the unique key that identifies the data
  14462. * @param data the data object to associate to the key for this Engine instance
  14463. * @return true if no such key were already present and the data was added successfully, false otherwise
  14464. */
  14465. Engine.prototype.addExternalData = function (key, data) {
  14466. if (!this._externalData) {
  14467. this._externalData = new BABYLON.StringDictionary();
  14468. }
  14469. return this._externalData.add(key, data);
  14470. };
  14471. /**
  14472. * Get an externaly attached data from its key
  14473. * @param key the unique key that identifies the data
  14474. * @return the associated data, if present (can be null), or undefined if not present
  14475. */
  14476. Engine.prototype.getExternalData = function (key) {
  14477. if (!this._externalData) {
  14478. this._externalData = new BABYLON.StringDictionary();
  14479. }
  14480. return this._externalData.get(key);
  14481. };
  14482. /**
  14483. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14484. * @param key the unique key that identifies the data
  14485. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14486. * @return the associated data, can be null if the factory returned null.
  14487. */
  14488. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14489. if (!this._externalData) {
  14490. this._externalData = new BABYLON.StringDictionary();
  14491. }
  14492. return this._externalData.getOrAddWithFactory(key, factory);
  14493. };
  14494. /**
  14495. * Remove an externaly attached data from the Engine instance
  14496. * @param key the unique key that identifies the data
  14497. * @return true if the data was successfully removed, false if it doesn't exist
  14498. */
  14499. Engine.prototype.removeExternalData = function (key) {
  14500. if (!this._externalData) {
  14501. this._externalData = new BABYLON.StringDictionary();
  14502. }
  14503. return this._externalData.remove(key);
  14504. };
  14505. Engine.prototype.unbindAllAttributes = function () {
  14506. if (this._mustWipeVertexAttributes) {
  14507. this._mustWipeVertexAttributes = false;
  14508. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14509. this._gl.disableVertexAttribArray(i);
  14510. this._vertexAttribArraysEnabled[i] = false;
  14511. this._currentBufferPointers[i].active = false;
  14512. }
  14513. return;
  14514. }
  14515. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14516. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14517. continue;
  14518. }
  14519. this._gl.disableVertexAttribArray(i);
  14520. this._vertexAttribArraysEnabled[i] = false;
  14521. this._currentBufferPointers[i].active = false;
  14522. }
  14523. };
  14524. Engine.prototype.releaseEffects = function () {
  14525. for (var name in this._compiledEffects) {
  14526. this._deleteProgram(this._compiledEffects[name]._program);
  14527. }
  14528. this._compiledEffects = {};
  14529. };
  14530. // Dispose
  14531. Engine.prototype.dispose = function () {
  14532. this.hideLoadingUI();
  14533. this.stopRenderLoop();
  14534. // Release postProcesses
  14535. while (this.postProcesses.length) {
  14536. this.postProcesses[0].dispose();
  14537. }
  14538. // Empty texture
  14539. if (this._emptyTexture) {
  14540. this._releaseTexture(this._emptyTexture);
  14541. this._emptyTexture = null;
  14542. }
  14543. if (this._emptyCubeTexture) {
  14544. this._releaseTexture(this._emptyCubeTexture);
  14545. this._emptyCubeTexture = null;
  14546. }
  14547. // Rescale PP
  14548. if (this._rescalePostProcess) {
  14549. this._rescalePostProcess.dispose();
  14550. }
  14551. // Release scenes
  14552. while (this.scenes.length) {
  14553. this.scenes[0].dispose();
  14554. }
  14555. // Release audio engine
  14556. if (Engine.audioEngine) {
  14557. Engine.audioEngine.dispose();
  14558. }
  14559. // Release effects
  14560. this.releaseEffects();
  14561. // Unbind
  14562. this.unbindAllAttributes();
  14563. if (this._dummyFramebuffer) {
  14564. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14565. }
  14566. //WebVR
  14567. this.disableVR();
  14568. // Events
  14569. if (BABYLON.Tools.IsWindowObjectExist()) {
  14570. window.removeEventListener("blur", this._onBlur);
  14571. window.removeEventListener("focus", this._onFocus);
  14572. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14573. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14574. if (this._renderingCanvas) {
  14575. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14576. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14577. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14578. if (!this._doNotHandleContextLost) {
  14579. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14580. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14581. }
  14582. }
  14583. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14584. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14585. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14586. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14587. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14588. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14589. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14590. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14591. if (this._onVrDisplayConnect) {
  14592. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14593. if (this._onVrDisplayDisconnect) {
  14594. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14595. }
  14596. if (this._onVrDisplayPresentChange) {
  14597. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14598. }
  14599. this._onVrDisplayConnect = null;
  14600. this._onVrDisplayDisconnect = null;
  14601. }
  14602. }
  14603. // Remove from Instances
  14604. var index = Engine.Instances.indexOf(this);
  14605. if (index >= 0) {
  14606. Engine.Instances.splice(index, 1);
  14607. }
  14608. this._workingCanvas = null;
  14609. this._workingContext = null;
  14610. this._currentBufferPointers = [];
  14611. this._renderingCanvas = null;
  14612. this._currentProgram = null;
  14613. this.onResizeObservable.clear();
  14614. this.onCanvasBlurObservable.clear();
  14615. this.onCanvasFocusObservable.clear();
  14616. this.onCanvasPointerOutObservable.clear();
  14617. this.onBeginFrameObservable.clear();
  14618. this.onEndFrameObservable.clear();
  14619. BABYLON.Effect.ResetCache();
  14620. // Abort active requests
  14621. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14622. var request = _a[_i];
  14623. request.abort();
  14624. }
  14625. };
  14626. // Loading screen
  14627. Engine.prototype.displayLoadingUI = function () {
  14628. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14629. return;
  14630. }
  14631. var loadingScreen = this.loadingScreen;
  14632. if (loadingScreen) {
  14633. loadingScreen.displayLoadingUI();
  14634. }
  14635. };
  14636. Engine.prototype.hideLoadingUI = function () {
  14637. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14638. return;
  14639. }
  14640. var loadingScreen = this.loadingScreen;
  14641. if (loadingScreen) {
  14642. loadingScreen.hideLoadingUI();
  14643. }
  14644. };
  14645. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14646. get: function () {
  14647. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14648. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14649. return this._loadingScreen;
  14650. },
  14651. set: function (loadingScreen) {
  14652. this._loadingScreen = loadingScreen;
  14653. },
  14654. enumerable: true,
  14655. configurable: true
  14656. });
  14657. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14658. set: function (text) {
  14659. this.loadingScreen.loadingUIText = text;
  14660. },
  14661. enumerable: true,
  14662. configurable: true
  14663. });
  14664. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14665. set: function (color) {
  14666. this.loadingScreen.loadingUIBackgroundColor = color;
  14667. },
  14668. enumerable: true,
  14669. configurable: true
  14670. });
  14671. Engine.prototype.attachContextLostEvent = function (callback) {
  14672. if (this._renderingCanvas) {
  14673. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14674. }
  14675. };
  14676. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14677. if (this._renderingCanvas) {
  14678. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14679. }
  14680. };
  14681. Engine.prototype.getVertexShaderSource = function (program) {
  14682. var shaders = this._gl.getAttachedShaders(program);
  14683. if (!shaders) {
  14684. return null;
  14685. }
  14686. return this._gl.getShaderSource(shaders[0]);
  14687. };
  14688. Engine.prototype.getFragmentShaderSource = function (program) {
  14689. var shaders = this._gl.getAttachedShaders(program);
  14690. if (!shaders) {
  14691. return null;
  14692. }
  14693. return this._gl.getShaderSource(shaders[1]);
  14694. };
  14695. Engine.prototype.getError = function () {
  14696. return this._gl.getError();
  14697. };
  14698. // FPS
  14699. Engine.prototype.getFps = function () {
  14700. return this._fps;
  14701. };
  14702. Engine.prototype.getDeltaTime = function () {
  14703. return this._deltaTime;
  14704. };
  14705. Engine.prototype._measureFps = function () {
  14706. this._performanceMonitor.sampleFrame();
  14707. this._fps = this._performanceMonitor.averageFPS;
  14708. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14709. };
  14710. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14711. if (faceIndex === void 0) { faceIndex = -1; }
  14712. var gl = this._gl;
  14713. if (!this._dummyFramebuffer) {
  14714. var dummy = gl.createFramebuffer();
  14715. if (!dummy) {
  14716. throw new Error("Unable to create dummy framebuffer");
  14717. }
  14718. this._dummyFramebuffer = dummy;
  14719. }
  14720. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14721. if (faceIndex > -1) {
  14722. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14723. }
  14724. else {
  14725. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14726. }
  14727. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14728. var buffer;
  14729. switch (readType) {
  14730. case gl.UNSIGNED_BYTE:
  14731. buffer = new Uint8Array(4 * width * height);
  14732. readType = gl.UNSIGNED_BYTE;
  14733. break;
  14734. default:
  14735. buffer = new Float32Array(4 * width * height);
  14736. readType = gl.FLOAT;
  14737. break;
  14738. }
  14739. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14740. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14741. return buffer;
  14742. };
  14743. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14744. if (this._webGLVersion > 1) {
  14745. return this._caps.colorBufferFloat;
  14746. }
  14747. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14748. };
  14749. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14750. if (this._webGLVersion > 1) {
  14751. return this._caps.colorBufferFloat;
  14752. }
  14753. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14754. };
  14755. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14756. Engine.prototype._canRenderToFramebuffer = function (type) {
  14757. var gl = this._gl;
  14758. //clear existing errors
  14759. while (gl.getError() !== gl.NO_ERROR) { }
  14760. var successful = true;
  14761. var texture = gl.createTexture();
  14762. gl.bindTexture(gl.TEXTURE_2D, texture);
  14763. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14766. var fb = gl.createFramebuffer();
  14767. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14768. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14769. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14770. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14771. successful = successful && (gl.getError() === gl.NO_ERROR);
  14772. //try render by clearing frame buffer's color buffer
  14773. if (successful) {
  14774. gl.clear(gl.COLOR_BUFFER_BIT);
  14775. successful = successful && (gl.getError() === gl.NO_ERROR);
  14776. }
  14777. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14778. if (successful) {
  14779. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14780. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14781. var readFormat = gl.RGBA;
  14782. var readType = gl.UNSIGNED_BYTE;
  14783. var buffer = new Uint8Array(4);
  14784. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14785. successful = successful && (gl.getError() === gl.NO_ERROR);
  14786. }
  14787. //clean up
  14788. gl.deleteTexture(texture);
  14789. gl.deleteFramebuffer(fb);
  14790. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14791. //clear accumulated errors
  14792. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14793. return successful;
  14794. };
  14795. Engine.prototype._getWebGLTextureType = function (type) {
  14796. if (type === Engine.TEXTURETYPE_FLOAT) {
  14797. return this._gl.FLOAT;
  14798. }
  14799. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14800. // Add Half Float Constant.
  14801. return this._gl.HALF_FLOAT_OES;
  14802. }
  14803. return this._gl.UNSIGNED_BYTE;
  14804. };
  14805. ;
  14806. /** @ignore */
  14807. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14808. if (this._webGLVersion === 1) {
  14809. return this._gl.RGBA;
  14810. }
  14811. if (type === Engine.TEXTURETYPE_FLOAT) {
  14812. if (format) {
  14813. switch (format) {
  14814. case Engine.TEXTUREFORMAT_R32F:
  14815. return this._gl.R32F;
  14816. case Engine.TEXTUREFORMAT_RG32F:
  14817. return this._gl.RG32F;
  14818. case Engine.TEXTUREFORMAT_RGB32F:
  14819. return this._gl.RGB32F;
  14820. }
  14821. }
  14822. return this._gl.RGBA32F;
  14823. }
  14824. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14825. return this._gl.RGBA16F;
  14826. }
  14827. return this._gl.RGBA;
  14828. };
  14829. ;
  14830. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14831. if (type === Engine.TEXTURETYPE_FLOAT) {
  14832. return this._gl.RGBA32F;
  14833. }
  14834. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14835. return this._gl.RGBA16F;
  14836. }
  14837. return this._gl.RGBA8;
  14838. };
  14839. ;
  14840. Engine.prototype.createQuery = function () {
  14841. return this._gl.createQuery();
  14842. };
  14843. Engine.prototype.deleteQuery = function (query) {
  14844. this._gl.deleteQuery(query);
  14845. return this;
  14846. };
  14847. Engine.prototype.isQueryResultAvailable = function (query) {
  14848. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14849. };
  14850. Engine.prototype.getQueryResult = function (query) {
  14851. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14852. };
  14853. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14854. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14855. this._gl.beginQuery(glAlgorithm, query);
  14856. return this;
  14857. };
  14858. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14859. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14860. this._gl.endQuery(glAlgorithm);
  14861. return this;
  14862. };
  14863. /* Time queries */
  14864. Engine.prototype._createTimeQuery = function () {
  14865. var timerQuery = this._caps.timerQuery;
  14866. if (timerQuery.createQueryEXT) {
  14867. return timerQuery.createQueryEXT();
  14868. }
  14869. return this.createQuery();
  14870. };
  14871. Engine.prototype._deleteTimeQuery = function (query) {
  14872. var timerQuery = this._caps.timerQuery;
  14873. if (timerQuery.deleteQueryEXT) {
  14874. timerQuery.deleteQueryEXT(query);
  14875. return;
  14876. }
  14877. this.deleteQuery(query);
  14878. };
  14879. Engine.prototype._getTimeQueryResult = function (query) {
  14880. var timerQuery = this._caps.timerQuery;
  14881. if (timerQuery.getQueryObjectEXT) {
  14882. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14883. }
  14884. return this.getQueryResult(query);
  14885. };
  14886. Engine.prototype._getTimeQueryAvailability = function (query) {
  14887. var timerQuery = this._caps.timerQuery;
  14888. if (timerQuery.getQueryObjectEXT) {
  14889. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14890. }
  14891. return this.isQueryResultAvailable(query);
  14892. };
  14893. Engine.prototype.startTimeQuery = function () {
  14894. var timerQuery = this._caps.timerQuery;
  14895. if (!timerQuery) {
  14896. return null;
  14897. }
  14898. var token = new BABYLON._TimeToken();
  14899. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14900. if (this._caps.canUseTimestampForTimerQuery) {
  14901. token._startTimeQuery = this._createTimeQuery();
  14902. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14903. }
  14904. else {
  14905. if (this._currentNonTimestampToken) {
  14906. return this._currentNonTimestampToken;
  14907. }
  14908. token._timeElapsedQuery = this._createTimeQuery();
  14909. if (timerQuery.beginQueryEXT) {
  14910. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14911. }
  14912. else {
  14913. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14914. }
  14915. this._currentNonTimestampToken = token;
  14916. }
  14917. return token;
  14918. };
  14919. Engine.prototype.endTimeQuery = function (token) {
  14920. var timerQuery = this._caps.timerQuery;
  14921. if (!timerQuery || !token) {
  14922. return -1;
  14923. }
  14924. if (this._caps.canUseTimestampForTimerQuery) {
  14925. if (!token._startTimeQuery) {
  14926. return -1;
  14927. }
  14928. if (!token._endTimeQuery) {
  14929. token._endTimeQuery = this._createTimeQuery();
  14930. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14931. }
  14932. }
  14933. else if (!token._timeElapsedQueryEnded) {
  14934. if (!token._timeElapsedQuery) {
  14935. return -1;
  14936. }
  14937. if (timerQuery.endQueryEXT) {
  14938. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14939. }
  14940. else {
  14941. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14942. }
  14943. token._timeElapsedQueryEnded = true;
  14944. }
  14945. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14946. var available = false;
  14947. if (token._endTimeQuery) {
  14948. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14949. }
  14950. else if (token._timeElapsedQuery) {
  14951. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14952. }
  14953. if (available && !disjoint) {
  14954. var result = 0;
  14955. if (this._caps.canUseTimestampForTimerQuery) {
  14956. if (!token._startTimeQuery || !token._endTimeQuery) {
  14957. return -1;
  14958. }
  14959. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14960. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14961. result = timeEnd - timeStart;
  14962. this._deleteTimeQuery(token._startTimeQuery);
  14963. this._deleteTimeQuery(token._endTimeQuery);
  14964. token._startTimeQuery = null;
  14965. token._endTimeQuery = null;
  14966. }
  14967. else {
  14968. if (!token._timeElapsedQuery) {
  14969. return -1;
  14970. }
  14971. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14972. this._deleteTimeQuery(token._timeElapsedQuery);
  14973. token._timeElapsedQuery = null;
  14974. token._timeElapsedQueryEnded = false;
  14975. this._currentNonTimestampToken = null;
  14976. }
  14977. return result;
  14978. }
  14979. return -1;
  14980. };
  14981. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14982. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14983. };
  14984. // Transform feedback
  14985. Engine.prototype.createTransformFeedback = function () {
  14986. return this._gl.createTransformFeedback();
  14987. };
  14988. Engine.prototype.deleteTransformFeedback = function (value) {
  14989. this._gl.deleteTransformFeedback(value);
  14990. };
  14991. Engine.prototype.bindTransformFeedback = function (value) {
  14992. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14993. };
  14994. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14995. if (usePoints === void 0) { usePoints = true; }
  14996. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14997. };
  14998. Engine.prototype.endTransformFeedback = function () {
  14999. this._gl.endTransformFeedback();
  15000. };
  15001. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15002. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15003. };
  15004. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15005. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15006. };
  15007. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15008. var _this = this;
  15009. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15010. this._activeRequests.push(request);
  15011. request.onCompleteObservable.add(function (request) {
  15012. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15013. });
  15014. return request;
  15015. };
  15016. /** @ignore */
  15017. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15018. var _this = this;
  15019. return new Promise(function (resolve, reject) {
  15020. _this._loadFile(url, function (data) {
  15021. resolve(data);
  15022. }, undefined, database, useArrayBuffer, function (request, exception) {
  15023. reject(exception);
  15024. });
  15025. });
  15026. };
  15027. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15028. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15029. var onload = function (data) {
  15030. loadedFiles[index] = data;
  15031. loadedFiles._internalCount++;
  15032. if (loadedFiles._internalCount === 6) {
  15033. onfinish(loadedFiles);
  15034. }
  15035. };
  15036. var onerror = function (request, exception) {
  15037. if (onErrorCallBack && request) {
  15038. onErrorCallBack(request.status + " " + request.statusText, exception);
  15039. }
  15040. };
  15041. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15042. };
  15043. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  15044. if (onError === void 0) { onError = null; }
  15045. var loadedFiles = [];
  15046. loadedFiles._internalCount = 0;
  15047. for (var index = 0; index < 6; index++) {
  15048. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15049. }
  15050. };
  15051. // Statics
  15052. Engine.isSupported = function () {
  15053. try {
  15054. var tempcanvas = document.createElement("canvas");
  15055. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15056. return gl != null && !!window.WebGLRenderingContext;
  15057. }
  15058. catch (e) {
  15059. return false;
  15060. }
  15061. };
  15062. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15063. Engine.ExceptionList = [
  15064. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15065. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15066. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15067. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15068. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15069. ];
  15070. Engine.Instances = new Array();
  15071. // Const statics
  15072. Engine._ALPHA_DISABLE = 0;
  15073. Engine._ALPHA_ADD = 1;
  15074. Engine._ALPHA_COMBINE = 2;
  15075. Engine._ALPHA_SUBTRACT = 3;
  15076. Engine._ALPHA_MULTIPLY = 4;
  15077. Engine._ALPHA_MAXIMIZED = 5;
  15078. Engine._ALPHA_ONEONE = 6;
  15079. Engine._ALPHA_PREMULTIPLIED = 7;
  15080. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15081. Engine._ALPHA_INTERPOLATE = 9;
  15082. Engine._ALPHA_SCREENMODE = 10;
  15083. Engine._DELAYLOADSTATE_NONE = 0;
  15084. Engine._DELAYLOADSTATE_LOADED = 1;
  15085. Engine._DELAYLOADSTATE_LOADING = 2;
  15086. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15087. Engine._TEXTUREFORMAT_ALPHA = 0;
  15088. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15089. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15090. Engine._TEXTUREFORMAT_RGB = 4;
  15091. Engine._TEXTUREFORMAT_RGBA = 5;
  15092. Engine._TEXTUREFORMAT_R32F = 6;
  15093. Engine._TEXTUREFORMAT_RG32F = 7;
  15094. Engine._TEXTUREFORMAT_RGB32F = 8;
  15095. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15096. Engine._TEXTURETYPE_FLOAT = 1;
  15097. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15098. // Depht or Stencil test Constants.
  15099. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15100. 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.
  15101. 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.
  15102. 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.
  15103. 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.
  15104. 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.
  15105. 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.
  15106. 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.
  15107. // Stencil Actions Constants.
  15108. Engine._KEEP = 0x1E00;
  15109. Engine._REPLACE = 0x1E01;
  15110. Engine._INCR = 0x1E02;
  15111. Engine._DECR = 0x1E03;
  15112. Engine._INVERT = 0x150A;
  15113. Engine._INCR_WRAP = 0x8507;
  15114. Engine._DECR_WRAP = 0x8508;
  15115. // Texture rescaling mode
  15116. Engine._SCALEMODE_FLOOR = 1;
  15117. Engine._SCALEMODE_NEAREST = 2;
  15118. Engine._SCALEMODE_CEILING = 3;
  15119. // Updatable statics so stick with vars here
  15120. Engine.CollisionsEpsilon = 0.001;
  15121. Engine.CodeRepository = "src/";
  15122. Engine.ShadersRepository = "src/Shaders/";
  15123. return Engine;
  15124. }());
  15125. BABYLON.Engine = Engine;
  15126. })(BABYLON || (BABYLON = {}));
  15127. //# sourceMappingURL=babylon.engine.js.map
  15128. var BABYLON;
  15129. (function (BABYLON) {
  15130. /**
  15131. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15132. */
  15133. var Node = /** @class */ (function () {
  15134. /**
  15135. * Creates a new Node
  15136. * @param {string} name - the name and id to be given to this node
  15137. * @param {BABYLON.Scene} the scene this node will be added to
  15138. */
  15139. function Node(name, scene) {
  15140. if (scene === void 0) { scene = null; }
  15141. /**
  15142. * Gets or sets a string used to store user defined state for the node
  15143. */
  15144. this.state = "";
  15145. /**
  15146. * Gets or sets an object used to store user defined information for the node
  15147. */
  15148. this.metadata = null;
  15149. /**
  15150. * Gets or sets a boolean used to define if the node must be serialized
  15151. */
  15152. this.doNotSerialize = false;
  15153. /** @ignore */
  15154. this._isDisposed = false;
  15155. /**
  15156. * Gets a list of {BABYLON.Animation} associated with the node
  15157. */
  15158. this.animations = new Array();
  15159. this._ranges = {};
  15160. this._isEnabled = true;
  15161. this._isReady = true;
  15162. /** @ignore */
  15163. this._currentRenderId = -1;
  15164. this._parentRenderId = -1;
  15165. /**
  15166. * An event triggered when the mesh is disposed
  15167. * @type {BABYLON.Observable}
  15168. */
  15169. this.onDisposeObservable = new BABYLON.Observable();
  15170. // Behaviors
  15171. this._behaviors = new Array();
  15172. this.name = name;
  15173. this.id = name;
  15174. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15175. this.uniqueId = this._scene.getUniqueId();
  15176. this._initCache();
  15177. }
  15178. /**
  15179. * Gets a boolean indicating if the node has been disposed
  15180. * @returns true if the node was disposed
  15181. */
  15182. Node.prototype.isDisposed = function () {
  15183. return this._isDisposed;
  15184. };
  15185. Object.defineProperty(Node.prototype, "parent", {
  15186. get: function () {
  15187. return this._parentNode;
  15188. },
  15189. /**
  15190. * Gets or sets the parent of the node
  15191. */
  15192. set: function (parent) {
  15193. if (this._parentNode === parent) {
  15194. return;
  15195. }
  15196. // Remove self from list of children of parent
  15197. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15198. var index = this._parentNode._children.indexOf(this);
  15199. if (index !== -1) {
  15200. this._parentNode._children.splice(index, 1);
  15201. }
  15202. }
  15203. // Store new parent
  15204. this._parentNode = parent;
  15205. // Add as child to new parent
  15206. if (this._parentNode) {
  15207. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15208. this._parentNode._children = new Array();
  15209. }
  15210. this._parentNode._children.push(this);
  15211. }
  15212. },
  15213. enumerable: true,
  15214. configurable: true
  15215. });
  15216. /**
  15217. * Gets a string idenfifying the name of the class
  15218. * @returns "Node" string
  15219. */
  15220. Node.prototype.getClassName = function () {
  15221. return "Node";
  15222. };
  15223. Object.defineProperty(Node.prototype, "onDispose", {
  15224. /**
  15225. * Sets a callback that will be raised when the node will be disposed
  15226. */
  15227. set: function (callback) {
  15228. if (this._onDisposeObserver) {
  15229. this.onDisposeObservable.remove(this._onDisposeObserver);
  15230. }
  15231. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15232. },
  15233. enumerable: true,
  15234. configurable: true
  15235. });
  15236. /**
  15237. * Gets the scene of the node
  15238. * @returns a {BABYLON.Scene}
  15239. */
  15240. Node.prototype.getScene = function () {
  15241. return this._scene;
  15242. };
  15243. /**
  15244. * Gets the engine of the node
  15245. * @returns a {BABYLON.Engine}
  15246. */
  15247. Node.prototype.getEngine = function () {
  15248. return this._scene.getEngine();
  15249. };
  15250. /**
  15251. * Attach a behavior to the node
  15252. * @see http://doc.babylonjs.com/features/behaviour
  15253. * @param behavior defines the behavior to attach
  15254. * @returns the current Node
  15255. */
  15256. Node.prototype.addBehavior = function (behavior) {
  15257. var _this = this;
  15258. var index = this._behaviors.indexOf(behavior);
  15259. if (index !== -1) {
  15260. return this;
  15261. }
  15262. behavior.init();
  15263. if (this._scene.isLoading) {
  15264. // We defer the attach when the scene will be loaded
  15265. var observer = this._scene.onDataLoadedObservable.add(function () {
  15266. behavior.attach(_this);
  15267. setTimeout(function () {
  15268. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15269. _this._scene.onDataLoadedObservable.remove(observer);
  15270. }, 0);
  15271. });
  15272. }
  15273. else {
  15274. behavior.attach(this);
  15275. }
  15276. this._behaviors.push(behavior);
  15277. return this;
  15278. };
  15279. /**
  15280. * Remove an attached behavior
  15281. * @see http://doc.babylonjs.com/features/behaviour
  15282. * @param behavior defines the behavior to attach
  15283. * @returns the current Node
  15284. */
  15285. Node.prototype.removeBehavior = function (behavior) {
  15286. var index = this._behaviors.indexOf(behavior);
  15287. if (index === -1) {
  15288. return this;
  15289. }
  15290. this._behaviors[index].detach();
  15291. this._behaviors.splice(index, 1);
  15292. return this;
  15293. };
  15294. Object.defineProperty(Node.prototype, "behaviors", {
  15295. /**
  15296. * Gets the list of attached behaviors
  15297. * @see http://doc.babylonjs.com/features/behaviour
  15298. */
  15299. get: function () {
  15300. return this._behaviors;
  15301. },
  15302. enumerable: true,
  15303. configurable: true
  15304. });
  15305. /**
  15306. * Gets an attached behavior by name
  15307. * @param name defines the name of the behavior to look for
  15308. * @see http://doc.babylonjs.com/features/behaviour
  15309. * @returns null if behavior was not found else the requested behavior
  15310. */
  15311. Node.prototype.getBehaviorByName = function (name) {
  15312. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15313. var behavior = _a[_i];
  15314. if (behavior.name === name) {
  15315. return behavior;
  15316. }
  15317. }
  15318. return null;
  15319. };
  15320. /**
  15321. * Returns the world matrix of the node
  15322. * @returns a matrix containing the node's world matrix
  15323. */
  15324. Node.prototype.getWorldMatrix = function () {
  15325. return BABYLON.Matrix.Identity();
  15326. };
  15327. // override it in derived class if you add new variables to the cache
  15328. // and call the parent class method
  15329. /** @ignore */
  15330. Node.prototype._initCache = function () {
  15331. this._cache = {};
  15332. this._cache.parent = undefined;
  15333. };
  15334. /** @ignore */
  15335. Node.prototype.updateCache = function (force) {
  15336. if (!force && this.isSynchronized())
  15337. return;
  15338. this._cache.parent = this.parent;
  15339. this._updateCache();
  15340. };
  15341. // override it in derived class if you add new variables to the cache
  15342. // and call the parent class method if !ignoreParentClass
  15343. /** @ignore */
  15344. Node.prototype._updateCache = function (ignoreParentClass) {
  15345. };
  15346. // override it in derived class if you add new variables to the cache
  15347. /** @ignore */
  15348. Node.prototype._isSynchronized = function () {
  15349. return true;
  15350. };
  15351. /** @ignore */
  15352. Node.prototype._markSyncedWithParent = function () {
  15353. if (this.parent) {
  15354. this._parentRenderId = this.parent._currentRenderId;
  15355. }
  15356. };
  15357. /** @ignore */
  15358. Node.prototype.isSynchronizedWithParent = function () {
  15359. if (!this.parent) {
  15360. return true;
  15361. }
  15362. if (this._parentRenderId !== this.parent._currentRenderId) {
  15363. return false;
  15364. }
  15365. return this.parent.isSynchronized();
  15366. };
  15367. /** @ignore */
  15368. Node.prototype.isSynchronized = function (updateCache) {
  15369. var check = this.hasNewParent();
  15370. check = check || !this.isSynchronizedWithParent();
  15371. check = check || !this._isSynchronized();
  15372. if (updateCache)
  15373. this.updateCache(true);
  15374. return !check;
  15375. };
  15376. /** @ignore */
  15377. Node.prototype.hasNewParent = function (update) {
  15378. if (this._cache.parent === this.parent)
  15379. return false;
  15380. if (update)
  15381. this._cache.parent = this.parent;
  15382. return true;
  15383. };
  15384. /**
  15385. * Is this node ready to be used/rendered
  15386. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15387. * @return true if the node is ready
  15388. */
  15389. Node.prototype.isReady = function (completeCheck) {
  15390. if (completeCheck === void 0) { completeCheck = false; }
  15391. return this._isReady;
  15392. };
  15393. /**
  15394. * Is this node enabled?
  15395. * 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
  15396. * @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
  15397. * @return whether this node (and its parent) is enabled
  15398. * @see setEnabled
  15399. */
  15400. Node.prototype.isEnabled = function (checkAncestors) {
  15401. if (checkAncestors === void 0) { checkAncestors = true; }
  15402. if (checkAncestors === false) {
  15403. return this._isEnabled;
  15404. }
  15405. if (this._isEnabled === false) {
  15406. return false;
  15407. }
  15408. if (this.parent !== undefined && this.parent !== null) {
  15409. return this.parent.isEnabled(checkAncestors);
  15410. }
  15411. return true;
  15412. };
  15413. /**
  15414. * Set the enabled state of this node
  15415. * @param value defines the new enabled state
  15416. * @see isEnabled
  15417. */
  15418. Node.prototype.setEnabled = function (value) {
  15419. this._isEnabled = value;
  15420. };
  15421. /**
  15422. * Is this node a descendant of the given node?
  15423. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15424. * @param ancestor defines the parent node to inspect
  15425. * @see parent
  15426. * @returns a boolean indicating if this node is a descendant of the given node
  15427. */
  15428. Node.prototype.isDescendantOf = function (ancestor) {
  15429. if (this.parent) {
  15430. if (this.parent === ancestor) {
  15431. return true;
  15432. }
  15433. return this.parent.isDescendantOf(ancestor);
  15434. }
  15435. return false;
  15436. };
  15437. /** @ignore */
  15438. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15439. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15440. if (!this._children) {
  15441. return;
  15442. }
  15443. for (var index = 0; index < this._children.length; index++) {
  15444. var item = this._children[index];
  15445. if (!predicate || predicate(item)) {
  15446. results.push(item);
  15447. }
  15448. if (!directDescendantsOnly) {
  15449. item._getDescendants(results, false, predicate);
  15450. }
  15451. }
  15452. };
  15453. /**
  15454. * Will return all nodes that have this node as ascendant
  15455. * @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
  15456. * @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
  15457. * @return all children nodes of all types
  15458. */
  15459. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15460. var results = new Array();
  15461. this._getDescendants(results, directDescendantsOnly, predicate);
  15462. return results;
  15463. };
  15464. /**
  15465. * Get all child-meshes of this node
  15466. * @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
  15467. * @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
  15468. * @returns an array of {BABYLON.AbstractMesh}
  15469. */
  15470. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15471. var results = [];
  15472. this._getDescendants(results, directDescendantsOnly, function (node) {
  15473. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15474. });
  15475. return results;
  15476. };
  15477. /**
  15478. * Get all child-transformNodes of this node
  15479. * @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
  15480. * @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
  15481. * @returns an array of {BABYLON.TransformNode}
  15482. */
  15483. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15484. var results = [];
  15485. this._getDescendants(results, directDescendantsOnly, function (node) {
  15486. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15487. });
  15488. return results;
  15489. };
  15490. /**
  15491. * Get all direct children of this node
  15492. * @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
  15493. * @returns an array of {BABYLON.Node}
  15494. */
  15495. Node.prototype.getChildren = function (predicate) {
  15496. return this.getDescendants(true, predicate);
  15497. };
  15498. /** @ignore */
  15499. Node.prototype._setReady = function (state) {
  15500. if (state === this._isReady) {
  15501. return;
  15502. }
  15503. if (!state) {
  15504. this._isReady = false;
  15505. return;
  15506. }
  15507. this._isReady = true;
  15508. if (this.onReady) {
  15509. this.onReady(this);
  15510. }
  15511. };
  15512. /**
  15513. * Get an animation by name
  15514. * @param name defines the name of the animation to look for
  15515. * @returns null if not found else the requested animation
  15516. */
  15517. Node.prototype.getAnimationByName = function (name) {
  15518. for (var i = 0; i < this.animations.length; i++) {
  15519. var animation = this.animations[i];
  15520. if (animation.name === name) {
  15521. return animation;
  15522. }
  15523. }
  15524. return null;
  15525. };
  15526. /**
  15527. * Creates an animation range for this node
  15528. * @param name defines the name of the range
  15529. * @param from defines the starting key
  15530. * @param to defines the end key
  15531. */
  15532. Node.prototype.createAnimationRange = function (name, from, to) {
  15533. // check name not already in use
  15534. if (!this._ranges[name]) {
  15535. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15536. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15537. if (this.animations[i]) {
  15538. this.animations[i].createRange(name, from, to);
  15539. }
  15540. }
  15541. }
  15542. };
  15543. /**
  15544. * Delete a specific animation range
  15545. * @param name defines the name of the range to delete
  15546. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15547. */
  15548. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15549. if (deleteFrames === void 0) { deleteFrames = true; }
  15550. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15551. if (this.animations[i]) {
  15552. this.animations[i].deleteRange(name, deleteFrames);
  15553. }
  15554. }
  15555. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15556. };
  15557. /**
  15558. * Get an animation range by name
  15559. * @param name defines the name of the animation range to look for
  15560. * @returns null if not found else the requested animation range
  15561. */
  15562. Node.prototype.getAnimationRange = function (name) {
  15563. return this._ranges[name];
  15564. };
  15565. /**
  15566. * Will start the animation sequence
  15567. * @param name defines the range frames for animation sequence
  15568. * @param loop defines if the animation should loop (false by default)
  15569. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15570. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15571. * @returns the object created for this animation. If range does not exist, it will return null
  15572. */
  15573. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15574. var range = this.getAnimationRange(name);
  15575. if (!range) {
  15576. return null;
  15577. }
  15578. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15579. };
  15580. /**
  15581. * Serialize animation ranges into a JSON compatible object
  15582. * @returns serialization object
  15583. */
  15584. Node.prototype.serializeAnimationRanges = function () {
  15585. var serializationRanges = [];
  15586. for (var name in this._ranges) {
  15587. var localRange = this._ranges[name];
  15588. if (!localRange) {
  15589. continue;
  15590. }
  15591. var range = {};
  15592. range.name = name;
  15593. range.from = localRange.from;
  15594. range.to = localRange.to;
  15595. serializationRanges.push(range);
  15596. }
  15597. return serializationRanges;
  15598. };
  15599. /**
  15600. * Computes the world matrix of the node
  15601. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15602. * @returns the world matrix
  15603. */
  15604. Node.prototype.computeWorldMatrix = function (force) {
  15605. return BABYLON.Matrix.Identity();
  15606. };
  15607. /**
  15608. * Releases all associated resources
  15609. */
  15610. Node.prototype.dispose = function () {
  15611. this.parent = null;
  15612. // Callback
  15613. this.onDisposeObservable.notifyObservers(this);
  15614. this.onDisposeObservable.clear();
  15615. // Behaviors
  15616. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15617. var behavior = _a[_i];
  15618. behavior.detach();
  15619. }
  15620. this._behaviors = [];
  15621. this._isDisposed = true;
  15622. };
  15623. /**
  15624. * Parse animation range data from a serialization object and store them into a given node
  15625. * @param node defines where to store the animation ranges
  15626. * @param parsedNode defines the serialization object to read data from
  15627. * @param scene defines the hosting scene
  15628. */
  15629. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15630. if (parsedNode.ranges) {
  15631. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15632. var data = parsedNode.ranges[index];
  15633. node.createAnimationRange(data.name, data.from, data.to);
  15634. }
  15635. }
  15636. };
  15637. __decorate([
  15638. BABYLON.serialize()
  15639. ], Node.prototype, "name", void 0);
  15640. __decorate([
  15641. BABYLON.serialize()
  15642. ], Node.prototype, "id", void 0);
  15643. __decorate([
  15644. BABYLON.serialize()
  15645. ], Node.prototype, "uniqueId", void 0);
  15646. __decorate([
  15647. BABYLON.serialize()
  15648. ], Node.prototype, "state", void 0);
  15649. __decorate([
  15650. BABYLON.serialize()
  15651. ], Node.prototype, "metadata", void 0);
  15652. return Node;
  15653. }());
  15654. BABYLON.Node = Node;
  15655. })(BABYLON || (BABYLON = {}));
  15656. //# sourceMappingURL=babylon.node.js.map
  15657. var BABYLON;
  15658. (function (BABYLON) {
  15659. var BoundingSphere = /** @class */ (function () {
  15660. function BoundingSphere(minimum, maximum) {
  15661. this.minimum = minimum;
  15662. this.maximum = maximum;
  15663. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15664. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15665. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15666. this.radius = distance * 0.5;
  15667. this.centerWorld = BABYLON.Vector3.Zero();
  15668. this._update(BABYLON.Matrix.Identity());
  15669. }
  15670. // Methods
  15671. BoundingSphere.prototype._update = function (world) {
  15672. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15673. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15674. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15675. };
  15676. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15677. for (var i = 0; i < 6; i++) {
  15678. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15679. return false;
  15680. }
  15681. return true;
  15682. };
  15683. BoundingSphere.prototype.intersectsPoint = function (point) {
  15684. var x = this.centerWorld.x - point.x;
  15685. var y = this.centerWorld.y - point.y;
  15686. var z = this.centerWorld.z - point.z;
  15687. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15688. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15689. return false;
  15690. return true;
  15691. };
  15692. // Statics
  15693. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15694. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15695. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15696. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15697. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15698. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15699. return false;
  15700. return true;
  15701. };
  15702. return BoundingSphere;
  15703. }());
  15704. BABYLON.BoundingSphere = BoundingSphere;
  15705. })(BABYLON || (BABYLON = {}));
  15706. //# sourceMappingURL=babylon.boundingSphere.js.map
  15707. var BABYLON;
  15708. (function (BABYLON) {
  15709. var BoundingBox = /** @class */ (function () {
  15710. function BoundingBox(minimum, maximum) {
  15711. this.minimum = minimum;
  15712. this.maximum = maximum;
  15713. this.vectors = new Array();
  15714. this.vectorsWorld = new Array();
  15715. // Bounding vectors
  15716. this.vectors.push(this.minimum.clone());
  15717. this.vectors.push(this.maximum.clone());
  15718. this.vectors.push(this.minimum.clone());
  15719. this.vectors[2].x = this.maximum.x;
  15720. this.vectors.push(this.minimum.clone());
  15721. this.vectors[3].y = this.maximum.y;
  15722. this.vectors.push(this.minimum.clone());
  15723. this.vectors[4].z = this.maximum.z;
  15724. this.vectors.push(this.maximum.clone());
  15725. this.vectors[5].z = this.minimum.z;
  15726. this.vectors.push(this.maximum.clone());
  15727. this.vectors[6].x = this.minimum.x;
  15728. this.vectors.push(this.maximum.clone());
  15729. this.vectors[7].y = this.minimum.y;
  15730. // OBB
  15731. this.center = this.maximum.add(this.minimum).scale(0.5);
  15732. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15733. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15734. // World
  15735. for (var index = 0; index < this.vectors.length; index++) {
  15736. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15737. }
  15738. this.minimumWorld = BABYLON.Vector3.Zero();
  15739. this.maximumWorld = BABYLON.Vector3.Zero();
  15740. this.centerWorld = BABYLON.Vector3.Zero();
  15741. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15742. this._update(BABYLON.Matrix.Identity());
  15743. }
  15744. // Methods
  15745. BoundingBox.prototype.getWorldMatrix = function () {
  15746. return this._worldMatrix;
  15747. };
  15748. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15749. this._worldMatrix.copyFrom(matrix);
  15750. return this;
  15751. };
  15752. BoundingBox.prototype._update = function (world) {
  15753. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15754. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15755. for (var index = 0; index < this.vectors.length; index++) {
  15756. var v = this.vectorsWorld[index];
  15757. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15758. if (v.x < this.minimumWorld.x)
  15759. this.minimumWorld.x = v.x;
  15760. if (v.y < this.minimumWorld.y)
  15761. this.minimumWorld.y = v.y;
  15762. if (v.z < this.minimumWorld.z)
  15763. this.minimumWorld.z = v.z;
  15764. if (v.x > this.maximumWorld.x)
  15765. this.maximumWorld.x = v.x;
  15766. if (v.y > this.maximumWorld.y)
  15767. this.maximumWorld.y = v.y;
  15768. if (v.z > this.maximumWorld.z)
  15769. this.maximumWorld.z = v.z;
  15770. }
  15771. // Extend
  15772. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15773. this.extendSizeWorld.scaleInPlace(0.5);
  15774. // OBB
  15775. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15776. this.centerWorld.scaleInPlace(0.5);
  15777. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15778. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15779. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15780. this._worldMatrix = world;
  15781. };
  15782. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15783. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15784. };
  15785. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15786. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15787. };
  15788. BoundingBox.prototype.intersectsPoint = function (point) {
  15789. var delta = -BABYLON.Epsilon;
  15790. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15791. return false;
  15792. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15793. return false;
  15794. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15795. return false;
  15796. return true;
  15797. };
  15798. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15799. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15800. };
  15801. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15802. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15803. return false;
  15804. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15805. return false;
  15806. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15807. return false;
  15808. return true;
  15809. };
  15810. // Statics
  15811. BoundingBox.Intersects = function (box0, box1) {
  15812. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15813. return false;
  15814. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15815. return false;
  15816. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15817. return false;
  15818. return true;
  15819. };
  15820. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15821. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15822. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15823. return (num <= (sphereRadius * sphereRadius));
  15824. };
  15825. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15826. for (var p = 0; p < 6; p++) {
  15827. for (var i = 0; i < 8; i++) {
  15828. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15829. return false;
  15830. }
  15831. }
  15832. }
  15833. return true;
  15834. };
  15835. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15836. for (var p = 0; p < 6; p++) {
  15837. var inCount = 8;
  15838. for (var i = 0; i < 8; i++) {
  15839. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15840. --inCount;
  15841. }
  15842. else {
  15843. break;
  15844. }
  15845. }
  15846. if (inCount === 0)
  15847. return false;
  15848. }
  15849. return true;
  15850. };
  15851. return BoundingBox;
  15852. }());
  15853. BABYLON.BoundingBox = BoundingBox;
  15854. })(BABYLON || (BABYLON = {}));
  15855. //# sourceMappingURL=babylon.boundingBox.js.map
  15856. var BABYLON;
  15857. (function (BABYLON) {
  15858. var computeBoxExtents = function (axis, box) {
  15859. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15860. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15861. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15862. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15863. var r = r0 + r1 + r2;
  15864. return {
  15865. min: p - r,
  15866. max: p + r
  15867. };
  15868. };
  15869. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15870. var axisOverlap = function (axis, box0, box1) {
  15871. var result0 = computeBoxExtents(axis, box0);
  15872. var result1 = computeBoxExtents(axis, box1);
  15873. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15874. };
  15875. var BoundingInfo = /** @class */ (function () {
  15876. function BoundingInfo(minimum, maximum) {
  15877. this.minimum = minimum;
  15878. this.maximum = maximum;
  15879. this._isLocked = false;
  15880. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15881. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15882. }
  15883. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15884. get: function () {
  15885. return this._isLocked;
  15886. },
  15887. set: function (value) {
  15888. this._isLocked = value;
  15889. },
  15890. enumerable: true,
  15891. configurable: true
  15892. });
  15893. // Methods
  15894. BoundingInfo.prototype.update = function (world) {
  15895. if (this._isLocked) {
  15896. return;
  15897. }
  15898. this.boundingBox._update(world);
  15899. this.boundingSphere._update(world);
  15900. };
  15901. /**
  15902. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15903. * @param center New center of the bounding info
  15904. * @param extend New extend of the bounding info
  15905. */
  15906. BoundingInfo.prototype.centerOn = function (center, extend) {
  15907. this.minimum = center.subtract(extend);
  15908. this.maximum = center.add(extend);
  15909. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15910. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15911. return this;
  15912. };
  15913. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15914. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15915. return false;
  15916. return this.boundingBox.isInFrustum(frustumPlanes);
  15917. };
  15918. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15919. /**
  15920. * Gets the world distance between the min and max points of the bounding box
  15921. */
  15922. get: function () {
  15923. var boundingBox = this.boundingBox;
  15924. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15925. return size.length();
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15931. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15932. };
  15933. BoundingInfo.prototype._checkCollision = function (collider) {
  15934. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15935. };
  15936. BoundingInfo.prototype.intersectsPoint = function (point) {
  15937. if (!this.boundingSphere.centerWorld) {
  15938. return false;
  15939. }
  15940. if (!this.boundingSphere.intersectsPoint(point)) {
  15941. return false;
  15942. }
  15943. if (!this.boundingBox.intersectsPoint(point)) {
  15944. return false;
  15945. }
  15946. return true;
  15947. };
  15948. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15949. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15950. return false;
  15951. }
  15952. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15953. return false;
  15954. }
  15955. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15956. return false;
  15957. }
  15958. if (!precise) {
  15959. return true;
  15960. }
  15961. var box0 = this.boundingBox;
  15962. var box1 = boundingInfo.boundingBox;
  15963. if (!axisOverlap(box0.directions[0], box0, box1))
  15964. return false;
  15965. if (!axisOverlap(box0.directions[1], box0, box1))
  15966. return false;
  15967. if (!axisOverlap(box0.directions[2], box0, box1))
  15968. return false;
  15969. if (!axisOverlap(box1.directions[0], box0, box1))
  15970. return false;
  15971. if (!axisOverlap(box1.directions[1], box0, box1))
  15972. return false;
  15973. if (!axisOverlap(box1.directions[2], box0, box1))
  15974. return false;
  15975. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15976. return false;
  15977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15978. return false;
  15979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15980. return false;
  15981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15982. return false;
  15983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15984. return false;
  15985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15986. return false;
  15987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15988. return false;
  15989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15990. return false;
  15991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15992. return false;
  15993. return true;
  15994. };
  15995. return BoundingInfo;
  15996. }());
  15997. BABYLON.BoundingInfo = BoundingInfo;
  15998. })(BABYLON || (BABYLON = {}));
  15999. //# sourceMappingURL=babylon.boundingInfo.js.map
  16000. var BABYLON;
  16001. (function (BABYLON) {
  16002. var TransformNode = /** @class */ (function (_super) {
  16003. __extends(TransformNode, _super);
  16004. function TransformNode(name, scene, isPure) {
  16005. if (scene === void 0) { scene = null; }
  16006. if (isPure === void 0) { isPure = true; }
  16007. var _this = _super.call(this, name, scene) || this;
  16008. // Properties
  16009. _this._rotation = BABYLON.Vector3.Zero();
  16010. _this._scaling = BABYLON.Vector3.One();
  16011. _this._isDirty = false;
  16012. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16013. _this.scalingDeterminant = 1;
  16014. _this.infiniteDistance = false;
  16015. _this.position = BABYLON.Vector3.Zero();
  16016. _this._localWorld = BABYLON.Matrix.Zero();
  16017. _this._worldMatrix = BABYLON.Matrix.Zero();
  16018. _this._worldMatrixDeterminant = 0;
  16019. _this._absolutePosition = BABYLON.Vector3.Zero();
  16020. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16021. _this._postMultiplyPivotMatrix = false;
  16022. _this._isWorldMatrixFrozen = false;
  16023. /**
  16024. * An event triggered after the world matrix is updated
  16025. * @type {BABYLON.Observable}
  16026. */
  16027. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16028. _this._nonUniformScaling = false;
  16029. if (isPure) {
  16030. _this.getScene().addTransformNode(_this);
  16031. }
  16032. return _this;
  16033. }
  16034. Object.defineProperty(TransformNode.prototype, "rotation", {
  16035. /**
  16036. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16037. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16038. * Default : (0.0, 0.0, 0.0)
  16039. */
  16040. get: function () {
  16041. return this._rotation;
  16042. },
  16043. set: function (newRotation) {
  16044. this._rotation = newRotation;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. Object.defineProperty(TransformNode.prototype, "scaling", {
  16050. /**
  16051. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16052. * Default : (1.0, 1.0, 1.0)
  16053. */
  16054. get: function () {
  16055. return this._scaling;
  16056. },
  16057. /**
  16058. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16059. * Default : (1.0, 1.0, 1.0)
  16060. */
  16061. set: function (newScaling) {
  16062. this._scaling = newScaling;
  16063. },
  16064. enumerable: true,
  16065. configurable: true
  16066. });
  16067. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16068. /**
  16069. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16070. * It's null by default.
  16071. * 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)
  16072. */
  16073. get: function () {
  16074. return this._rotationQuaternion;
  16075. },
  16076. set: function (quaternion) {
  16077. this._rotationQuaternion = quaternion;
  16078. //reset the rotation vector.
  16079. if (quaternion && this.rotation.length()) {
  16080. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16081. }
  16082. },
  16083. enumerable: true,
  16084. configurable: true
  16085. });
  16086. /**
  16087. * Returns the latest update of the World matrix
  16088. * Returns a Matrix.
  16089. */
  16090. TransformNode.prototype.getWorldMatrix = function () {
  16091. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16092. this.computeWorldMatrix();
  16093. }
  16094. return this._worldMatrix;
  16095. };
  16096. /**
  16097. * Returns the latest update of the World matrix determinant.
  16098. */
  16099. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16100. return this._worldMatrixDeterminant;
  16101. };
  16102. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16103. /**
  16104. * Returns directly the latest state of the mesh World matrix.
  16105. * A Matrix is returned.
  16106. */
  16107. get: function () {
  16108. return this._worldMatrix;
  16109. },
  16110. enumerable: true,
  16111. configurable: true
  16112. });
  16113. /**
  16114. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16115. * Returns the AbstractMesh.
  16116. */
  16117. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16118. this._poseMatrix.copyFrom(matrix);
  16119. return this;
  16120. };
  16121. /**
  16122. * Returns the mesh Pose matrix.
  16123. * Returned object : Matrix
  16124. */
  16125. TransformNode.prototype.getPoseMatrix = function () {
  16126. return this._poseMatrix;
  16127. };
  16128. TransformNode.prototype._isSynchronized = function () {
  16129. if (this._isDirty) {
  16130. return false;
  16131. }
  16132. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16133. return false;
  16134. if (this._cache.pivotMatrixUpdated) {
  16135. return false;
  16136. }
  16137. if (this.infiniteDistance) {
  16138. return false;
  16139. }
  16140. if (!this._cache.position.equals(this.position))
  16141. return false;
  16142. if (this.rotationQuaternion) {
  16143. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16144. return false;
  16145. }
  16146. if (!this._cache.rotation.equals(this.rotation))
  16147. return false;
  16148. if (!this._cache.scaling.equals(this.scaling))
  16149. return false;
  16150. return true;
  16151. };
  16152. TransformNode.prototype._initCache = function () {
  16153. _super.prototype._initCache.call(this);
  16154. this._cache.localMatrixUpdated = false;
  16155. this._cache.position = BABYLON.Vector3.Zero();
  16156. this._cache.scaling = BABYLON.Vector3.Zero();
  16157. this._cache.rotation = BABYLON.Vector3.Zero();
  16158. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16159. this._cache.billboardMode = -1;
  16160. };
  16161. TransformNode.prototype.markAsDirty = function (property) {
  16162. if (property === "rotation") {
  16163. this.rotationQuaternion = null;
  16164. }
  16165. this._currentRenderId = Number.MAX_VALUE;
  16166. this._isDirty = true;
  16167. return this;
  16168. };
  16169. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16170. /**
  16171. * Returns the current mesh absolute position.
  16172. * Retuns a Vector3.
  16173. */
  16174. get: function () {
  16175. return this._absolutePosition;
  16176. },
  16177. enumerable: true,
  16178. configurable: true
  16179. });
  16180. /**
  16181. * Sets a new matrix to apply before all other transformation
  16182. * @param matrix defines the transform matrix
  16183. * @returns the current TransformNode
  16184. */
  16185. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16186. return this.setPivotMatrix(matrix, false);
  16187. };
  16188. /**
  16189. * Sets a new pivot matrix to the current node
  16190. * @param matrix defines the new pivot matrix to use
  16191. * @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
  16192. * @returns the current TransformNode
  16193. */
  16194. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16195. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16196. this._pivotMatrix = matrix.clone();
  16197. this._cache.pivotMatrixUpdated = true;
  16198. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16199. if (this._postMultiplyPivotMatrix) {
  16200. if (!this._pivotMatrixInverse) {
  16201. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16202. }
  16203. else {
  16204. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16205. }
  16206. }
  16207. return this;
  16208. };
  16209. /**
  16210. * Returns the mesh pivot matrix.
  16211. * Default : Identity.
  16212. * A Matrix is returned.
  16213. */
  16214. TransformNode.prototype.getPivotMatrix = function () {
  16215. return this._pivotMatrix;
  16216. };
  16217. /**
  16218. * Prevents the World matrix to be computed any longer.
  16219. * Returns the AbstractMesh.
  16220. */
  16221. TransformNode.prototype.freezeWorldMatrix = function () {
  16222. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16223. this.computeWorldMatrix(true);
  16224. this._isWorldMatrixFrozen = true;
  16225. return this;
  16226. };
  16227. /**
  16228. * Allows back the World matrix computation.
  16229. * Returns the AbstractMesh.
  16230. */
  16231. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16232. this._isWorldMatrixFrozen = false;
  16233. this.computeWorldMatrix(true);
  16234. return this;
  16235. };
  16236. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16237. /**
  16238. * True if the World matrix has been frozen.
  16239. * Returns a boolean.
  16240. */
  16241. get: function () {
  16242. return this._isWorldMatrixFrozen;
  16243. },
  16244. enumerable: true,
  16245. configurable: true
  16246. });
  16247. /**
  16248. * Retuns the mesh absolute position in the World.
  16249. * Returns a Vector3.
  16250. */
  16251. TransformNode.prototype.getAbsolutePosition = function () {
  16252. this.computeWorldMatrix();
  16253. return this._absolutePosition;
  16254. };
  16255. /**
  16256. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16257. * Returns the AbstractMesh.
  16258. */
  16259. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16260. if (!absolutePosition) {
  16261. return this;
  16262. }
  16263. var absolutePositionX;
  16264. var absolutePositionY;
  16265. var absolutePositionZ;
  16266. if (absolutePosition.x === undefined) {
  16267. if (arguments.length < 3) {
  16268. return this;
  16269. }
  16270. absolutePositionX = arguments[0];
  16271. absolutePositionY = arguments[1];
  16272. absolutePositionZ = arguments[2];
  16273. }
  16274. else {
  16275. absolutePositionX = absolutePosition.x;
  16276. absolutePositionY = absolutePosition.y;
  16277. absolutePositionZ = absolutePosition.z;
  16278. }
  16279. if (this.parent) {
  16280. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16281. invertParentWorldMatrix.invert();
  16282. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16283. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16284. }
  16285. else {
  16286. this.position.x = absolutePositionX;
  16287. this.position.y = absolutePositionY;
  16288. this.position.z = absolutePositionZ;
  16289. }
  16290. return this;
  16291. };
  16292. /**
  16293. * Sets the mesh position in its local space.
  16294. * Returns the AbstractMesh.
  16295. */
  16296. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16297. this.computeWorldMatrix();
  16298. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16299. return this;
  16300. };
  16301. /**
  16302. * Returns the mesh position in the local space from the current World matrix values.
  16303. * Returns a new Vector3.
  16304. */
  16305. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16306. this.computeWorldMatrix();
  16307. var invLocalWorldMatrix = this._localWorld.clone();
  16308. invLocalWorldMatrix.invert();
  16309. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16310. };
  16311. /**
  16312. * Translates the mesh along the passed Vector3 in its local space.
  16313. * Returns the AbstractMesh.
  16314. */
  16315. TransformNode.prototype.locallyTranslate = function (vector3) {
  16316. this.computeWorldMatrix(true);
  16317. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16318. return this;
  16319. };
  16320. /**
  16321. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16322. * @param targetPoint the position (must be in same space as current mesh) to look at
  16323. * @param yawCor optional yaw (y-axis) correction in radians
  16324. * @param pitchCor optional pitch (x-axis) correction in radians
  16325. * @param rollCor optional roll (z-axis) correction in radians
  16326. * @param space the choosen space of the target
  16327. * @returns the TransformNode.
  16328. */
  16329. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16330. if (yawCor === void 0) { yawCor = 0; }
  16331. if (pitchCor === void 0) { pitchCor = 0; }
  16332. if (rollCor === void 0) { rollCor = 0; }
  16333. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16334. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16335. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16336. targetPoint.subtractToRef(pos, dv);
  16337. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16338. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16339. var pitch = Math.atan2(dv.y, len);
  16340. if (this.rotationQuaternion) {
  16341. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16342. }
  16343. else {
  16344. this.rotation.x = pitch + pitchCor;
  16345. this.rotation.y = yaw + yawCor;
  16346. this.rotation.z = rollCor;
  16347. }
  16348. return this;
  16349. };
  16350. /**
  16351. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16352. * This Vector3 is expressed in the World space.
  16353. */
  16354. TransformNode.prototype.getDirection = function (localAxis) {
  16355. var result = BABYLON.Vector3.Zero();
  16356. this.getDirectionToRef(localAxis, result);
  16357. return result;
  16358. };
  16359. /**
  16360. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16361. * localAxis is expressed in the mesh local space.
  16362. * result is computed in the Wordl space from the mesh World matrix.
  16363. * Returns the AbstractMesh.
  16364. */
  16365. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16366. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16367. return this;
  16368. };
  16369. /**
  16370. * Sets a new pivot point to the current node
  16371. * @param point defines the new pivot point to use
  16372. * @param space defines if the point is in world or local space (local by default)
  16373. * @returns the current TransformNode
  16374. */
  16375. TransformNode.prototype.setPivotPoint = function (point, space) {
  16376. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16377. if (this.getScene().getRenderId() == 0) {
  16378. this.computeWorldMatrix(true);
  16379. }
  16380. var wm = this.getWorldMatrix();
  16381. if (space == BABYLON.Space.WORLD) {
  16382. var tmat = BABYLON.Tmp.Matrix[0];
  16383. wm.invertToRef(tmat);
  16384. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16385. }
  16386. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16387. };
  16388. /**
  16389. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16390. */
  16391. TransformNode.prototype.getPivotPoint = function () {
  16392. var point = BABYLON.Vector3.Zero();
  16393. this.getPivotPointToRef(point);
  16394. return point;
  16395. };
  16396. /**
  16397. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16398. * Returns the AbstractMesh.
  16399. */
  16400. TransformNode.prototype.getPivotPointToRef = function (result) {
  16401. result.x = -this._pivotMatrix.m[12];
  16402. result.y = -this._pivotMatrix.m[13];
  16403. result.z = -this._pivotMatrix.m[14];
  16404. return this;
  16405. };
  16406. /**
  16407. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16408. */
  16409. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16410. var point = BABYLON.Vector3.Zero();
  16411. this.getAbsolutePivotPointToRef(point);
  16412. return point;
  16413. };
  16414. /**
  16415. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16416. * Returns the AbstractMesh.
  16417. */
  16418. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16419. result.x = this._pivotMatrix.m[12];
  16420. result.y = this._pivotMatrix.m[13];
  16421. result.z = this._pivotMatrix.m[14];
  16422. this.getPivotPointToRef(result);
  16423. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16424. return this;
  16425. };
  16426. /**
  16427. * Defines the passed node as the parent of the current node.
  16428. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16429. * Returns the TransformNode.
  16430. */
  16431. TransformNode.prototype.setParent = function (node) {
  16432. if (node === null) {
  16433. var rotation = BABYLON.Tmp.Quaternion[0];
  16434. var position = BABYLON.Tmp.Vector3[0];
  16435. var scale = BABYLON.Tmp.Vector3[1];
  16436. if (this.parent && this.parent.computeWorldMatrix) {
  16437. this.parent.computeWorldMatrix(true);
  16438. }
  16439. this.computeWorldMatrix(true);
  16440. this.getWorldMatrix().decompose(scale, rotation, position);
  16441. if (this.rotationQuaternion) {
  16442. this.rotationQuaternion.copyFrom(rotation);
  16443. }
  16444. else {
  16445. rotation.toEulerAnglesToRef(this.rotation);
  16446. }
  16447. this.scaling.x = scale.x;
  16448. this.scaling.y = scale.y;
  16449. this.scaling.z = scale.z;
  16450. this.position.x = position.x;
  16451. this.position.y = position.y;
  16452. this.position.z = position.z;
  16453. }
  16454. else {
  16455. var rotation = BABYLON.Tmp.Quaternion[0];
  16456. var position = BABYLON.Tmp.Vector3[0];
  16457. var scale = BABYLON.Tmp.Vector3[1];
  16458. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16459. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16460. this.computeWorldMatrix(true);
  16461. node.computeWorldMatrix(true);
  16462. node.getWorldMatrix().invertToRef(invParentMatrix);
  16463. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16464. diffMatrix.decompose(scale, rotation, position);
  16465. if (this.rotationQuaternion) {
  16466. this.rotationQuaternion.copyFrom(rotation);
  16467. }
  16468. else {
  16469. rotation.toEulerAnglesToRef(this.rotation);
  16470. }
  16471. this.position.x = position.x;
  16472. this.position.y = position.y;
  16473. this.position.z = position.z;
  16474. this.scaling.x = scale.x;
  16475. this.scaling.y = scale.y;
  16476. this.scaling.z = scale.z;
  16477. }
  16478. this.parent = node;
  16479. return this;
  16480. };
  16481. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16482. get: function () {
  16483. return this._nonUniformScaling;
  16484. },
  16485. enumerable: true,
  16486. configurable: true
  16487. });
  16488. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16489. if (this._nonUniformScaling === value) {
  16490. return false;
  16491. }
  16492. this._nonUniformScaling = true;
  16493. return true;
  16494. };
  16495. /**
  16496. * Attach the current TransformNode to another TransformNode associated with a bone
  16497. * @param bone Bone affecting the TransformNode
  16498. * @param affectedTransformNode TransformNode associated with the bone
  16499. */
  16500. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16501. this._transformToBoneReferal = affectedTransformNode;
  16502. this.parent = bone;
  16503. if (bone.getWorldMatrix().determinant() < 0) {
  16504. this.scalingDeterminant *= -1;
  16505. }
  16506. return this;
  16507. };
  16508. TransformNode.prototype.detachFromBone = function () {
  16509. if (!this.parent) {
  16510. return this;
  16511. }
  16512. if (this.parent.getWorldMatrix().determinant() < 0) {
  16513. this.scalingDeterminant *= -1;
  16514. }
  16515. this._transformToBoneReferal = null;
  16516. this.parent = null;
  16517. return this;
  16518. };
  16519. /**
  16520. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16521. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16522. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16523. * The passed axis is also normalized.
  16524. * Returns the AbstractMesh.
  16525. */
  16526. TransformNode.prototype.rotate = function (axis, amount, space) {
  16527. axis.normalize();
  16528. if (!this.rotationQuaternion) {
  16529. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16530. this.rotation = BABYLON.Vector3.Zero();
  16531. }
  16532. var rotationQuaternion;
  16533. if (!space || space === BABYLON.Space.LOCAL) {
  16534. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16535. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16536. }
  16537. else {
  16538. if (this.parent) {
  16539. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16540. invertParentWorldMatrix.invert();
  16541. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16542. }
  16543. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16544. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16545. }
  16546. return this;
  16547. };
  16548. /**
  16549. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16550. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16551. * The passed axis is also normalized.
  16552. * Returns the AbstractMesh.
  16553. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16554. */
  16555. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16556. axis.normalize();
  16557. if (!this.rotationQuaternion) {
  16558. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16559. this.rotation.copyFromFloats(0, 0, 0);
  16560. }
  16561. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16562. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16563. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16564. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16565. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16566. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16567. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16568. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16569. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16570. return this;
  16571. };
  16572. /**
  16573. * Translates the mesh along the axis vector for the passed distance in the given space.
  16574. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16575. * Returns the AbstractMesh.
  16576. */
  16577. TransformNode.prototype.translate = function (axis, distance, space) {
  16578. var displacementVector = axis.scale(distance);
  16579. if (!space || space === BABYLON.Space.LOCAL) {
  16580. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16581. this.setPositionWithLocalVector(tempV3);
  16582. }
  16583. else {
  16584. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16585. }
  16586. return this;
  16587. };
  16588. /**
  16589. * Adds a rotation step to the mesh current rotation.
  16590. * x, y, z are Euler angles expressed in radians.
  16591. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16592. * This means this rotation is made in the mesh local space only.
  16593. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16594. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16595. * ```javascript
  16596. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16597. * ```
  16598. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16599. * 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.
  16600. * Returns the AbstractMesh.
  16601. */
  16602. TransformNode.prototype.addRotation = function (x, y, z) {
  16603. var rotationQuaternion;
  16604. if (this.rotationQuaternion) {
  16605. rotationQuaternion = this.rotationQuaternion;
  16606. }
  16607. else {
  16608. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16609. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16610. }
  16611. var accumulation = BABYLON.Tmp.Quaternion[0];
  16612. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16613. rotationQuaternion.multiplyInPlace(accumulation);
  16614. if (!this.rotationQuaternion) {
  16615. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16616. }
  16617. return this;
  16618. };
  16619. /**
  16620. * Computes the mesh World matrix and returns it.
  16621. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16622. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16623. * If the parameter `force`is set to `true`, the actual computation is done.
  16624. * Returns the mesh World Matrix.
  16625. */
  16626. TransformNode.prototype.computeWorldMatrix = function (force) {
  16627. if (this._isWorldMatrixFrozen) {
  16628. return this._worldMatrix;
  16629. }
  16630. if (!force && this.isSynchronized(true)) {
  16631. return this._worldMatrix;
  16632. }
  16633. this._cache.position.copyFrom(this.position);
  16634. this._cache.scaling.copyFrom(this.scaling);
  16635. this._cache.pivotMatrixUpdated = false;
  16636. this._cache.billboardMode = this.billboardMode;
  16637. this._currentRenderId = this.getScene().getRenderId();
  16638. this._isDirty = false;
  16639. // Scaling
  16640. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16641. // Rotation
  16642. //rotate, if quaternion is set and rotation was used
  16643. if (this.rotationQuaternion) {
  16644. var len = this.rotation.length();
  16645. if (len) {
  16646. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16647. this.rotation.copyFromFloats(0, 0, 0);
  16648. }
  16649. }
  16650. if (this.rotationQuaternion) {
  16651. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16652. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16653. }
  16654. else {
  16655. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16656. this._cache.rotation.copyFrom(this.rotation);
  16657. }
  16658. // Translation
  16659. var camera = this.getScene().activeCamera;
  16660. if (this.infiniteDistance && !this.parent && camera) {
  16661. var cameraWorldMatrix = camera.getWorldMatrix();
  16662. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16663. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16664. }
  16665. else {
  16666. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16667. }
  16668. // Composing transformations
  16669. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16670. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16671. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16672. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16673. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16674. // Need to decompose each rotation here
  16675. var currentPosition = BABYLON.Tmp.Vector3[3];
  16676. if (this.parent && this.parent.getWorldMatrix) {
  16677. if (this._transformToBoneReferal) {
  16678. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16679. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16680. }
  16681. else {
  16682. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16683. }
  16684. }
  16685. else {
  16686. currentPosition.copyFrom(this.position);
  16687. }
  16688. currentPosition.subtractInPlace(camera.globalPosition);
  16689. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16690. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16691. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16692. }
  16693. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16694. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16695. }
  16696. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16697. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16698. }
  16699. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16700. }
  16701. else {
  16702. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16703. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16704. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16705. }
  16706. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16707. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16708. }
  16709. // Local world
  16710. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16711. // Parent
  16712. if (this.parent && this.parent.getWorldMatrix) {
  16713. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16714. if (this._transformToBoneReferal) {
  16715. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16716. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16717. }
  16718. else {
  16719. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16720. }
  16721. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16722. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16723. this._worldMatrix.copyFrom(this._localWorld);
  16724. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16725. }
  16726. else {
  16727. if (this._transformToBoneReferal) {
  16728. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16729. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16730. }
  16731. else {
  16732. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16733. }
  16734. }
  16735. this._markSyncedWithParent();
  16736. }
  16737. else {
  16738. this._worldMatrix.copyFrom(this._localWorld);
  16739. }
  16740. // Post multiply inverse of pivotMatrix
  16741. if (this._postMultiplyPivotMatrix) {
  16742. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16743. }
  16744. // Normal matrix
  16745. if (this.scaling.isNonUniform) {
  16746. this._updateNonUniformScalingState(true);
  16747. }
  16748. else if (this.parent && this.parent._nonUniformScaling) {
  16749. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16750. }
  16751. else {
  16752. this._updateNonUniformScalingState(false);
  16753. }
  16754. this._afterComputeWorldMatrix();
  16755. // Absolute position
  16756. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16757. // Callbacks
  16758. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16759. if (!this._poseMatrix) {
  16760. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16761. }
  16762. // Cache the determinant
  16763. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16764. return this._worldMatrix;
  16765. };
  16766. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16767. };
  16768. /**
  16769. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16770. * @param func: callback function to add
  16771. *
  16772. * Returns the TransformNode.
  16773. */
  16774. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16775. this.onAfterWorldMatrixUpdateObservable.add(func);
  16776. return this;
  16777. };
  16778. /**
  16779. * Removes a registered callback function.
  16780. * Returns the TransformNode.
  16781. */
  16782. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16783. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16784. return this;
  16785. };
  16786. /**
  16787. * Clone the current transform node
  16788. * Returns the new transform node
  16789. * @param name Name of the new clone
  16790. * @param newParent New parent for the clone
  16791. * @param doNotCloneChildren Do not clone children hierarchy
  16792. */
  16793. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16794. var _this = this;
  16795. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16796. result.name = name;
  16797. result.id = name;
  16798. if (newParent) {
  16799. result.parent = newParent;
  16800. }
  16801. if (!doNotCloneChildren) {
  16802. // Children
  16803. var directDescendants = this.getDescendants(true);
  16804. for (var index = 0; index < directDescendants.length; index++) {
  16805. var child = directDescendants[index];
  16806. if (child.clone) {
  16807. child.clone(name + "." + child.name, result);
  16808. }
  16809. }
  16810. }
  16811. return result;
  16812. };
  16813. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16814. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16815. serializationObject.type = this.getClassName();
  16816. // Parent
  16817. if (this.parent) {
  16818. serializationObject.parentId = this.parent.id;
  16819. }
  16820. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16821. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16822. }
  16823. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16824. serializationObject.isEnabled = this.isEnabled();
  16825. // Parent
  16826. if (this.parent) {
  16827. serializationObject.parentId = this.parent.id;
  16828. }
  16829. return serializationObject;
  16830. };
  16831. // Statics
  16832. /**
  16833. * Returns a new TransformNode object parsed from the source provided.
  16834. * The parameter `parsedMesh` is the source.
  16835. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16836. */
  16837. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16838. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16839. if (BABYLON.Tags) {
  16840. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16841. }
  16842. if (parsedTransformNode.localMatrix) {
  16843. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16844. }
  16845. else if (parsedTransformNode.pivotMatrix) {
  16846. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16847. }
  16848. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16849. // Parent
  16850. if (parsedTransformNode.parentId) {
  16851. transformNode._waitingParentId = parsedTransformNode.parentId;
  16852. }
  16853. return transformNode;
  16854. };
  16855. /**
  16856. * Disposes the TransformNode.
  16857. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16858. * Returns nothing.
  16859. */
  16860. TransformNode.prototype.dispose = function (doNotRecurse) {
  16861. // Animations
  16862. this.getScene().stopAnimation(this);
  16863. // Remove from scene
  16864. this.getScene().removeTransformNode(this);
  16865. if (!doNotRecurse) {
  16866. // Children
  16867. var objects = this.getDescendants(true);
  16868. for (var index = 0; index < objects.length; index++) {
  16869. objects[index].dispose();
  16870. }
  16871. }
  16872. else {
  16873. var childMeshes = this.getChildMeshes(true);
  16874. for (index = 0; index < childMeshes.length; index++) {
  16875. var child = childMeshes[index];
  16876. child.parent = null;
  16877. child.computeWorldMatrix(true);
  16878. }
  16879. }
  16880. this.onAfterWorldMatrixUpdateObservable.clear();
  16881. _super.prototype.dispose.call(this);
  16882. };
  16883. // Statics
  16884. TransformNode.BILLBOARDMODE_NONE = 0;
  16885. TransformNode.BILLBOARDMODE_X = 1;
  16886. TransformNode.BILLBOARDMODE_Y = 2;
  16887. TransformNode.BILLBOARDMODE_Z = 4;
  16888. TransformNode.BILLBOARDMODE_ALL = 7;
  16889. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16890. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16891. __decorate([
  16892. BABYLON.serializeAsVector3()
  16893. ], TransformNode.prototype, "_rotation", void 0);
  16894. __decorate([
  16895. BABYLON.serializeAsQuaternion()
  16896. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16897. __decorate([
  16898. BABYLON.serializeAsVector3()
  16899. ], TransformNode.prototype, "_scaling", void 0);
  16900. __decorate([
  16901. BABYLON.serialize()
  16902. ], TransformNode.prototype, "billboardMode", void 0);
  16903. __decorate([
  16904. BABYLON.serialize()
  16905. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16906. __decorate([
  16907. BABYLON.serialize()
  16908. ], TransformNode.prototype, "infiniteDistance", void 0);
  16909. __decorate([
  16910. BABYLON.serializeAsVector3()
  16911. ], TransformNode.prototype, "position", void 0);
  16912. return TransformNode;
  16913. }(BABYLON.Node));
  16914. BABYLON.TransformNode = TransformNode;
  16915. })(BABYLON || (BABYLON = {}));
  16916. //# sourceMappingURL=babylon.transformNode.js.map
  16917. var BABYLON;
  16918. (function (BABYLON) {
  16919. var AbstractMesh = /** @class */ (function (_super) {
  16920. __extends(AbstractMesh, _super);
  16921. // Constructor
  16922. function AbstractMesh(name, scene) {
  16923. if (scene === void 0) { scene = null; }
  16924. var _this = _super.call(this, name, scene, false) || this;
  16925. _this._facetNb = 0; // facet number
  16926. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16927. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16928. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16929. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16930. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16931. _this._subDiv = {
  16932. max: 1,
  16933. X: 1,
  16934. Y: 1,
  16935. Z: 1
  16936. };
  16937. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16938. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16939. // Events
  16940. /**
  16941. * An event triggered when this mesh collides with another one
  16942. * @type {BABYLON.Observable}
  16943. */
  16944. _this.onCollideObservable = new BABYLON.Observable();
  16945. /**
  16946. * An event triggered when the collision's position changes
  16947. * @type {BABYLON.Observable}
  16948. */
  16949. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16950. /**
  16951. * An event triggered when material is changed
  16952. * @type {BABYLON.Observable}
  16953. */
  16954. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16955. // Properties
  16956. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16957. /**
  16958. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16959. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16960. * or
  16961. * 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.
  16962. * for more info check WebGl documentations
  16963. */
  16964. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16965. /**
  16966. * 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:
  16967. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16968. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16969. * 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.
  16970. */
  16971. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16972. /**
  16973. * 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.
  16974. * The default value is -1 which means don't break the query and wait till the result.
  16975. */
  16976. _this.occlusionRetryCount = -1;
  16977. _this._occlusionInternalRetryCounter = 0;
  16978. _this._isOccluded = false;
  16979. _this._isOcclusionQueryInProgress = false;
  16980. _this._visibility = 1.0;
  16981. _this.alphaIndex = Number.MAX_VALUE;
  16982. _this.isVisible = true;
  16983. _this.isPickable = true;
  16984. _this.showBoundingBox = false;
  16985. _this.showSubMeshesBoundingBox = false;
  16986. _this.isBlocker = false;
  16987. _this.enablePointerMoveEvents = false;
  16988. _this.renderingGroupId = 0;
  16989. _this._receiveShadows = false;
  16990. _this.renderOutline = false;
  16991. _this.outlineColor = BABYLON.Color3.Red();
  16992. _this.outlineWidth = 0.02;
  16993. _this.renderOverlay = false;
  16994. _this.overlayColor = BABYLON.Color3.Red();
  16995. _this.overlayAlpha = 0.5;
  16996. _this._hasVertexAlpha = false;
  16997. _this._useVertexColors = true;
  16998. _this._computeBonesUsingShaders = true;
  16999. _this._numBoneInfluencers = 4;
  17000. _this._applyFog = true;
  17001. _this.useOctreeForRenderingSelection = true;
  17002. _this.useOctreeForPicking = true;
  17003. _this.useOctreeForCollisions = true;
  17004. _this._layerMask = 0x0FFFFFFF;
  17005. /**
  17006. * True if the mesh must be rendered in any case.
  17007. */
  17008. _this.alwaysSelectAsActiveMesh = false;
  17009. /**
  17010. * This scene's action manager
  17011. * @type {BABYLON.ActionManager}
  17012. */
  17013. _this.actionManager = null;
  17014. // Physics
  17015. _this.physicsImpostor = null;
  17016. // Collisions
  17017. _this._checkCollisions = false;
  17018. _this._collisionMask = -1;
  17019. _this._collisionGroup = -1;
  17020. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17021. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17022. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17023. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17024. // Edges
  17025. _this.edgesWidth = 1;
  17026. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17027. // Cache
  17028. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17029. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17030. _this._renderId = 0;
  17031. _this._intersectionsInProgress = new Array();
  17032. _this._unIndexed = false;
  17033. _this._lightSources = new Array();
  17034. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17035. if (collidedMesh === void 0) { collidedMesh = null; }
  17036. //TODO move this to the collision coordinator!
  17037. if (_this.getScene().workerCollisions)
  17038. newPosition.multiplyInPlace(_this._collider._radius);
  17039. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17040. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17041. _this.position.addInPlace(_this._diffPositionForCollisions);
  17042. }
  17043. if (collidedMesh) {
  17044. _this.onCollideObservable.notifyObservers(collidedMesh);
  17045. }
  17046. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17047. };
  17048. _this.getScene().addMesh(_this);
  17049. _this._resyncLightSources();
  17050. return _this;
  17051. }
  17052. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17053. get: function () {
  17054. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17055. },
  17056. enumerable: true,
  17057. configurable: true
  17058. });
  17059. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17060. get: function () {
  17061. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17062. },
  17063. enumerable: true,
  17064. configurable: true
  17065. });
  17066. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17067. get: function () {
  17068. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17069. },
  17070. enumerable: true,
  17071. configurable: true
  17072. });
  17073. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17074. get: function () {
  17075. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17076. },
  17077. enumerable: true,
  17078. configurable: true
  17079. });
  17080. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17081. get: function () {
  17082. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17083. },
  17084. enumerable: true,
  17085. configurable: true
  17086. });
  17087. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17088. /**
  17089. * Read-only : the number of facets in the mesh
  17090. */
  17091. get: function () {
  17092. return this._facetNb;
  17093. },
  17094. enumerable: true,
  17095. configurable: true
  17096. });
  17097. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17098. /**
  17099. * The number (integer) of subdivisions per axis in the partioning space
  17100. */
  17101. get: function () {
  17102. return this._partitioningSubdivisions;
  17103. },
  17104. set: function (nb) {
  17105. this._partitioningSubdivisions = nb;
  17106. },
  17107. enumerable: true,
  17108. configurable: true
  17109. });
  17110. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17111. /**
  17112. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17113. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17114. */
  17115. get: function () {
  17116. return this._partitioningBBoxRatio;
  17117. },
  17118. set: function (ratio) {
  17119. this._partitioningBBoxRatio = ratio;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17125. /**
  17126. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17127. * Works only for updatable meshes.
  17128. * Doesn't work with multi-materials.
  17129. */
  17130. get: function () {
  17131. return this._facetDepthSort;
  17132. },
  17133. set: function (sort) {
  17134. this._facetDepthSort = sort;
  17135. },
  17136. enumerable: true,
  17137. configurable: true
  17138. });
  17139. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17140. /**
  17141. * The location (Vector3) where the facet depth sort must be computed from.
  17142. * By default, the active camera position.
  17143. * Used only when facet depth sort is enabled.
  17144. */
  17145. get: function () {
  17146. return this._facetDepthSortFrom;
  17147. },
  17148. set: function (location) {
  17149. this._facetDepthSortFrom = location;
  17150. },
  17151. enumerable: true,
  17152. configurable: true
  17153. });
  17154. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17155. /**
  17156. * Read-only boolean : is the feature facetData enabled ?
  17157. */
  17158. get: function () {
  17159. return this._facetDataEnabled;
  17160. },
  17161. enumerable: true,
  17162. configurable: true
  17163. });
  17164. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17165. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17166. return false;
  17167. }
  17168. this._markSubMeshesAsMiscDirty();
  17169. return true;
  17170. };
  17171. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17172. set: function (callback) {
  17173. if (this._onCollideObserver) {
  17174. this.onCollideObservable.remove(this._onCollideObserver);
  17175. }
  17176. this._onCollideObserver = this.onCollideObservable.add(callback);
  17177. },
  17178. enumerable: true,
  17179. configurable: true
  17180. });
  17181. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17182. set: function (callback) {
  17183. if (this._onCollisionPositionChangeObserver) {
  17184. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17185. }
  17186. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17192. /**
  17193. * 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.
  17194. */
  17195. get: function () {
  17196. return this._isOccluded;
  17197. },
  17198. set: function (value) {
  17199. this._isOccluded = value;
  17200. },
  17201. enumerable: true,
  17202. configurable: true
  17203. });
  17204. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17205. /**
  17206. * Flag to check the progress status of the query
  17207. */
  17208. get: function () {
  17209. return this._isOcclusionQueryInProgress;
  17210. },
  17211. enumerable: true,
  17212. configurable: true
  17213. });
  17214. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17215. /**
  17216. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17217. */
  17218. get: function () {
  17219. return this._visibility;
  17220. },
  17221. /**
  17222. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17223. */
  17224. set: function (value) {
  17225. if (this._visibility === value) {
  17226. return;
  17227. }
  17228. this._visibility = value;
  17229. this._markSubMeshesAsMiscDirty();
  17230. },
  17231. enumerable: true,
  17232. configurable: true
  17233. });
  17234. Object.defineProperty(AbstractMesh.prototype, "material", {
  17235. get: function () {
  17236. return this._material;
  17237. },
  17238. set: function (value) {
  17239. if (this._material === value) {
  17240. return;
  17241. }
  17242. this._material = value;
  17243. if (this.onMaterialChangedObservable.hasObservers) {
  17244. this.onMaterialChangedObservable.notifyObservers(this);
  17245. }
  17246. if (!this.subMeshes) {
  17247. return;
  17248. }
  17249. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17250. var subMesh = _a[_i];
  17251. subMesh.setEffect(null);
  17252. }
  17253. },
  17254. enumerable: true,
  17255. configurable: true
  17256. });
  17257. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17258. get: function () {
  17259. return this._receiveShadows;
  17260. },
  17261. set: function (value) {
  17262. if (this._receiveShadows === value) {
  17263. return;
  17264. }
  17265. this._receiveShadows = value;
  17266. this._markSubMeshesAsLightDirty();
  17267. },
  17268. enumerable: true,
  17269. configurable: true
  17270. });
  17271. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17272. get: function () {
  17273. return this._hasVertexAlpha;
  17274. },
  17275. set: function (value) {
  17276. if (this._hasVertexAlpha === value) {
  17277. return;
  17278. }
  17279. this._hasVertexAlpha = value;
  17280. this._markSubMeshesAsAttributesDirty();
  17281. this._markSubMeshesAsMiscDirty();
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17287. get: function () {
  17288. return this._useVertexColors;
  17289. },
  17290. set: function (value) {
  17291. if (this._useVertexColors === value) {
  17292. return;
  17293. }
  17294. this._useVertexColors = value;
  17295. this._markSubMeshesAsAttributesDirty();
  17296. },
  17297. enumerable: true,
  17298. configurable: true
  17299. });
  17300. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17301. get: function () {
  17302. return this._computeBonesUsingShaders;
  17303. },
  17304. set: function (value) {
  17305. if (this._computeBonesUsingShaders === value) {
  17306. return;
  17307. }
  17308. this._computeBonesUsingShaders = value;
  17309. this._markSubMeshesAsAttributesDirty();
  17310. },
  17311. enumerable: true,
  17312. configurable: true
  17313. });
  17314. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17315. get: function () {
  17316. return this._numBoneInfluencers;
  17317. },
  17318. set: function (value) {
  17319. if (this._numBoneInfluencers === value) {
  17320. return;
  17321. }
  17322. this._numBoneInfluencers = value;
  17323. this._markSubMeshesAsAttributesDirty();
  17324. },
  17325. enumerable: true,
  17326. configurable: true
  17327. });
  17328. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17329. get: function () {
  17330. return this._applyFog;
  17331. },
  17332. set: function (value) {
  17333. if (this._applyFog === value) {
  17334. return;
  17335. }
  17336. this._applyFog = value;
  17337. this._markSubMeshesAsMiscDirty();
  17338. },
  17339. enumerable: true,
  17340. configurable: true
  17341. });
  17342. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17343. get: function () {
  17344. return this._layerMask;
  17345. },
  17346. set: function (value) {
  17347. if (value === this._layerMask) {
  17348. return;
  17349. }
  17350. this._layerMask = value;
  17351. this._resyncLightSources();
  17352. },
  17353. enumerable: true,
  17354. configurable: true
  17355. });
  17356. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17357. get: function () {
  17358. return this._collisionMask;
  17359. },
  17360. set: function (mask) {
  17361. this._collisionMask = !isNaN(mask) ? mask : -1;
  17362. },
  17363. enumerable: true,
  17364. configurable: true
  17365. });
  17366. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17367. get: function () {
  17368. return this._collisionGroup;
  17369. },
  17370. set: function (mask) {
  17371. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17372. },
  17373. enumerable: true,
  17374. configurable: true
  17375. });
  17376. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17377. get: function () {
  17378. return null;
  17379. },
  17380. enumerable: true,
  17381. configurable: true
  17382. });
  17383. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17384. get: function () {
  17385. return this._skeleton;
  17386. },
  17387. set: function (value) {
  17388. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17389. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17390. }
  17391. if (value && value.needInitialSkinMatrix) {
  17392. value._registerMeshWithPoseMatrix(this);
  17393. }
  17394. this._skeleton = value;
  17395. if (!this._skeleton) {
  17396. this._bonesTransformMatrices = null;
  17397. }
  17398. this._markSubMeshesAsAttributesDirty();
  17399. },
  17400. enumerable: true,
  17401. configurable: true
  17402. });
  17403. /**
  17404. * Returns the string "AbstractMesh"
  17405. */
  17406. AbstractMesh.prototype.getClassName = function () {
  17407. return "AbstractMesh";
  17408. };
  17409. /**
  17410. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17411. */
  17412. AbstractMesh.prototype.toString = function (fullDetails) {
  17413. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17414. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17415. if (this._skeleton) {
  17416. ret += ", skeleton: " + this._skeleton.name;
  17417. }
  17418. if (fullDetails) {
  17419. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17420. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17421. }
  17422. return ret;
  17423. };
  17424. AbstractMesh.prototype._rebuild = function () {
  17425. if (this._occlusionQuery) {
  17426. this._occlusionQuery = null;
  17427. }
  17428. if (this._edgesRenderer) {
  17429. this._edgesRenderer._rebuild();
  17430. }
  17431. if (!this.subMeshes) {
  17432. return;
  17433. }
  17434. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17435. var subMesh = _a[_i];
  17436. subMesh._rebuild();
  17437. }
  17438. };
  17439. AbstractMesh.prototype._resyncLightSources = function () {
  17440. this._lightSources.length = 0;
  17441. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17442. var light = _a[_i];
  17443. if (!light.isEnabled()) {
  17444. continue;
  17445. }
  17446. if (light.canAffectMesh(this)) {
  17447. this._lightSources.push(light);
  17448. }
  17449. }
  17450. this._markSubMeshesAsLightDirty();
  17451. };
  17452. AbstractMesh.prototype._resyncLighSource = function (light) {
  17453. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17454. var index = this._lightSources.indexOf(light);
  17455. if (index === -1) {
  17456. if (!isIn) {
  17457. return;
  17458. }
  17459. this._lightSources.push(light);
  17460. }
  17461. else {
  17462. if (isIn) {
  17463. return;
  17464. }
  17465. this._lightSources.splice(index, 1);
  17466. }
  17467. this._markSubMeshesAsLightDirty();
  17468. };
  17469. AbstractMesh.prototype._removeLightSource = function (light) {
  17470. var index = this._lightSources.indexOf(light);
  17471. if (index === -1) {
  17472. return;
  17473. }
  17474. this._lightSources.splice(index, 1);
  17475. this._markSubMeshesAsLightDirty();
  17476. };
  17477. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17478. if (!this.subMeshes) {
  17479. return;
  17480. }
  17481. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17482. var subMesh = _a[_i];
  17483. if (subMesh._materialDefines) {
  17484. func(subMesh._materialDefines);
  17485. }
  17486. }
  17487. };
  17488. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17489. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17490. };
  17491. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17492. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17493. };
  17494. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17495. if (!this.subMeshes) {
  17496. return;
  17497. }
  17498. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17499. var subMesh = _a[_i];
  17500. var material = subMesh.getMaterial();
  17501. if (material) {
  17502. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17503. }
  17504. }
  17505. };
  17506. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17507. /**
  17508. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17509. * Default : (1.0, 1.0, 1.0)
  17510. */
  17511. get: function () {
  17512. return this._scaling;
  17513. },
  17514. /**
  17515. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17516. * Default : (1.0, 1.0, 1.0)
  17517. */
  17518. set: function (newScaling) {
  17519. this._scaling = newScaling;
  17520. if (this.physicsImpostor) {
  17521. this.physicsImpostor.forceUpdate();
  17522. }
  17523. },
  17524. enumerable: true,
  17525. configurable: true
  17526. });
  17527. // Methods
  17528. /**
  17529. * Disables the mesh edger rendering mode.
  17530. * Returns the AbstractMesh.
  17531. */
  17532. AbstractMesh.prototype.disableEdgesRendering = function () {
  17533. if (this._edgesRenderer) {
  17534. this._edgesRenderer.dispose();
  17535. this._edgesRenderer = null;
  17536. }
  17537. return this;
  17538. };
  17539. /**
  17540. * Enables the edge rendering mode on the mesh.
  17541. * This mode makes the mesh edges visible.
  17542. * Returns the AbstractMesh.
  17543. */
  17544. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17545. if (epsilon === void 0) { epsilon = 0.95; }
  17546. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17547. this.disableEdgesRendering();
  17548. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17549. return this;
  17550. };
  17551. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17552. /**
  17553. * Returns true if the mesh is blocked. Used by the class Mesh.
  17554. * Returns the boolean `false` by default.
  17555. */
  17556. get: function () {
  17557. return false;
  17558. },
  17559. enumerable: true,
  17560. configurable: true
  17561. });
  17562. /**
  17563. * Returns the mesh itself by default, used by the class Mesh.
  17564. * Returned type : AbstractMesh
  17565. */
  17566. AbstractMesh.prototype.getLOD = function (camera) {
  17567. return this;
  17568. };
  17569. /**
  17570. * Returns 0 by default, used by the class Mesh.
  17571. * Returns an integer.
  17572. */
  17573. AbstractMesh.prototype.getTotalVertices = function () {
  17574. return 0;
  17575. };
  17576. /**
  17577. * Returns null by default, used by the class Mesh.
  17578. * Returned type : integer array
  17579. */
  17580. AbstractMesh.prototype.getIndices = function () {
  17581. return null;
  17582. };
  17583. /**
  17584. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17585. * Returned type : float array or Float32Array
  17586. */
  17587. AbstractMesh.prototype.getVerticesData = function (kind) {
  17588. return null;
  17589. };
  17590. /**
  17591. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17592. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17593. * The `data` are either a numeric array either a Float32Array.
  17594. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17595. * 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).
  17596. * Note that a new underlying VertexBuffer object is created each call.
  17597. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17598. *
  17599. * Possible `kind` values :
  17600. * - BABYLON.VertexBuffer.PositionKind
  17601. * - BABYLON.VertexBuffer.UVKind
  17602. * - BABYLON.VertexBuffer.UV2Kind
  17603. * - BABYLON.VertexBuffer.UV3Kind
  17604. * - BABYLON.VertexBuffer.UV4Kind
  17605. * - BABYLON.VertexBuffer.UV5Kind
  17606. * - BABYLON.VertexBuffer.UV6Kind
  17607. * - BABYLON.VertexBuffer.ColorKind
  17608. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17609. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17610. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17611. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17612. *
  17613. * Returns the Mesh.
  17614. */
  17615. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17616. return this;
  17617. };
  17618. /**
  17619. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17620. * If the mesh has no geometry, it is simply returned as it is.
  17621. * The `data` are either a numeric array either a Float32Array.
  17622. * No new underlying VertexBuffer object is created.
  17623. * 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.
  17624. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17625. *
  17626. * Possible `kind` values :
  17627. * - BABYLON.VertexBuffer.PositionKind
  17628. * - BABYLON.VertexBuffer.UVKind
  17629. * - BABYLON.VertexBuffer.UV2Kind
  17630. * - BABYLON.VertexBuffer.UV3Kind
  17631. * - BABYLON.VertexBuffer.UV4Kind
  17632. * - BABYLON.VertexBuffer.UV5Kind
  17633. * - BABYLON.VertexBuffer.UV6Kind
  17634. * - BABYLON.VertexBuffer.ColorKind
  17635. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17636. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17637. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17638. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17639. *
  17640. * Returns the Mesh.
  17641. */
  17642. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17643. return this;
  17644. };
  17645. /**
  17646. * Sets the mesh indices.
  17647. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17648. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17649. * This method creates a new index buffer each call.
  17650. * Returns the Mesh.
  17651. */
  17652. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17653. return this;
  17654. };
  17655. /** Returns false by default, used by the class Mesh.
  17656. * Returns a boolean
  17657. */
  17658. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17659. return false;
  17660. };
  17661. /**
  17662. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17663. * Returns a BoundingInfo
  17664. */
  17665. AbstractMesh.prototype.getBoundingInfo = function () {
  17666. if (this._masterMesh) {
  17667. return this._masterMesh.getBoundingInfo();
  17668. }
  17669. if (!this._boundingInfo) {
  17670. // this._boundingInfo is being created here
  17671. this._updateBoundingInfo();
  17672. }
  17673. // cannot be null.
  17674. return this._boundingInfo;
  17675. };
  17676. /**
  17677. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17678. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17679. */
  17680. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17681. if (includeDescendants === void 0) { includeDescendants = true; }
  17682. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17683. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17684. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17685. if (maxDimension === 0) {
  17686. return this;
  17687. }
  17688. var scale = 1 / maxDimension;
  17689. this.scaling.scaleInPlace(scale);
  17690. return this;
  17691. };
  17692. /**
  17693. * Sets a mesh new object BoundingInfo.
  17694. * Returns the AbstractMesh.
  17695. */
  17696. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17697. this._boundingInfo = boundingInfo;
  17698. return this;
  17699. };
  17700. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17701. get: function () {
  17702. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17703. },
  17704. enumerable: true,
  17705. configurable: true
  17706. });
  17707. AbstractMesh.prototype._preActivate = function () {
  17708. };
  17709. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17710. };
  17711. AbstractMesh.prototype._activate = function (renderId) {
  17712. this._renderId = renderId;
  17713. };
  17714. /**
  17715. * Returns the latest update of the World matrix
  17716. * Returns a Matrix.
  17717. */
  17718. AbstractMesh.prototype.getWorldMatrix = function () {
  17719. if (this._masterMesh) {
  17720. return this._masterMesh.getWorldMatrix();
  17721. }
  17722. return _super.prototype.getWorldMatrix.call(this);
  17723. };
  17724. /**
  17725. * Returns the latest update of the World matrix determinant.
  17726. */
  17727. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17728. if (this._masterMesh) {
  17729. return this._masterMesh._getWorldMatrixDeterminant();
  17730. }
  17731. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17732. };
  17733. // ================================== Point of View Movement =================================
  17734. /**
  17735. * Perform relative position change from the point of view of behind the front of the mesh.
  17736. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17737. * Supports definition of mesh facing forward or backward.
  17738. * @param {number} amountRight
  17739. * @param {number} amountUp
  17740. * @param {number} amountForward
  17741. *
  17742. * Returns the AbstractMesh.
  17743. */
  17744. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17745. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17746. return this;
  17747. };
  17748. /**
  17749. * Calculate relative position change from the point of view of behind the front of the mesh.
  17750. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17751. * Supports definition of mesh facing forward or backward.
  17752. * @param {number} amountRight
  17753. * @param {number} amountUp
  17754. * @param {number} amountForward
  17755. *
  17756. * Returns a new Vector3.
  17757. */
  17758. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17759. var rotMatrix = new BABYLON.Matrix();
  17760. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17761. rotQuaternion.toRotationMatrix(rotMatrix);
  17762. var translationDelta = BABYLON.Vector3.Zero();
  17763. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17764. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17765. return translationDelta;
  17766. };
  17767. // ================================== Point of View Rotation =================================
  17768. /**
  17769. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17770. * Supports definition of mesh facing forward or backward.
  17771. * @param {number} flipBack
  17772. * @param {number} twirlClockwise
  17773. * @param {number} tiltRight
  17774. *
  17775. * Returns the AbstractMesh.
  17776. */
  17777. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17778. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17779. return this;
  17780. };
  17781. /**
  17782. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17783. * Supports definition of mesh facing forward or backward.
  17784. * @param {number} flipBack
  17785. * @param {number} twirlClockwise
  17786. * @param {number} tiltRight
  17787. *
  17788. * Returns a new Vector3.
  17789. */
  17790. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17791. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17792. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17793. };
  17794. /**
  17795. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17796. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17797. */
  17798. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17799. if (includeDescendants === void 0) { includeDescendants = true; }
  17800. this.computeWorldMatrix(true);
  17801. var min;
  17802. var max;
  17803. var boundingInfo = this.getBoundingInfo();
  17804. if (!this.subMeshes) {
  17805. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17806. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17807. }
  17808. else {
  17809. min = boundingInfo.boundingBox.minimumWorld;
  17810. max = boundingInfo.boundingBox.maximumWorld;
  17811. }
  17812. if (includeDescendants) {
  17813. var descendants = this.getDescendants(false);
  17814. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17815. var descendant = descendants_1[_i];
  17816. var childMesh = descendant;
  17817. childMesh.computeWorldMatrix(true);
  17818. //make sure we have the needed params to get mix and max
  17819. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17820. continue;
  17821. }
  17822. var childBoundingInfo = childMesh.getBoundingInfo();
  17823. var boundingBox = childBoundingInfo.boundingBox;
  17824. var minBox = boundingBox.minimumWorld;
  17825. var maxBox = boundingBox.maximumWorld;
  17826. BABYLON.Tools.CheckExtends(minBox, min, max);
  17827. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17828. }
  17829. }
  17830. return {
  17831. min: min,
  17832. max: max
  17833. };
  17834. };
  17835. /**
  17836. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17837. * Returns the AbstractMesh.
  17838. */
  17839. AbstractMesh.prototype._updateBoundingInfo = function () {
  17840. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17841. this._boundingInfo.update(this.worldMatrixFromCache);
  17842. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17843. return this;
  17844. };
  17845. /**
  17846. * Update a mesh's children BoundingInfo objects only.
  17847. * Returns the AbstractMesh.
  17848. */
  17849. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17850. if (!this.subMeshes) {
  17851. return this;
  17852. }
  17853. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17854. var subMesh = this.subMeshes[subIndex];
  17855. if (!subMesh.IsGlobal) {
  17856. subMesh.updateBoundingInfo(matrix);
  17857. }
  17858. }
  17859. return this;
  17860. };
  17861. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17862. // Bounding info
  17863. this._updateBoundingInfo();
  17864. };
  17865. /**
  17866. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17867. * A mesh is in the frustum if its bounding box intersects the frustum.
  17868. * Boolean returned.
  17869. */
  17870. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17871. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17872. };
  17873. /**
  17874. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17875. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17876. * Boolean returned.
  17877. */
  17878. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17879. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17880. ;
  17881. };
  17882. /**
  17883. * True if the mesh intersects another mesh or a SolidParticle object.
  17884. * 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)
  17885. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17886. * Returns a boolean.
  17887. */
  17888. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17889. if (precise === void 0) { precise = false; }
  17890. if (!this._boundingInfo || !mesh._boundingInfo) {
  17891. return false;
  17892. }
  17893. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17894. return true;
  17895. }
  17896. if (includeDescendants) {
  17897. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17898. var child = _a[_i];
  17899. if (child.intersectsMesh(mesh, precise, true)) {
  17900. return true;
  17901. }
  17902. }
  17903. }
  17904. return false;
  17905. };
  17906. /**
  17907. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17908. * Returns a boolean.
  17909. */
  17910. AbstractMesh.prototype.intersectsPoint = function (point) {
  17911. if (!this._boundingInfo) {
  17912. return false;
  17913. }
  17914. return this._boundingInfo.intersectsPoint(point);
  17915. };
  17916. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17917. return this.physicsImpostor;
  17918. };
  17919. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17920. if (camera === void 0) { camera = null; }
  17921. if (!camera) {
  17922. camera = this.getScene().activeCamera;
  17923. }
  17924. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17925. };
  17926. /**
  17927. * Returns the distance from the mesh to the active camera.
  17928. * Returns a float.
  17929. */
  17930. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17931. if (camera === void 0) { camera = null; }
  17932. if (!camera) {
  17933. camera = this.getScene().activeCamera;
  17934. }
  17935. return this.absolutePosition.subtract(camera.position).length();
  17936. };
  17937. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17938. if (!this.physicsImpostor) {
  17939. return this;
  17940. }
  17941. this.physicsImpostor.applyImpulse(force, contactPoint);
  17942. return this;
  17943. };
  17944. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17945. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17946. return this;
  17947. }
  17948. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17949. mainPivot: pivot1,
  17950. connectedPivot: pivot2,
  17951. nativeParams: options
  17952. });
  17953. return this;
  17954. };
  17955. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17956. // Collisions
  17957. /**
  17958. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17959. * Default `false`.
  17960. */
  17961. get: function () {
  17962. return this._checkCollisions;
  17963. },
  17964. set: function (collisionEnabled) {
  17965. this._checkCollisions = collisionEnabled;
  17966. if (this.getScene().workerCollisions) {
  17967. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17968. }
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17974. /**
  17975. * Gets Collider object used to compute collisions (not physics)
  17976. */
  17977. get: function () {
  17978. return this._collider;
  17979. },
  17980. enumerable: true,
  17981. configurable: true
  17982. });
  17983. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17984. var globalPosition = this.getAbsolutePosition();
  17985. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17986. if (!this._collider) {
  17987. this._collider = new BABYLON.Collider();
  17988. }
  17989. this._collider._radius = this.ellipsoid;
  17990. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17991. return this;
  17992. };
  17993. // Submeshes octree
  17994. /**
  17995. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17996. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17997. * Returns an Octree of submeshes.
  17998. */
  17999. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18000. if (maxCapacity === void 0) { maxCapacity = 64; }
  18001. if (maxDepth === void 0) { maxDepth = 2; }
  18002. if (!this._submeshesOctree) {
  18003. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18004. }
  18005. this.computeWorldMatrix(true);
  18006. var boundingInfo = this.getBoundingInfo();
  18007. // Update octree
  18008. var bbox = boundingInfo.boundingBox;
  18009. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18010. return this._submeshesOctree;
  18011. };
  18012. // Collisions
  18013. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18014. this._generatePointsArray();
  18015. if (!this._positions) {
  18016. return this;
  18017. }
  18018. // Transformation
  18019. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18020. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18021. subMesh._lastColliderWorldVertices = [];
  18022. subMesh._trianglePlanes = [];
  18023. var start = subMesh.verticesStart;
  18024. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18025. for (var i = start; i < end; i++) {
  18026. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18027. }
  18028. }
  18029. // Collide
  18030. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18031. if (collider.collisionFound) {
  18032. collider.collidedMesh = this;
  18033. }
  18034. return this;
  18035. };
  18036. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18037. var subMeshes;
  18038. var len;
  18039. // Octrees
  18040. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18041. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18042. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18043. len = intersections.length;
  18044. subMeshes = intersections.data;
  18045. }
  18046. else {
  18047. subMeshes = this.subMeshes;
  18048. len = subMeshes.length;
  18049. }
  18050. for (var index = 0; index < len; index++) {
  18051. var subMesh = subMeshes[index];
  18052. // Bounding test
  18053. if (len > 1 && !subMesh._checkCollision(collider))
  18054. continue;
  18055. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18056. }
  18057. return this;
  18058. };
  18059. AbstractMesh.prototype._checkCollision = function (collider) {
  18060. // Bounding box test
  18061. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18062. return this;
  18063. // Transformation matrix
  18064. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18065. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18066. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18067. return this;
  18068. };
  18069. // Picking
  18070. AbstractMesh.prototype._generatePointsArray = function () {
  18071. return false;
  18072. };
  18073. /**
  18074. * Checks if the passed Ray intersects with the mesh.
  18075. * Returns an object PickingInfo.
  18076. */
  18077. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18078. var pickingInfo = new BABYLON.PickingInfo();
  18079. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18080. return pickingInfo;
  18081. }
  18082. if (!this._generatePointsArray()) {
  18083. return pickingInfo;
  18084. }
  18085. var intersectInfo = null;
  18086. // Octrees
  18087. var subMeshes;
  18088. var len;
  18089. if (this._submeshesOctree && this.useOctreeForPicking) {
  18090. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18091. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18092. len = intersections.length;
  18093. subMeshes = intersections.data;
  18094. }
  18095. else {
  18096. subMeshes = this.subMeshes;
  18097. len = subMeshes.length;
  18098. }
  18099. for (var index = 0; index < len; index++) {
  18100. var subMesh = subMeshes[index];
  18101. // Bounding test
  18102. if (len > 1 && !subMesh.canIntersects(ray))
  18103. continue;
  18104. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18105. if (currentIntersectInfo) {
  18106. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18107. intersectInfo = currentIntersectInfo;
  18108. intersectInfo.subMeshId = index;
  18109. if (fastCheck) {
  18110. break;
  18111. }
  18112. }
  18113. }
  18114. }
  18115. if (intersectInfo) {
  18116. // Get picked point
  18117. var world = this.getWorldMatrix();
  18118. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18119. var direction = ray.direction.clone();
  18120. direction = direction.scale(intersectInfo.distance);
  18121. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18122. var pickedPoint = worldOrigin.add(worldDirection);
  18123. // Return result
  18124. pickingInfo.hit = true;
  18125. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18126. pickingInfo.pickedPoint = pickedPoint;
  18127. pickingInfo.pickedMesh = this;
  18128. pickingInfo.bu = intersectInfo.bu || 0;
  18129. pickingInfo.bv = intersectInfo.bv || 0;
  18130. pickingInfo.faceId = intersectInfo.faceId;
  18131. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18132. return pickingInfo;
  18133. }
  18134. return pickingInfo;
  18135. };
  18136. /**
  18137. * Clones the mesh, used by the class Mesh.
  18138. * Just returns `null` for an AbstractMesh.
  18139. */
  18140. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18141. return null;
  18142. };
  18143. /**
  18144. * Disposes all the mesh submeshes.
  18145. * Returns the AbstractMesh.
  18146. */
  18147. AbstractMesh.prototype.releaseSubMeshes = function () {
  18148. if (this.subMeshes) {
  18149. while (this.subMeshes.length) {
  18150. this.subMeshes[0].dispose();
  18151. }
  18152. }
  18153. else {
  18154. this.subMeshes = new Array();
  18155. }
  18156. return this;
  18157. };
  18158. /**
  18159. * Disposes the AbstractMesh.
  18160. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18161. * Returns nothing.
  18162. */
  18163. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18164. var _this = this;
  18165. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18166. var index;
  18167. // Action manager
  18168. if (this.actionManager !== undefined && this.actionManager !== null) {
  18169. this.actionManager.dispose();
  18170. this.actionManager = null;
  18171. }
  18172. // Skeleton
  18173. this.skeleton = null;
  18174. // Physics
  18175. if (this.physicsImpostor) {
  18176. this.physicsImpostor.dispose();
  18177. }
  18178. // Intersections in progress
  18179. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18180. var other = this._intersectionsInProgress[index];
  18181. var pos = other._intersectionsInProgress.indexOf(this);
  18182. other._intersectionsInProgress.splice(pos, 1);
  18183. }
  18184. this._intersectionsInProgress = [];
  18185. // Lights
  18186. var lights = this.getScene().lights;
  18187. lights.forEach(function (light) {
  18188. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18189. if (meshIndex !== -1) {
  18190. light.includedOnlyMeshes.splice(meshIndex, 1);
  18191. }
  18192. meshIndex = light.excludedMeshes.indexOf(_this);
  18193. if (meshIndex !== -1) {
  18194. light.excludedMeshes.splice(meshIndex, 1);
  18195. }
  18196. // Shadow generators
  18197. var generator = light.getShadowGenerator();
  18198. if (generator) {
  18199. var shadowMap = generator.getShadowMap();
  18200. if (shadowMap && shadowMap.renderList) {
  18201. meshIndex = shadowMap.renderList.indexOf(_this);
  18202. if (meshIndex !== -1) {
  18203. shadowMap.renderList.splice(meshIndex, 1);
  18204. }
  18205. }
  18206. }
  18207. });
  18208. // Edges
  18209. if (this._edgesRenderer) {
  18210. this._edgesRenderer.dispose();
  18211. this._edgesRenderer = null;
  18212. }
  18213. // SubMeshes
  18214. if (this.getClassName() !== "InstancedMesh") {
  18215. this.releaseSubMeshes();
  18216. }
  18217. // Octree
  18218. var sceneOctree = this.getScene().selectionOctree;
  18219. if (sceneOctree !== undefined && sceneOctree !== null) {
  18220. var index = sceneOctree.dynamicContent.indexOf(this);
  18221. if (index !== -1) {
  18222. sceneOctree.dynamicContent.splice(index, 1);
  18223. }
  18224. }
  18225. // Query
  18226. var engine = this.getScene().getEngine();
  18227. if (this._occlusionQuery) {
  18228. this._isOcclusionQueryInProgress = false;
  18229. engine.deleteQuery(this._occlusionQuery);
  18230. this._occlusionQuery = null;
  18231. }
  18232. // Engine
  18233. engine.wipeCaches();
  18234. // Remove from scene
  18235. this.getScene().removeMesh(this);
  18236. if (disposeMaterialAndTextures) {
  18237. if (this.material) {
  18238. this.material.dispose(false, true);
  18239. }
  18240. }
  18241. if (!doNotRecurse) {
  18242. // Particles
  18243. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18244. if (this.getScene().particleSystems[index].emitter === this) {
  18245. this.getScene().particleSystems[index].dispose();
  18246. index--;
  18247. }
  18248. }
  18249. }
  18250. // facet data
  18251. if (this._facetDataEnabled) {
  18252. this.disableFacetData();
  18253. }
  18254. this.onAfterWorldMatrixUpdateObservable.clear();
  18255. this.onCollideObservable.clear();
  18256. this.onCollisionPositionChangeObservable.clear();
  18257. _super.prototype.dispose.call(this, doNotRecurse);
  18258. };
  18259. /**
  18260. * Adds the passed mesh as a child to the current mesh.
  18261. * Returns the AbstractMesh.
  18262. */
  18263. AbstractMesh.prototype.addChild = function (mesh) {
  18264. mesh.setParent(this);
  18265. return this;
  18266. };
  18267. /**
  18268. * Removes the passed mesh from the current mesh children list.
  18269. * Returns the AbstractMesh.
  18270. */
  18271. AbstractMesh.prototype.removeChild = function (mesh) {
  18272. mesh.setParent(null);
  18273. return this;
  18274. };
  18275. // Facet data
  18276. /**
  18277. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18278. * Returns the AbstractMesh.
  18279. */
  18280. AbstractMesh.prototype._initFacetData = function () {
  18281. if (!this._facetNormals) {
  18282. this._facetNormals = new Array();
  18283. }
  18284. if (!this._facetPositions) {
  18285. this._facetPositions = new Array();
  18286. }
  18287. if (!this._facetPartitioning) {
  18288. this._facetPartitioning = new Array();
  18289. }
  18290. this._facetNb = (this.getIndices().length / 3) | 0;
  18291. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18292. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18293. for (var f = 0; f < this._facetNb; f++) {
  18294. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18295. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18296. }
  18297. this._facetDataEnabled = true;
  18298. return this;
  18299. };
  18300. /**
  18301. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18302. * This method can be called within the render loop.
  18303. * 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.
  18304. * Returns the AbstractMesh.
  18305. */
  18306. AbstractMesh.prototype.updateFacetData = function () {
  18307. if (!this._facetDataEnabled) {
  18308. this._initFacetData();
  18309. }
  18310. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18311. var indices = this.getIndices();
  18312. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18313. var bInfo = this.getBoundingInfo();
  18314. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18315. // init arrays, matrix and sort function on first call
  18316. this._facetDepthSortEnabled = true;
  18317. if (indices instanceof Uint16Array) {
  18318. this._depthSortedIndices = new Uint16Array(indices);
  18319. }
  18320. else if (indices instanceof Uint32Array) {
  18321. this._depthSortedIndices = new Uint32Array(indices);
  18322. }
  18323. else {
  18324. var needs32bits = false;
  18325. for (var i = 0; i < indices.length; i++) {
  18326. if (indices[i] > 65535) {
  18327. needs32bits = true;
  18328. break;
  18329. }
  18330. }
  18331. if (needs32bits) {
  18332. this._depthSortedIndices = new Uint32Array(indices);
  18333. }
  18334. else {
  18335. this._depthSortedIndices = new Uint16Array(indices);
  18336. }
  18337. }
  18338. this._facetDepthSortFunction = function (f1, f2) {
  18339. return (f2.sqDistance - f1.sqDistance);
  18340. };
  18341. if (!this._facetDepthSortFrom) {
  18342. var camera = this.getScene().activeCamera;
  18343. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18344. }
  18345. this._depthSortedFacets = [];
  18346. for (var f = 0; f < this._facetNb; f++) {
  18347. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18348. this._depthSortedFacets.push(depthSortedFacet);
  18349. }
  18350. this._invertedMatrix = BABYLON.Matrix.Identity();
  18351. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18352. }
  18353. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18354. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18355. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18356. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18357. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18358. this._subDiv.max = this._partitioningSubdivisions;
  18359. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18360. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18361. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18362. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18363. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18364. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18365. // set the parameters for ComputeNormals()
  18366. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18367. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18368. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18369. this._facetParameters.bInfo = bInfo;
  18370. this._facetParameters.bbSize = this._bbSize;
  18371. this._facetParameters.subDiv = this._subDiv;
  18372. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18373. this._facetParameters.depthSort = this._facetDepthSort;
  18374. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18375. this.computeWorldMatrix(true);
  18376. this._worldMatrix.invertToRef(this._invertedMatrix);
  18377. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18378. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18379. }
  18380. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18381. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18382. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18383. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18384. var l = (this._depthSortedIndices.length / 3) | 0;
  18385. for (var f = 0; f < l; f++) {
  18386. var sind = this._depthSortedFacets[f].ind;
  18387. this._depthSortedIndices[f * 3] = indices[sind];
  18388. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18389. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18390. }
  18391. this.updateIndices(this._depthSortedIndices);
  18392. }
  18393. return this;
  18394. };
  18395. /**
  18396. * Returns the facetLocalNormals array.
  18397. * The normals are expressed in the mesh local space.
  18398. */
  18399. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18400. if (!this._facetNormals) {
  18401. this.updateFacetData();
  18402. }
  18403. return this._facetNormals;
  18404. };
  18405. /**
  18406. * Returns the facetLocalPositions array.
  18407. * The facet positions are expressed in the mesh local space.
  18408. */
  18409. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18410. if (!this._facetPositions) {
  18411. this.updateFacetData();
  18412. }
  18413. return this._facetPositions;
  18414. };
  18415. /**
  18416. * Returns the facetLocalPartioning array.
  18417. */
  18418. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18419. if (!this._facetPartitioning) {
  18420. this.updateFacetData();
  18421. }
  18422. return this._facetPartitioning;
  18423. };
  18424. /**
  18425. * Returns the i-th facet position in the world system.
  18426. * This method allocates a new Vector3 per call.
  18427. */
  18428. AbstractMesh.prototype.getFacetPosition = function (i) {
  18429. var pos = BABYLON.Vector3.Zero();
  18430. this.getFacetPositionToRef(i, pos);
  18431. return pos;
  18432. };
  18433. /**
  18434. * Sets the reference Vector3 with the i-th facet position in the world system.
  18435. * Returns the AbstractMesh.
  18436. */
  18437. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18438. var localPos = (this.getFacetLocalPositions())[i];
  18439. var world = this.getWorldMatrix();
  18440. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18441. return this;
  18442. };
  18443. /**
  18444. * Returns the i-th facet normal in the world system.
  18445. * This method allocates a new Vector3 per call.
  18446. */
  18447. AbstractMesh.prototype.getFacetNormal = function (i) {
  18448. var norm = BABYLON.Vector3.Zero();
  18449. this.getFacetNormalToRef(i, norm);
  18450. return norm;
  18451. };
  18452. /**
  18453. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18454. * Returns the AbstractMesh.
  18455. */
  18456. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18457. var localNorm = (this.getFacetLocalNormals())[i];
  18458. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18459. return this;
  18460. };
  18461. /**
  18462. * 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).
  18463. */
  18464. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18465. var bInfo = this.getBoundingInfo();
  18466. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18467. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18468. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18469. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18470. return null;
  18471. }
  18472. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18473. };
  18474. /**
  18475. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18476. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18477. * 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.
  18478. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18479. * 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.
  18480. */
  18481. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18482. if (checkFace === void 0) { checkFace = false; }
  18483. if (facing === void 0) { facing = true; }
  18484. var world = this.getWorldMatrix();
  18485. var invMat = BABYLON.Tmp.Matrix[5];
  18486. world.invertToRef(invMat);
  18487. var invVect = BABYLON.Tmp.Vector3[8];
  18488. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18489. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18490. if (projected) {
  18491. // tranform the local computed projected vector to world coordinates
  18492. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18493. }
  18494. return closest;
  18495. };
  18496. /**
  18497. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18498. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18499. * 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.
  18500. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18501. * 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.
  18502. */
  18503. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18504. if (checkFace === void 0) { checkFace = false; }
  18505. if (facing === void 0) { facing = true; }
  18506. var closest = null;
  18507. var tmpx = 0.0;
  18508. var tmpy = 0.0;
  18509. var tmpz = 0.0;
  18510. var d = 0.0; // tmp dot facet normal * facet position
  18511. var t0 = 0.0;
  18512. var projx = 0.0;
  18513. var projy = 0.0;
  18514. var projz = 0.0;
  18515. // Get all the facets in the same partitioning block than (x, y, z)
  18516. var facetPositions = this.getFacetLocalPositions();
  18517. var facetNormals = this.getFacetLocalNormals();
  18518. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18519. if (!facetsInBlock) {
  18520. return null;
  18521. }
  18522. // Get the closest facet to (x, y, z)
  18523. var shortest = Number.MAX_VALUE; // init distance vars
  18524. var tmpDistance = shortest;
  18525. var fib; // current facet in the block
  18526. var norm; // current facet normal
  18527. var p0; // current facet barycenter position
  18528. // loop on all the facets in the current partitioning block
  18529. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18530. fib = facetsInBlock[idx];
  18531. norm = facetNormals[fib];
  18532. p0 = facetPositions[fib];
  18533. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18534. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18535. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18536. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18537. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18538. projx = x + norm.x * t0;
  18539. projy = y + norm.y * t0;
  18540. projz = z + norm.z * t0;
  18541. tmpx = projx - x;
  18542. tmpy = projy - y;
  18543. tmpz = projz - z;
  18544. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18545. if (tmpDistance < shortest) {
  18546. shortest = tmpDistance;
  18547. closest = fib;
  18548. if (projected) {
  18549. projected.x = projx;
  18550. projected.y = projy;
  18551. projected.z = projz;
  18552. }
  18553. }
  18554. }
  18555. }
  18556. return closest;
  18557. };
  18558. /**
  18559. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18560. */
  18561. AbstractMesh.prototype.getFacetDataParameters = function () {
  18562. return this._facetParameters;
  18563. };
  18564. /**
  18565. * Disables the feature FacetData and frees the related memory.
  18566. * Returns the AbstractMesh.
  18567. */
  18568. AbstractMesh.prototype.disableFacetData = function () {
  18569. if (this._facetDataEnabled) {
  18570. this._facetDataEnabled = false;
  18571. this._facetPositions = new Array();
  18572. this._facetNormals = new Array();
  18573. this._facetPartitioning = new Array();
  18574. this._facetParameters = null;
  18575. this._depthSortedIndices = new Uint32Array(0);
  18576. }
  18577. return this;
  18578. };
  18579. /**
  18580. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18581. * Returns the mesh.
  18582. */
  18583. AbstractMesh.prototype.updateIndices = function (indices) {
  18584. return this;
  18585. };
  18586. /**
  18587. * The mesh Geometry. Actually used by the Mesh object.
  18588. * Returns a blank geometry object.
  18589. */
  18590. /**
  18591. * Creates new normals data for the mesh.
  18592. * @param updatable.
  18593. */
  18594. AbstractMesh.prototype.createNormals = function (updatable) {
  18595. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18596. var indices = this.getIndices();
  18597. var normals;
  18598. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18599. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18600. }
  18601. else {
  18602. normals = [];
  18603. }
  18604. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18605. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18606. };
  18607. /**
  18608. * Align the mesh with a normal.
  18609. * Returns the mesh.
  18610. */
  18611. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18612. if (!upDirection) {
  18613. upDirection = BABYLON.Axis.Y;
  18614. }
  18615. var axisX = BABYLON.Tmp.Vector3[0];
  18616. var axisZ = BABYLON.Tmp.Vector3[1];
  18617. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18618. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18619. if (this.rotationQuaternion) {
  18620. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18621. }
  18622. else {
  18623. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18624. }
  18625. return this;
  18626. };
  18627. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18628. var engine = this.getEngine();
  18629. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18630. this._isOccluded = false;
  18631. return;
  18632. }
  18633. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18634. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18635. if (isOcclusionQueryAvailable) {
  18636. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18637. this._isOcclusionQueryInProgress = false;
  18638. this._occlusionInternalRetryCounter = 0;
  18639. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18640. }
  18641. else {
  18642. this._occlusionInternalRetryCounter++;
  18643. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18644. this._isOcclusionQueryInProgress = false;
  18645. this._occlusionInternalRetryCounter = 0;
  18646. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18647. // if strict continue the last state of the object.
  18648. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18649. }
  18650. else {
  18651. return;
  18652. }
  18653. }
  18654. }
  18655. var scene = this.getScene();
  18656. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18657. if (!this._occlusionQuery) {
  18658. this._occlusionQuery = engine.createQuery();
  18659. }
  18660. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18661. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18662. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18663. this._isOcclusionQueryInProgress = true;
  18664. };
  18665. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18666. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18667. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18668. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18669. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18670. return AbstractMesh;
  18671. }(BABYLON.TransformNode));
  18672. BABYLON.AbstractMesh = AbstractMesh;
  18673. })(BABYLON || (BABYLON = {}));
  18674. //# sourceMappingURL=babylon.abstractMesh.js.map
  18675. var BABYLON;
  18676. (function (BABYLON) {
  18677. /**
  18678. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18679. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18680. * 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.
  18681. */
  18682. var Light = /** @class */ (function (_super) {
  18683. __extends(Light, _super);
  18684. /**
  18685. * Creates a Light object in the scene.
  18686. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18687. * @param name The firendly name of the light
  18688. * @param scene The scene the light belongs too
  18689. */
  18690. function Light(name, scene) {
  18691. var _this = _super.call(this, name, scene) || this;
  18692. /**
  18693. * Diffuse gives the basic color to an object.
  18694. */
  18695. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18696. /**
  18697. * Specular produces a highlight color on an object.
  18698. * Note: This is note affecting PBR materials.
  18699. */
  18700. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18701. /**
  18702. * Strength of the light.
  18703. * Note: By default it is define in the framework own unit.
  18704. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18705. */
  18706. _this.intensity = 1.0;
  18707. /**
  18708. * Defines how far from the source the light is impacting in scene units.
  18709. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18710. */
  18711. _this.range = Number.MAX_VALUE;
  18712. /**
  18713. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18714. * of light.
  18715. */
  18716. _this._photometricScale = 1.0;
  18717. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18718. _this._radius = 0.00001;
  18719. /**
  18720. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18721. * exceeding the number allowed of the materials.
  18722. */
  18723. _this.renderPriority = 0;
  18724. /**
  18725. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18726. * the current shadow generator.
  18727. */
  18728. _this.shadowEnabled = true;
  18729. _this._excludeWithLayerMask = 0;
  18730. _this._includeOnlyWithLayerMask = 0;
  18731. _this._lightmapMode = 0;
  18732. /**
  18733. * @ignore Internal use only.
  18734. */
  18735. _this._excludedMeshesIds = new Array();
  18736. /**
  18737. * @ignore Internal use only.
  18738. */
  18739. _this._includedOnlyMeshesIds = new Array();
  18740. _this.getScene().addLight(_this);
  18741. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18742. _this._buildUniformLayout();
  18743. _this.includedOnlyMeshes = new Array();
  18744. _this.excludedMeshes = new Array();
  18745. _this._resyncMeshes();
  18746. return _this;
  18747. }
  18748. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18749. /**
  18750. * If every light affecting the material is in this lightmapMode,
  18751. * material.lightmapTexture adds or multiplies
  18752. * (depends on material.useLightmapAsShadowmap)
  18753. * after every other light calculations.
  18754. */
  18755. get: function () {
  18756. return Light._LIGHTMAP_DEFAULT;
  18757. },
  18758. enumerable: true,
  18759. configurable: true
  18760. });
  18761. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18762. /**
  18763. * material.lightmapTexture as only diffuse lighting from this light
  18764. * adds only specular lighting from this light
  18765. * adds dynamic shadows
  18766. */
  18767. get: function () {
  18768. return Light._LIGHTMAP_SPECULAR;
  18769. },
  18770. enumerable: true,
  18771. configurable: true
  18772. });
  18773. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18774. /**
  18775. * material.lightmapTexture as only lighting
  18776. * no light calculation from this light
  18777. * only adds dynamic shadows from this light
  18778. */
  18779. get: function () {
  18780. return Light._LIGHTMAP_SHADOWSONLY;
  18781. },
  18782. enumerable: true,
  18783. configurable: true
  18784. });
  18785. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18786. /**
  18787. * Each light type uses the default quantity according to its type:
  18788. * point/spot lights use luminous intensity
  18789. * directional lights use illuminance
  18790. */
  18791. get: function () {
  18792. return Light._INTENSITYMODE_AUTOMATIC;
  18793. },
  18794. enumerable: true,
  18795. configurable: true
  18796. });
  18797. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18798. /**
  18799. * lumen (lm)
  18800. */
  18801. get: function () {
  18802. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18803. },
  18804. enumerable: true,
  18805. configurable: true
  18806. });
  18807. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18808. /**
  18809. * candela (lm/sr)
  18810. */
  18811. get: function () {
  18812. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18813. },
  18814. enumerable: true,
  18815. configurable: true
  18816. });
  18817. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18818. /**
  18819. * lux (lm/m^2)
  18820. */
  18821. get: function () {
  18822. return Light._INTENSITYMODE_ILLUMINANCE;
  18823. },
  18824. enumerable: true,
  18825. configurable: true
  18826. });
  18827. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18828. /**
  18829. * nit (cd/m^2)
  18830. */
  18831. get: function () {
  18832. return Light._INTENSITYMODE_LUMINANCE;
  18833. },
  18834. enumerable: true,
  18835. configurable: true
  18836. });
  18837. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18838. /**
  18839. * Light type const id of the point light.
  18840. */
  18841. get: function () {
  18842. return Light._LIGHTTYPEID_POINTLIGHT;
  18843. },
  18844. enumerable: true,
  18845. configurable: true
  18846. });
  18847. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18848. /**
  18849. * Light type const id of the directional light.
  18850. */
  18851. get: function () {
  18852. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18853. },
  18854. enumerable: true,
  18855. configurable: true
  18856. });
  18857. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18858. /**
  18859. * Light type const id of the spot light.
  18860. */
  18861. get: function () {
  18862. return Light._LIGHTTYPEID_SPOTLIGHT;
  18863. },
  18864. enumerable: true,
  18865. configurable: true
  18866. });
  18867. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18868. /**
  18869. * Light type const id of the hemispheric light.
  18870. */
  18871. get: function () {
  18872. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. Object.defineProperty(Light.prototype, "intensityMode", {
  18878. /**
  18879. * Gets the photometric scale used to interpret the intensity.
  18880. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18881. */
  18882. get: function () {
  18883. return this._intensityMode;
  18884. },
  18885. /**
  18886. * Sets the photometric scale used to interpret the intensity.
  18887. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18888. */
  18889. set: function (value) {
  18890. this._intensityMode = value;
  18891. this._computePhotometricScale();
  18892. },
  18893. enumerable: true,
  18894. configurable: true
  18895. });
  18896. ;
  18897. ;
  18898. Object.defineProperty(Light.prototype, "radius", {
  18899. /**
  18900. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18901. */
  18902. get: function () {
  18903. return this._radius;
  18904. },
  18905. /**
  18906. * sets the light radius used by PBR Materials to simulate soft area lights.
  18907. */
  18908. set: function (value) {
  18909. this._radius = value;
  18910. this._computePhotometricScale();
  18911. },
  18912. enumerable: true,
  18913. configurable: true
  18914. });
  18915. ;
  18916. ;
  18917. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18918. /**
  18919. * Gets the only meshes impacted by this light.
  18920. */
  18921. get: function () {
  18922. return this._includedOnlyMeshes;
  18923. },
  18924. /**
  18925. * Sets the only meshes impacted by this light.
  18926. */
  18927. set: function (value) {
  18928. this._includedOnlyMeshes = value;
  18929. this._hookArrayForIncludedOnly(value);
  18930. },
  18931. enumerable: true,
  18932. configurable: true
  18933. });
  18934. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18935. /**
  18936. * Gets the meshes not impacted by this light.
  18937. */
  18938. get: function () {
  18939. return this._excludedMeshes;
  18940. },
  18941. /**
  18942. * Sets the meshes not impacted by this light.
  18943. */
  18944. set: function (value) {
  18945. this._excludedMeshes = value;
  18946. this._hookArrayForExcluded(value);
  18947. },
  18948. enumerable: true,
  18949. configurable: true
  18950. });
  18951. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18952. /**
  18953. * Gets the layer id use to find what meshes are not impacted by the light.
  18954. * Inactive if 0
  18955. */
  18956. get: function () {
  18957. return this._excludeWithLayerMask;
  18958. },
  18959. /**
  18960. * Sets the layer id use to find what meshes are not impacted by the light.
  18961. * Inactive if 0
  18962. */
  18963. set: function (value) {
  18964. this._excludeWithLayerMask = value;
  18965. this._resyncMeshes();
  18966. },
  18967. enumerable: true,
  18968. configurable: true
  18969. });
  18970. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18971. /**
  18972. * Gets the layer id use to find what meshes are impacted by the light.
  18973. * Inactive if 0
  18974. */
  18975. get: function () {
  18976. return this._includeOnlyWithLayerMask;
  18977. },
  18978. /**
  18979. * Sets the layer id use to find what meshes are impacted by the light.
  18980. * Inactive if 0
  18981. */
  18982. set: function (value) {
  18983. this._includeOnlyWithLayerMask = value;
  18984. this._resyncMeshes();
  18985. },
  18986. enumerable: true,
  18987. configurable: true
  18988. });
  18989. Object.defineProperty(Light.prototype, "lightmapMode", {
  18990. /**
  18991. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18992. */
  18993. get: function () {
  18994. return this._lightmapMode;
  18995. },
  18996. /**
  18997. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18998. */
  18999. set: function (value) {
  19000. if (this._lightmapMode === value) {
  19001. return;
  19002. }
  19003. this._lightmapMode = value;
  19004. this._markMeshesAsLightDirty();
  19005. },
  19006. enumerable: true,
  19007. configurable: true
  19008. });
  19009. /**
  19010. * Returns the string "Light".
  19011. * @returns the class name
  19012. */
  19013. Light.prototype.getClassName = function () {
  19014. return "Light";
  19015. };
  19016. /**
  19017. * Converts the light information to a readable string for debug purpose.
  19018. * @param fullDetails Supports for multiple levels of logging within scene loading
  19019. * @returns the human readable light info
  19020. */
  19021. Light.prototype.toString = function (fullDetails) {
  19022. var ret = "Name: " + this.name;
  19023. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19024. if (this.animations) {
  19025. for (var i = 0; i < this.animations.length; i++) {
  19026. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19027. }
  19028. }
  19029. if (fullDetails) {
  19030. }
  19031. return ret;
  19032. };
  19033. /**
  19034. * Set the enabled state of this node.
  19035. * @param value - the new enabled state
  19036. * @see isEnabled
  19037. */
  19038. Light.prototype.setEnabled = function (value) {
  19039. _super.prototype.setEnabled.call(this, value);
  19040. this._resyncMeshes();
  19041. };
  19042. /**
  19043. * Returns the Light associated shadow generator if any.
  19044. * @return the associated shadow generator.
  19045. */
  19046. Light.prototype.getShadowGenerator = function () {
  19047. return this._shadowGenerator;
  19048. };
  19049. /**
  19050. * Returns a Vector3, the absolute light position in the World.
  19051. * @returns the world space position of the light
  19052. */
  19053. Light.prototype.getAbsolutePosition = function () {
  19054. return BABYLON.Vector3.Zero();
  19055. };
  19056. /**
  19057. * Specifies if the light will affect the passed mesh.
  19058. * @param mesh The mesh to test against the light
  19059. * @return true the mesh is affected otherwise, false.
  19060. */
  19061. Light.prototype.canAffectMesh = function (mesh) {
  19062. if (!mesh) {
  19063. return true;
  19064. }
  19065. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19066. return false;
  19067. }
  19068. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19069. return false;
  19070. }
  19071. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19072. return false;
  19073. }
  19074. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19075. return false;
  19076. }
  19077. return true;
  19078. };
  19079. /**
  19080. * Computes and Returns the light World matrix.
  19081. * @returns the world matrix
  19082. */
  19083. Light.prototype.getWorldMatrix = function () {
  19084. this._currentRenderId = this.getScene().getRenderId();
  19085. var worldMatrix = this._getWorldMatrix();
  19086. if (this.parent && this.parent.getWorldMatrix) {
  19087. if (!this._parentedWorldMatrix) {
  19088. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19089. }
  19090. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19091. this._markSyncedWithParent();
  19092. return this._parentedWorldMatrix;
  19093. }
  19094. return worldMatrix;
  19095. };
  19096. /**
  19097. * Sort function to order lights for rendering.
  19098. * @param a First Light object to compare to second.
  19099. * @param b Second Light object to compare first.
  19100. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19101. */
  19102. Light.CompareLightsPriority = function (a, b) {
  19103. //shadow-casting lights have priority over non-shadow-casting lights
  19104. //the renderPrioirty is a secondary sort criterion
  19105. if (a.shadowEnabled !== b.shadowEnabled) {
  19106. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19107. }
  19108. return b.renderPriority - a.renderPriority;
  19109. };
  19110. /**
  19111. * Disposes the light.
  19112. */
  19113. Light.prototype.dispose = function () {
  19114. if (this._shadowGenerator) {
  19115. this._shadowGenerator.dispose();
  19116. this._shadowGenerator = null;
  19117. }
  19118. // Animations
  19119. this.getScene().stopAnimation(this);
  19120. // Remove from meshes
  19121. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19122. var mesh = _a[_i];
  19123. mesh._removeLightSource(this);
  19124. }
  19125. this._uniformBuffer.dispose();
  19126. // Remove from scene
  19127. this.getScene().removeLight(this);
  19128. _super.prototype.dispose.call(this);
  19129. };
  19130. /**
  19131. * Returns the light type ID (integer).
  19132. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19133. */
  19134. Light.prototype.getTypeID = function () {
  19135. return 0;
  19136. };
  19137. /**
  19138. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19139. * @returns the scaled intensity in intensity mode unit
  19140. */
  19141. Light.prototype.getScaledIntensity = function () {
  19142. return this._photometricScale * this.intensity;
  19143. };
  19144. /**
  19145. * Returns a new Light object, named "name", from the current one.
  19146. * @param name The name of the cloned light
  19147. * @returns the new created light
  19148. */
  19149. Light.prototype.clone = function (name) {
  19150. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19151. if (!constructor) {
  19152. return null;
  19153. }
  19154. return BABYLON.SerializationHelper.Clone(constructor, this);
  19155. };
  19156. /**
  19157. * Serializes the current light into a Serialization object.
  19158. * @returns the serialized object.
  19159. */
  19160. Light.prototype.serialize = function () {
  19161. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19162. // Type
  19163. serializationObject.type = this.getTypeID();
  19164. // Parent
  19165. if (this.parent) {
  19166. serializationObject.parentId = this.parent.id;
  19167. }
  19168. // Inclusion / exclusions
  19169. if (this.excludedMeshes.length > 0) {
  19170. serializationObject.excludedMeshesIds = [];
  19171. this.excludedMeshes.forEach(function (mesh) {
  19172. serializationObject.excludedMeshesIds.push(mesh.id);
  19173. });
  19174. }
  19175. if (this.includedOnlyMeshes.length > 0) {
  19176. serializationObject.includedOnlyMeshesIds = [];
  19177. this.includedOnlyMeshes.forEach(function (mesh) {
  19178. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19179. });
  19180. }
  19181. // Animations
  19182. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19183. serializationObject.ranges = this.serializeAnimationRanges();
  19184. return serializationObject;
  19185. };
  19186. /**
  19187. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19188. * This new light is named "name" and added to the passed scene.
  19189. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19190. * @param name The friendly name of the light
  19191. * @param scene The scene the new light will belong to
  19192. * @returns the constructor function
  19193. */
  19194. Light.GetConstructorFromName = function (type, name, scene) {
  19195. switch (type) {
  19196. case 0:
  19197. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19198. case 1:
  19199. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19200. case 2:
  19201. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19202. case 3:
  19203. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19204. }
  19205. return null;
  19206. };
  19207. /**
  19208. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19209. * @param parsedLight The JSON representation of the light
  19210. * @param scene The scene to create the parsed light in
  19211. * @returns the created light after parsing
  19212. */
  19213. Light.Parse = function (parsedLight, scene) {
  19214. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19215. if (!constructor) {
  19216. return null;
  19217. }
  19218. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19219. // Inclusion / exclusions
  19220. if (parsedLight.excludedMeshesIds) {
  19221. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19222. }
  19223. if (parsedLight.includedOnlyMeshesIds) {
  19224. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19225. }
  19226. // Parent
  19227. if (parsedLight.parentId) {
  19228. light._waitingParentId = parsedLight.parentId;
  19229. }
  19230. // Animations
  19231. if (parsedLight.animations) {
  19232. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19233. var parsedAnimation = parsedLight.animations[animationIndex];
  19234. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19235. }
  19236. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19237. }
  19238. if (parsedLight.autoAnimate) {
  19239. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19240. }
  19241. return light;
  19242. };
  19243. Light.prototype._hookArrayForExcluded = function (array) {
  19244. var _this = this;
  19245. var oldPush = array.push;
  19246. array.push = function () {
  19247. var items = [];
  19248. for (var _i = 0; _i < arguments.length; _i++) {
  19249. items[_i] = arguments[_i];
  19250. }
  19251. var result = oldPush.apply(array, items);
  19252. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19253. var item = items_1[_a];
  19254. item._resyncLighSource(_this);
  19255. }
  19256. return result;
  19257. };
  19258. var oldSplice = array.splice;
  19259. array.splice = function (index, deleteCount) {
  19260. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19261. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19262. var item = deleted_1[_i];
  19263. item._resyncLighSource(_this);
  19264. }
  19265. return deleted;
  19266. };
  19267. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19268. var item = array_1[_i];
  19269. item._resyncLighSource(this);
  19270. }
  19271. };
  19272. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19273. var _this = this;
  19274. var oldPush = array.push;
  19275. array.push = function () {
  19276. var items = [];
  19277. for (var _i = 0; _i < arguments.length; _i++) {
  19278. items[_i] = arguments[_i];
  19279. }
  19280. var result = oldPush.apply(array, items);
  19281. _this._resyncMeshes();
  19282. return result;
  19283. };
  19284. var oldSplice = array.splice;
  19285. array.splice = function (index, deleteCount) {
  19286. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19287. _this._resyncMeshes();
  19288. return deleted;
  19289. };
  19290. this._resyncMeshes();
  19291. };
  19292. Light.prototype._resyncMeshes = function () {
  19293. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19294. var mesh = _a[_i];
  19295. mesh._resyncLighSource(this);
  19296. }
  19297. };
  19298. /**
  19299. * Forces the meshes to update their light related information in their rendering used effects
  19300. * @ignore Internal Use Only
  19301. */
  19302. Light.prototype._markMeshesAsLightDirty = function () {
  19303. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19304. var mesh = _a[_i];
  19305. if (mesh._lightSources.indexOf(this) !== -1) {
  19306. mesh._markSubMeshesAsLightDirty();
  19307. }
  19308. }
  19309. };
  19310. /**
  19311. * Recomputes the cached photometric scale if needed.
  19312. */
  19313. Light.prototype._computePhotometricScale = function () {
  19314. this._photometricScale = this._getPhotometricScale();
  19315. this.getScene().resetCachedMaterial();
  19316. };
  19317. /**
  19318. * Returns the Photometric Scale according to the light type and intensity mode.
  19319. */
  19320. Light.prototype._getPhotometricScale = function () {
  19321. var photometricScale = 0.0;
  19322. var lightTypeID = this.getTypeID();
  19323. //get photometric mode
  19324. var photometricMode = this.intensityMode;
  19325. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19326. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19327. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19328. }
  19329. else {
  19330. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19331. }
  19332. }
  19333. //compute photometric scale
  19334. switch (lightTypeID) {
  19335. case Light.LIGHTTYPEID_POINTLIGHT:
  19336. case Light.LIGHTTYPEID_SPOTLIGHT:
  19337. switch (photometricMode) {
  19338. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19339. photometricScale = 1.0 / (4.0 * Math.PI);
  19340. break;
  19341. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19342. photometricScale = 1.0;
  19343. break;
  19344. case Light.INTENSITYMODE_LUMINANCE:
  19345. photometricScale = this.radius * this.radius;
  19346. break;
  19347. }
  19348. break;
  19349. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19350. switch (photometricMode) {
  19351. case Light.INTENSITYMODE_ILLUMINANCE:
  19352. photometricScale = 1.0;
  19353. break;
  19354. case Light.INTENSITYMODE_LUMINANCE:
  19355. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19356. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19357. var apexAngleRadians = this.radius;
  19358. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19359. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19360. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19361. photometricScale = solidAngle;
  19362. break;
  19363. }
  19364. break;
  19365. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19366. // No fall off in hemisperic light.
  19367. photometricScale = 1.0;
  19368. break;
  19369. }
  19370. return photometricScale;
  19371. };
  19372. /**
  19373. * Reorder the light in the scene according to their defined priority.
  19374. * @ignore Internal Use Only
  19375. */
  19376. Light.prototype._reorderLightsInScene = function () {
  19377. var scene = this.getScene();
  19378. if (this._renderPriority != 0) {
  19379. scene.requireLightSorting = true;
  19380. }
  19381. this.getScene().sortLightsByPriority();
  19382. };
  19383. //lightmapMode Consts
  19384. Light._LIGHTMAP_DEFAULT = 0;
  19385. Light._LIGHTMAP_SPECULAR = 1;
  19386. Light._LIGHTMAP_SHADOWSONLY = 2;
  19387. // Intensity Mode Consts
  19388. Light._INTENSITYMODE_AUTOMATIC = 0;
  19389. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19390. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19391. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19392. Light._INTENSITYMODE_LUMINANCE = 4;
  19393. // Light types ids const.
  19394. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19395. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19396. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19397. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19398. __decorate([
  19399. BABYLON.serializeAsColor3()
  19400. ], Light.prototype, "diffuse", void 0);
  19401. __decorate([
  19402. BABYLON.serializeAsColor3()
  19403. ], Light.prototype, "specular", void 0);
  19404. __decorate([
  19405. BABYLON.serialize()
  19406. ], Light.prototype, "intensity", void 0);
  19407. __decorate([
  19408. BABYLON.serialize()
  19409. ], Light.prototype, "range", void 0);
  19410. __decorate([
  19411. BABYLON.serialize()
  19412. ], Light.prototype, "intensityMode", null);
  19413. __decorate([
  19414. BABYLON.serialize()
  19415. ], Light.prototype, "radius", null);
  19416. __decorate([
  19417. BABYLON.serialize()
  19418. ], Light.prototype, "_renderPriority", void 0);
  19419. __decorate([
  19420. BABYLON.expandToProperty("_reorderLightsInScene")
  19421. ], Light.prototype, "renderPriority", void 0);
  19422. __decorate([
  19423. BABYLON.serialize()
  19424. ], Light.prototype, "shadowEnabled", void 0);
  19425. __decorate([
  19426. BABYLON.serialize("excludeWithLayerMask")
  19427. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19428. __decorate([
  19429. BABYLON.serialize("includeOnlyWithLayerMask")
  19430. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19431. __decorate([
  19432. BABYLON.serialize("lightmapMode")
  19433. ], Light.prototype, "_lightmapMode", void 0);
  19434. return Light;
  19435. }(BABYLON.Node));
  19436. BABYLON.Light = Light;
  19437. })(BABYLON || (BABYLON = {}));
  19438. //# sourceMappingURL=babylon.light.js.map
  19439. var BABYLON;
  19440. (function (BABYLON) {
  19441. var Camera = /** @class */ (function (_super) {
  19442. __extends(Camera, _super);
  19443. function Camera(name, position, scene) {
  19444. var _this = _super.call(this, name, scene) || this;
  19445. /**
  19446. * The vector the camera should consider as up.
  19447. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19448. */
  19449. _this.upVector = BABYLON.Vector3.Up();
  19450. _this.orthoLeft = null;
  19451. _this.orthoRight = null;
  19452. _this.orthoBottom = null;
  19453. _this.orthoTop = null;
  19454. /**
  19455. * FOV is set in Radians. (default is 0.8)
  19456. */
  19457. _this.fov = 0.8;
  19458. _this.minZ = 1;
  19459. _this.maxZ = 10000.0;
  19460. _this.inertia = 0.9;
  19461. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19462. _this.isIntermediate = false;
  19463. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19464. /**
  19465. * Restricts the camera to viewing objects with the same layerMask.
  19466. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19467. */
  19468. _this.layerMask = 0x0FFFFFFF;
  19469. /**
  19470. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19471. */
  19472. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19473. // Camera rig members
  19474. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19475. _this._rigCameras = new Array();
  19476. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19477. _this._skipRendering = false;
  19478. _this.customRenderTargets = new Array();
  19479. // Observables
  19480. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19481. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19482. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19483. _this.onRestoreStateObservable = new BABYLON.Observable();
  19484. // Cache
  19485. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19486. _this._projectionMatrix = new BABYLON.Matrix();
  19487. _this._doNotComputeProjectionMatrix = false;
  19488. _this._postProcesses = new Array();
  19489. _this._transformMatrix = BABYLON.Matrix.Zero();
  19490. _this._activeMeshes = new BABYLON.SmartArray(256);
  19491. _this._globalPosition = BABYLON.Vector3.Zero();
  19492. _this._refreshFrustumPlanes = true;
  19493. _this.getScene().addCamera(_this);
  19494. if (!_this.getScene().activeCamera) {
  19495. _this.getScene().activeCamera = _this;
  19496. }
  19497. _this.position = position;
  19498. return _this;
  19499. }
  19500. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19501. get: function () {
  19502. return Camera._PERSPECTIVE_CAMERA;
  19503. },
  19504. enumerable: true,
  19505. configurable: true
  19506. });
  19507. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19508. get: function () {
  19509. return Camera._ORTHOGRAPHIC_CAMERA;
  19510. },
  19511. enumerable: true,
  19512. configurable: true
  19513. });
  19514. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19515. /**
  19516. * This is the default FOV mode for perspective cameras.
  19517. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19518. *
  19519. */
  19520. get: function () {
  19521. return Camera._FOVMODE_VERTICAL_FIXED;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19527. /**
  19528. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19529. *
  19530. */
  19531. get: function () {
  19532. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19533. },
  19534. enumerable: true,
  19535. configurable: true
  19536. });
  19537. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19538. get: function () {
  19539. return Camera._RIG_MODE_NONE;
  19540. },
  19541. enumerable: true,
  19542. configurable: true
  19543. });
  19544. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19545. get: function () {
  19546. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19547. },
  19548. enumerable: true,
  19549. configurable: true
  19550. });
  19551. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19552. get: function () {
  19553. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19554. },
  19555. enumerable: true,
  19556. configurable: true
  19557. });
  19558. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19559. get: function () {
  19560. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19561. },
  19562. enumerable: true,
  19563. configurable: true
  19564. });
  19565. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19566. get: function () {
  19567. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19568. },
  19569. enumerable: true,
  19570. configurable: true
  19571. });
  19572. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19573. get: function () {
  19574. return Camera._RIG_MODE_VR;
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19580. get: function () {
  19581. return Camera._RIG_MODE_WEBVR;
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. /**
  19587. * Store current camera state (fov, position, etc..)
  19588. */
  19589. Camera.prototype.storeState = function () {
  19590. this._stateStored = true;
  19591. this._storedFov = this.fov;
  19592. return this;
  19593. };
  19594. /**
  19595. * Restores the camera state values if it has been stored. You must call storeState() first
  19596. */
  19597. Camera.prototype._restoreStateValues = function () {
  19598. if (!this._stateStored) {
  19599. return false;
  19600. }
  19601. this.fov = this._storedFov;
  19602. return true;
  19603. };
  19604. /**
  19605. * Restored camera state. You must call storeState() first
  19606. */
  19607. Camera.prototype.restoreState = function () {
  19608. if (this._restoreStateValues()) {
  19609. this.onRestoreStateObservable.notifyObservers(this);
  19610. return true;
  19611. }
  19612. return false;
  19613. };
  19614. Camera.prototype.getClassName = function () {
  19615. return "Camera";
  19616. };
  19617. /**
  19618. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19619. */
  19620. Camera.prototype.toString = function (fullDetails) {
  19621. var ret = "Name: " + this.name;
  19622. ret += ", type: " + this.getClassName();
  19623. if (this.animations) {
  19624. for (var i = 0; i < this.animations.length; i++) {
  19625. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19626. }
  19627. }
  19628. if (fullDetails) {
  19629. }
  19630. return ret;
  19631. };
  19632. Object.defineProperty(Camera.prototype, "globalPosition", {
  19633. get: function () {
  19634. return this._globalPosition;
  19635. },
  19636. enumerable: true,
  19637. configurable: true
  19638. });
  19639. Camera.prototype.getActiveMeshes = function () {
  19640. return this._activeMeshes;
  19641. };
  19642. Camera.prototype.isActiveMesh = function (mesh) {
  19643. return (this._activeMeshes.indexOf(mesh) !== -1);
  19644. };
  19645. //Cache
  19646. Camera.prototype._initCache = function () {
  19647. _super.prototype._initCache.call(this);
  19648. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19649. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19650. this._cache.mode = undefined;
  19651. this._cache.minZ = undefined;
  19652. this._cache.maxZ = undefined;
  19653. this._cache.fov = undefined;
  19654. this._cache.fovMode = undefined;
  19655. this._cache.aspectRatio = undefined;
  19656. this._cache.orthoLeft = undefined;
  19657. this._cache.orthoRight = undefined;
  19658. this._cache.orthoBottom = undefined;
  19659. this._cache.orthoTop = undefined;
  19660. this._cache.renderWidth = undefined;
  19661. this._cache.renderHeight = undefined;
  19662. };
  19663. Camera.prototype._updateCache = function (ignoreParentClass) {
  19664. if (!ignoreParentClass) {
  19665. _super.prototype._updateCache.call(this);
  19666. }
  19667. this._cache.position.copyFrom(this.position);
  19668. this._cache.upVector.copyFrom(this.upVector);
  19669. };
  19670. // Synchronized
  19671. Camera.prototype._isSynchronized = function () {
  19672. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19673. };
  19674. Camera.prototype._isSynchronizedViewMatrix = function () {
  19675. if (!_super.prototype._isSynchronized.call(this))
  19676. return false;
  19677. return this._cache.position.equals(this.position)
  19678. && this._cache.upVector.equals(this.upVector)
  19679. && this.isSynchronizedWithParent();
  19680. };
  19681. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19682. var check = this._cache.mode === this.mode
  19683. && this._cache.minZ === this.minZ
  19684. && this._cache.maxZ === this.maxZ;
  19685. if (!check) {
  19686. return false;
  19687. }
  19688. var engine = this.getEngine();
  19689. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19690. check = this._cache.fov === this.fov
  19691. && this._cache.fovMode === this.fovMode
  19692. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19693. }
  19694. else {
  19695. check = this._cache.orthoLeft === this.orthoLeft
  19696. && this._cache.orthoRight === this.orthoRight
  19697. && this._cache.orthoBottom === this.orthoBottom
  19698. && this._cache.orthoTop === this.orthoTop
  19699. && this._cache.renderWidth === engine.getRenderWidth()
  19700. && this._cache.renderHeight === engine.getRenderHeight();
  19701. }
  19702. return check;
  19703. };
  19704. // Controls
  19705. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19706. };
  19707. Camera.prototype.detachControl = function (element) {
  19708. };
  19709. Camera.prototype.update = function () {
  19710. this._checkInputs();
  19711. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19712. this._updateRigCameras();
  19713. }
  19714. };
  19715. Camera.prototype._checkInputs = function () {
  19716. this.onAfterCheckInputsObservable.notifyObservers(this);
  19717. };
  19718. Object.defineProperty(Camera.prototype, "rigCameras", {
  19719. get: function () {
  19720. return this._rigCameras;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19726. get: function () {
  19727. return this._rigPostProcess;
  19728. },
  19729. enumerable: true,
  19730. configurable: true
  19731. });
  19732. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19733. // invalidate framebuffer
  19734. if (this._postProcesses.length > 0) {
  19735. this._postProcesses[0].markTextureDirty();
  19736. }
  19737. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19738. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19739. var cam = this._rigCameras[i];
  19740. var rigPostProcess = cam._rigPostProcess;
  19741. // for VR rig, there does not have to be a post process
  19742. if (rigPostProcess) {
  19743. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19744. if (isPass) {
  19745. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19746. cam.isIntermediate = this._postProcesses.length === 0;
  19747. }
  19748. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19749. rigPostProcess.markTextureDirty();
  19750. }
  19751. else {
  19752. cam._postProcesses = this._postProcesses.slice(0);
  19753. }
  19754. }
  19755. };
  19756. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19757. if (insertAt === void 0) { insertAt = null; }
  19758. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19759. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19760. return 0;
  19761. }
  19762. if (insertAt == null || insertAt < 0) {
  19763. this._postProcesses.push(postProcess);
  19764. }
  19765. else {
  19766. this._postProcesses.splice(insertAt, 0, postProcess);
  19767. }
  19768. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19769. return this._postProcesses.indexOf(postProcess);
  19770. };
  19771. Camera.prototype.detachPostProcess = function (postProcess) {
  19772. var idx = this._postProcesses.indexOf(postProcess);
  19773. if (idx !== -1) {
  19774. this._postProcesses.splice(idx, 1);
  19775. }
  19776. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19777. };
  19778. Camera.prototype.getWorldMatrix = function () {
  19779. if (!this._worldMatrix) {
  19780. this._worldMatrix = BABYLON.Matrix.Identity();
  19781. }
  19782. var viewMatrix = this.getViewMatrix();
  19783. viewMatrix.invertToRef(this._worldMatrix);
  19784. return this._worldMatrix;
  19785. };
  19786. Camera.prototype._getViewMatrix = function () {
  19787. return BABYLON.Matrix.Identity();
  19788. };
  19789. Camera.prototype.getViewMatrix = function (force) {
  19790. if (!force && this._isSynchronizedViewMatrix()) {
  19791. return this._computedViewMatrix;
  19792. }
  19793. this.updateCache();
  19794. this._computedViewMatrix = this._getViewMatrix();
  19795. this._currentRenderId = this.getScene().getRenderId();
  19796. this._refreshFrustumPlanes = true;
  19797. if (!this.parent || !this.parent.getWorldMatrix) {
  19798. this._globalPosition.copyFrom(this.position);
  19799. }
  19800. else {
  19801. if (!this._worldMatrix) {
  19802. this._worldMatrix = BABYLON.Matrix.Identity();
  19803. }
  19804. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19805. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19806. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19807. this._computedViewMatrix.invert();
  19808. this._markSyncedWithParent();
  19809. }
  19810. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19811. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19812. }
  19813. this.onViewMatrixChangedObservable.notifyObservers(this);
  19814. return this._computedViewMatrix;
  19815. };
  19816. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19817. this._doNotComputeProjectionMatrix = true;
  19818. if (projection !== undefined) {
  19819. this._projectionMatrix = projection;
  19820. }
  19821. };
  19822. ;
  19823. Camera.prototype.unfreezeProjectionMatrix = function () {
  19824. this._doNotComputeProjectionMatrix = false;
  19825. };
  19826. ;
  19827. Camera.prototype.getProjectionMatrix = function (force) {
  19828. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19829. return this._projectionMatrix;
  19830. }
  19831. // Cache
  19832. this._cache.mode = this.mode;
  19833. this._cache.minZ = this.minZ;
  19834. this._cache.maxZ = this.maxZ;
  19835. // Matrix
  19836. this._refreshFrustumPlanes = true;
  19837. var engine = this.getEngine();
  19838. var scene = this.getScene();
  19839. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19840. this._cache.fov = this.fov;
  19841. this._cache.fovMode = this.fovMode;
  19842. this._cache.aspectRatio = engine.getAspectRatio(this);
  19843. if (this.minZ <= 0) {
  19844. this.minZ = 0.1;
  19845. }
  19846. if (scene.useRightHandedSystem) {
  19847. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19848. }
  19849. else {
  19850. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19851. }
  19852. }
  19853. else {
  19854. var halfWidth = engine.getRenderWidth() / 2.0;
  19855. var halfHeight = engine.getRenderHeight() / 2.0;
  19856. if (scene.useRightHandedSystem) {
  19857. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19858. }
  19859. else {
  19860. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19861. }
  19862. this._cache.orthoLeft = this.orthoLeft;
  19863. this._cache.orthoRight = this.orthoRight;
  19864. this._cache.orthoBottom = this.orthoBottom;
  19865. this._cache.orthoTop = this.orthoTop;
  19866. this._cache.renderWidth = engine.getRenderWidth();
  19867. this._cache.renderHeight = engine.getRenderHeight();
  19868. }
  19869. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19870. return this._projectionMatrix;
  19871. };
  19872. Camera.prototype.getTranformationMatrix = function () {
  19873. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19874. return this._transformMatrix;
  19875. };
  19876. Camera.prototype.updateFrustumPlanes = function () {
  19877. if (!this._refreshFrustumPlanes) {
  19878. return;
  19879. }
  19880. this.getTranformationMatrix();
  19881. if (!this._frustumPlanes) {
  19882. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19883. }
  19884. else {
  19885. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19886. }
  19887. this._refreshFrustumPlanes = false;
  19888. };
  19889. Camera.prototype.isInFrustum = function (target) {
  19890. this.updateFrustumPlanes();
  19891. return target.isInFrustum(this._frustumPlanes);
  19892. };
  19893. Camera.prototype.isCompletelyInFrustum = function (target) {
  19894. this.updateFrustumPlanes();
  19895. return target.isCompletelyInFrustum(this._frustumPlanes);
  19896. };
  19897. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19898. if (length === void 0) { length = 100; }
  19899. if (!transform) {
  19900. transform = this.getWorldMatrix();
  19901. }
  19902. if (!origin) {
  19903. origin = this.position;
  19904. }
  19905. var forward = new BABYLON.Vector3(0, 0, 1);
  19906. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19907. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19908. return new BABYLON.Ray(origin, direction, length);
  19909. };
  19910. Camera.prototype.dispose = function () {
  19911. // Observables
  19912. this.onViewMatrixChangedObservable.clear();
  19913. this.onProjectionMatrixChangedObservable.clear();
  19914. this.onAfterCheckInputsObservable.clear();
  19915. this.onRestoreStateObservable.clear();
  19916. // Inputs
  19917. if (this.inputs) {
  19918. this.inputs.clear();
  19919. }
  19920. // Animations
  19921. this.getScene().stopAnimation(this);
  19922. // Remove from scene
  19923. this.getScene().removeCamera(this);
  19924. while (this._rigCameras.length > 0) {
  19925. var camera = this._rigCameras.pop();
  19926. if (camera) {
  19927. camera.dispose();
  19928. }
  19929. }
  19930. // Postprocesses
  19931. if (this._rigPostProcess) {
  19932. this._rigPostProcess.dispose(this);
  19933. this._rigPostProcess = null;
  19934. this._postProcesses = [];
  19935. }
  19936. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19937. this._rigPostProcess = null;
  19938. this._postProcesses = [];
  19939. }
  19940. else {
  19941. var i = this._postProcesses.length;
  19942. while (--i >= 0) {
  19943. this._postProcesses[i].dispose(this);
  19944. }
  19945. }
  19946. // Render targets
  19947. var i = this.customRenderTargets.length;
  19948. while (--i >= 0) {
  19949. this.customRenderTargets[i].dispose();
  19950. }
  19951. this.customRenderTargets = [];
  19952. // Active Meshes
  19953. this._activeMeshes.dispose();
  19954. _super.prototype.dispose.call(this);
  19955. };
  19956. Object.defineProperty(Camera.prototype, "leftCamera", {
  19957. // ---- Camera rigs section ----
  19958. get: function () {
  19959. if (this._rigCameras.length < 1) {
  19960. return null;
  19961. }
  19962. return this._rigCameras[0];
  19963. },
  19964. enumerable: true,
  19965. configurable: true
  19966. });
  19967. Object.defineProperty(Camera.prototype, "rightCamera", {
  19968. get: function () {
  19969. if (this._rigCameras.length < 2) {
  19970. return null;
  19971. }
  19972. return this._rigCameras[1];
  19973. },
  19974. enumerable: true,
  19975. configurable: true
  19976. });
  19977. Camera.prototype.getLeftTarget = function () {
  19978. if (this._rigCameras.length < 1) {
  19979. return null;
  19980. }
  19981. return this._rigCameras[0].getTarget();
  19982. };
  19983. Camera.prototype.getRightTarget = function () {
  19984. if (this._rigCameras.length < 2) {
  19985. return null;
  19986. }
  19987. return this._rigCameras[1].getTarget();
  19988. };
  19989. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19990. if (this.cameraRigMode === mode) {
  19991. return;
  19992. }
  19993. while (this._rigCameras.length > 0) {
  19994. var camera = this._rigCameras.pop();
  19995. if (camera) {
  19996. camera.dispose();
  19997. }
  19998. }
  19999. this.cameraRigMode = mode;
  20000. this._cameraRigParams = {};
  20001. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20002. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20003. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20004. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20005. // create the rig cameras, unless none
  20006. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20007. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20008. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20009. if (leftCamera && rightCamera) {
  20010. this._rigCameras.push(leftCamera);
  20011. this._rigCameras.push(rightCamera);
  20012. }
  20013. }
  20014. switch (this.cameraRigMode) {
  20015. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20016. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20017. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20018. break;
  20019. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20020. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20021. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20022. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20023. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20024. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20025. break;
  20026. case Camera.RIG_MODE_VR:
  20027. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20028. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20029. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20030. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20031. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20032. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20033. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20034. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20035. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20036. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20037. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20038. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20039. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20040. if (metrics.compensateDistortion) {
  20041. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20042. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20043. }
  20044. break;
  20045. case Camera.RIG_MODE_WEBVR:
  20046. if (rigParams.vrDisplay) {
  20047. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20048. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20049. //Left eye
  20050. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20051. this._rigCameras[0].setCameraRigParameter("left", true);
  20052. //leaving this for future reference
  20053. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20054. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20055. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20056. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20057. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20058. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20059. this._rigCameras[0].parent = this;
  20060. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20061. //Right eye
  20062. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20063. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20064. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20065. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20066. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20067. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20068. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20069. this._rigCameras[1].parent = this;
  20070. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20071. if (Camera.UseAlternateWebVRRendering) {
  20072. this._rigCameras[1]._skipRendering = true;
  20073. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20074. }
  20075. }
  20076. break;
  20077. }
  20078. this._cascadePostProcessesToRigCams();
  20079. this.update();
  20080. };
  20081. Camera.prototype._getVRProjectionMatrix = function () {
  20082. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20083. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20084. return this._projectionMatrix;
  20085. };
  20086. Camera.prototype._updateCameraRotationMatrix = function () {
  20087. //Here for WebVR
  20088. };
  20089. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20090. //Here for WebVR
  20091. };
  20092. /**
  20093. * This function MUST be overwritten by the different WebVR cameras available.
  20094. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20095. */
  20096. Camera.prototype._getWebVRProjectionMatrix = function () {
  20097. return BABYLON.Matrix.Identity();
  20098. };
  20099. /**
  20100. * This function MUST be overwritten by the different WebVR cameras available.
  20101. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20102. */
  20103. Camera.prototype._getWebVRViewMatrix = function () {
  20104. return BABYLON.Matrix.Identity();
  20105. };
  20106. Camera.prototype.setCameraRigParameter = function (name, value) {
  20107. if (!this._cameraRigParams) {
  20108. this._cameraRigParams = {};
  20109. }
  20110. this._cameraRigParams[name] = value;
  20111. //provisionnally:
  20112. if (name === "interaxialDistance") {
  20113. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20114. }
  20115. };
  20116. /**
  20117. * needs to be overridden by children so sub has required properties to be copied
  20118. */
  20119. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20120. return null;
  20121. };
  20122. /**
  20123. * May need to be overridden by children
  20124. */
  20125. Camera.prototype._updateRigCameras = function () {
  20126. for (var i = 0; i < this._rigCameras.length; i++) {
  20127. this._rigCameras[i].minZ = this.minZ;
  20128. this._rigCameras[i].maxZ = this.maxZ;
  20129. this._rigCameras[i].fov = this.fov;
  20130. }
  20131. // only update viewport when ANAGLYPH
  20132. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20133. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20134. }
  20135. };
  20136. Camera.prototype._setupInputs = function () {
  20137. };
  20138. Camera.prototype.serialize = function () {
  20139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20140. // Type
  20141. serializationObject.type = this.getClassName();
  20142. // Parent
  20143. if (this.parent) {
  20144. serializationObject.parentId = this.parent.id;
  20145. }
  20146. if (this.inputs) {
  20147. this.inputs.serialize(serializationObject);
  20148. }
  20149. // Animations
  20150. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20151. serializationObject.ranges = this.serializeAnimationRanges();
  20152. return serializationObject;
  20153. };
  20154. Camera.prototype.clone = function (name) {
  20155. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20156. };
  20157. Camera.prototype.getDirection = function (localAxis) {
  20158. var result = BABYLON.Vector3.Zero();
  20159. this.getDirectionToRef(localAxis, result);
  20160. return result;
  20161. };
  20162. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20163. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20164. };
  20165. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20166. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20167. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20168. switch (type) {
  20169. case "ArcRotateCamera":
  20170. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20171. case "DeviceOrientationCamera":
  20172. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20173. case "FollowCamera":
  20174. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20175. case "ArcFollowCamera":
  20176. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20177. case "GamepadCamera":
  20178. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20179. case "TouchCamera":
  20180. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20181. case "VirtualJoysticksCamera":
  20182. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20183. case "WebVRFreeCamera":
  20184. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20185. case "WebVRGamepadCamera":
  20186. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20187. case "VRDeviceOrientationFreeCamera":
  20188. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20189. case "VRDeviceOrientationGamepadCamera":
  20190. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20191. case "AnaglyphArcRotateCamera":
  20192. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20193. case "AnaglyphFreeCamera":
  20194. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20195. case "AnaglyphGamepadCamera":
  20196. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20197. case "AnaglyphUniversalCamera":
  20198. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20199. case "StereoscopicArcRotateCamera":
  20200. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20201. case "StereoscopicFreeCamera":
  20202. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20203. case "StereoscopicGamepadCamera":
  20204. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20205. case "StereoscopicUniversalCamera":
  20206. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20207. case "FreeCamera":// Forcing Universal here
  20208. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20209. default:// Universal Camera is the default value
  20210. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20211. }
  20212. };
  20213. Camera.prototype.computeWorldMatrix = function () {
  20214. return this.getWorldMatrix();
  20215. };
  20216. Camera.Parse = function (parsedCamera, scene) {
  20217. var type = parsedCamera.type;
  20218. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20219. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20220. // Parent
  20221. if (parsedCamera.parentId) {
  20222. camera._waitingParentId = parsedCamera.parentId;
  20223. }
  20224. //If camera has an input manager, let it parse inputs settings
  20225. if (camera.inputs) {
  20226. camera.inputs.parse(parsedCamera);
  20227. camera._setupInputs();
  20228. }
  20229. if (camera.setPosition) {
  20230. camera.position.copyFromFloats(0, 0, 0);
  20231. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20232. }
  20233. // Target
  20234. if (parsedCamera.target) {
  20235. if (camera.setTarget) {
  20236. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20237. }
  20238. }
  20239. // Apply 3d rig, when found
  20240. if (parsedCamera.cameraRigMode) {
  20241. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20242. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20243. }
  20244. // Animations
  20245. if (parsedCamera.animations) {
  20246. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20247. var parsedAnimation = parsedCamera.animations[animationIndex];
  20248. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20249. }
  20250. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20251. }
  20252. if (parsedCamera.autoAnimate) {
  20253. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20254. }
  20255. return camera;
  20256. };
  20257. // Statics
  20258. Camera._PERSPECTIVE_CAMERA = 0;
  20259. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20260. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20261. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20262. Camera._RIG_MODE_NONE = 0;
  20263. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20264. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20265. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20266. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20267. Camera._RIG_MODE_VR = 20;
  20268. Camera._RIG_MODE_WEBVR = 21;
  20269. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20270. Camera.UseAlternateWebVRRendering = false;
  20271. __decorate([
  20272. BABYLON.serializeAsVector3()
  20273. ], Camera.prototype, "position", void 0);
  20274. __decorate([
  20275. BABYLON.serializeAsVector3()
  20276. ], Camera.prototype, "upVector", void 0);
  20277. __decorate([
  20278. BABYLON.serialize()
  20279. ], Camera.prototype, "orthoLeft", void 0);
  20280. __decorate([
  20281. BABYLON.serialize()
  20282. ], Camera.prototype, "orthoRight", void 0);
  20283. __decorate([
  20284. BABYLON.serialize()
  20285. ], Camera.prototype, "orthoBottom", void 0);
  20286. __decorate([
  20287. BABYLON.serialize()
  20288. ], Camera.prototype, "orthoTop", void 0);
  20289. __decorate([
  20290. BABYLON.serialize()
  20291. ], Camera.prototype, "fov", void 0);
  20292. __decorate([
  20293. BABYLON.serialize()
  20294. ], Camera.prototype, "minZ", void 0);
  20295. __decorate([
  20296. BABYLON.serialize()
  20297. ], Camera.prototype, "maxZ", void 0);
  20298. __decorate([
  20299. BABYLON.serialize()
  20300. ], Camera.prototype, "inertia", void 0);
  20301. __decorate([
  20302. BABYLON.serialize()
  20303. ], Camera.prototype, "mode", void 0);
  20304. __decorate([
  20305. BABYLON.serialize()
  20306. ], Camera.prototype, "layerMask", void 0);
  20307. __decorate([
  20308. BABYLON.serialize()
  20309. ], Camera.prototype, "fovMode", void 0);
  20310. __decorate([
  20311. BABYLON.serialize()
  20312. ], Camera.prototype, "cameraRigMode", void 0);
  20313. __decorate([
  20314. BABYLON.serialize()
  20315. ], Camera.prototype, "interaxialDistance", void 0);
  20316. __decorate([
  20317. BABYLON.serialize()
  20318. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20319. return Camera;
  20320. }(BABYLON.Node));
  20321. BABYLON.Camera = Camera;
  20322. })(BABYLON || (BABYLON = {}));
  20323. //# sourceMappingURL=babylon.camera.js.map
  20324. var BABYLON;
  20325. (function (BABYLON) {
  20326. var RenderingManager = /** @class */ (function () {
  20327. function RenderingManager(scene) {
  20328. this._renderingGroups = new Array();
  20329. this._autoClearDepthStencil = {};
  20330. this._customOpaqueSortCompareFn = {};
  20331. this._customAlphaTestSortCompareFn = {};
  20332. this._customTransparentSortCompareFn = {};
  20333. this._renderinGroupInfo = null;
  20334. this._scene = scene;
  20335. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20336. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20337. }
  20338. }
  20339. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20340. if (depth === void 0) { depth = true; }
  20341. if (stencil === void 0) { stencil = true; }
  20342. if (this._depthStencilBufferAlreadyCleaned) {
  20343. return;
  20344. }
  20345. this._scene.getEngine().clear(null, false, depth, stencil);
  20346. this._depthStencilBufferAlreadyCleaned = true;
  20347. };
  20348. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20349. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20350. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20351. var info = null;
  20352. if (observable) {
  20353. if (!this._renderinGroupInfo) {
  20354. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20355. }
  20356. info = this._renderinGroupInfo;
  20357. info.scene = this._scene;
  20358. info.camera = this._scene.activeCamera;
  20359. }
  20360. // Dispatch sprites
  20361. if (renderSprites) {
  20362. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20363. var manager = this._scene.spriteManagers[index];
  20364. this.dispatchSprites(manager);
  20365. }
  20366. }
  20367. // Render
  20368. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20369. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20370. var renderingGroup = this._renderingGroups[index];
  20371. if (!renderingGroup && !observable)
  20372. continue;
  20373. var renderingGroupMask = 0;
  20374. // Fire PRECLEAR stage
  20375. if (observable && info) {
  20376. renderingGroupMask = Math.pow(2, index);
  20377. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20378. info.renderingGroupId = index;
  20379. observable.notifyObservers(info, renderingGroupMask);
  20380. }
  20381. // Clear depth/stencil if needed
  20382. if (RenderingManager.AUTOCLEAR) {
  20383. var autoClear = this._autoClearDepthStencil[index];
  20384. if (autoClear && autoClear.autoClear) {
  20385. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20386. }
  20387. }
  20388. if (observable && info) {
  20389. // Fire PREOPAQUE stage
  20390. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20391. observable.notifyObservers(info, renderingGroupMask);
  20392. // Fire PRETRANSPARENT stage
  20393. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20394. observable.notifyObservers(info, renderingGroupMask);
  20395. }
  20396. if (renderingGroup)
  20397. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20398. // Fire POSTTRANSPARENT stage
  20399. if (observable && info) {
  20400. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20401. observable.notifyObservers(info, renderingGroupMask);
  20402. }
  20403. }
  20404. };
  20405. RenderingManager.prototype.reset = function () {
  20406. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20407. var renderingGroup = this._renderingGroups[index];
  20408. if (renderingGroup) {
  20409. renderingGroup.prepare();
  20410. }
  20411. }
  20412. };
  20413. RenderingManager.prototype.dispose = function () {
  20414. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20415. var renderingGroup = this._renderingGroups[index];
  20416. if (renderingGroup) {
  20417. renderingGroup.dispose();
  20418. }
  20419. }
  20420. this._renderingGroups.length = 0;
  20421. };
  20422. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20423. if (this._renderingGroups[renderingGroupId] === undefined) {
  20424. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20425. }
  20426. };
  20427. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20428. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20429. this._prepareRenderingGroup(renderingGroupId);
  20430. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20431. };
  20432. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20433. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20434. this._prepareRenderingGroup(renderingGroupId);
  20435. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20436. };
  20437. /**
  20438. * @param subMesh The submesh to dispatch
  20439. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20440. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20441. */
  20442. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20443. if (mesh === undefined) {
  20444. mesh = subMesh.getMesh();
  20445. }
  20446. var renderingGroupId = mesh.renderingGroupId || 0;
  20447. this._prepareRenderingGroup(renderingGroupId);
  20448. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20449. };
  20450. /**
  20451. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20452. * This allowed control for front to back rendering or reversly depending of the special needs.
  20453. *
  20454. * @param renderingGroupId The rendering group id corresponding to its index
  20455. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20456. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20457. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20458. */
  20459. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20460. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20461. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20462. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20463. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20464. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20465. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20466. if (this._renderingGroups[renderingGroupId]) {
  20467. var group = this._renderingGroups[renderingGroupId];
  20468. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20469. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20470. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20471. }
  20472. };
  20473. /**
  20474. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20475. *
  20476. * @param renderingGroupId The rendering group id corresponding to its index
  20477. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20478. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20479. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20480. */
  20481. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20482. if (depth === void 0) { depth = true; }
  20483. if (stencil === void 0) { stencil = true; }
  20484. this._autoClearDepthStencil[renderingGroupId] = {
  20485. autoClear: autoClearDepthStencil,
  20486. depth: depth,
  20487. stencil: stencil
  20488. };
  20489. };
  20490. /**
  20491. * The max id used for rendering groups (not included)
  20492. */
  20493. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20494. /**
  20495. * The min id used for rendering groups (included)
  20496. */
  20497. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20498. /**
  20499. * Used to globally prevent autoclearing scenes.
  20500. */
  20501. RenderingManager.AUTOCLEAR = true;
  20502. return RenderingManager;
  20503. }());
  20504. BABYLON.RenderingManager = RenderingManager;
  20505. })(BABYLON || (BABYLON = {}));
  20506. //# sourceMappingURL=babylon.renderingManager.js.map
  20507. var BABYLON;
  20508. (function (BABYLON) {
  20509. var RenderingGroup = /** @class */ (function () {
  20510. /**
  20511. * Creates a new rendering group.
  20512. * @param index The rendering group index
  20513. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20514. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20515. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20516. */
  20517. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20518. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20519. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20520. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20521. this.index = index;
  20522. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20523. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20524. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20525. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20526. this._particleSystems = new BABYLON.SmartArray(256);
  20527. this._spriteManagers = new BABYLON.SmartArray(256);
  20528. this._edgesRenderers = new BABYLON.SmartArray(16);
  20529. this._scene = scene;
  20530. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20531. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20532. this.transparentSortCompareFn = transparentSortCompareFn;
  20533. }
  20534. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20535. /**
  20536. * Set the opaque sort comparison function.
  20537. * If null the sub meshes will be render in the order they were created
  20538. */
  20539. set: function (value) {
  20540. this._opaqueSortCompareFn = value;
  20541. if (value) {
  20542. this._renderOpaque = this.renderOpaqueSorted;
  20543. }
  20544. else {
  20545. this._renderOpaque = RenderingGroup.renderUnsorted;
  20546. }
  20547. },
  20548. enumerable: true,
  20549. configurable: true
  20550. });
  20551. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20552. /**
  20553. * Set the alpha test sort comparison function.
  20554. * If null the sub meshes will be render in the order they were created
  20555. */
  20556. set: function (value) {
  20557. this._alphaTestSortCompareFn = value;
  20558. if (value) {
  20559. this._renderAlphaTest = this.renderAlphaTestSorted;
  20560. }
  20561. else {
  20562. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20563. }
  20564. },
  20565. enumerable: true,
  20566. configurable: true
  20567. });
  20568. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20569. /**
  20570. * Set the transparent sort comparison function.
  20571. * If null the sub meshes will be render in the order they were created
  20572. */
  20573. set: function (value) {
  20574. if (value) {
  20575. this._transparentSortCompareFn = value;
  20576. }
  20577. else {
  20578. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20579. }
  20580. this._renderTransparent = this.renderTransparentSorted;
  20581. },
  20582. enumerable: true,
  20583. configurable: true
  20584. });
  20585. /**
  20586. * Render all the sub meshes contained in the group.
  20587. * @param customRenderFunction Used to override the default render behaviour of the group.
  20588. * @returns true if rendered some submeshes.
  20589. */
  20590. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20591. if (customRenderFunction) {
  20592. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20593. return;
  20594. }
  20595. var engine = this._scene.getEngine();
  20596. // Depth only
  20597. if (this._depthOnlySubMeshes.length !== 0) {
  20598. engine.setColorWrite(false);
  20599. this._renderAlphaTest(this._depthOnlySubMeshes);
  20600. engine.setColorWrite(true);
  20601. }
  20602. // Opaque
  20603. if (this._opaqueSubMeshes.length !== 0) {
  20604. this._renderOpaque(this._opaqueSubMeshes);
  20605. }
  20606. // Alpha test
  20607. if (this._alphaTestSubMeshes.length !== 0) {
  20608. this._renderAlphaTest(this._alphaTestSubMeshes);
  20609. }
  20610. var stencilState = engine.getStencilBuffer();
  20611. engine.setStencilBuffer(false);
  20612. // Sprites
  20613. if (renderSprites) {
  20614. this._renderSprites();
  20615. }
  20616. // Particles
  20617. if (renderParticles) {
  20618. this._renderParticles(activeMeshes);
  20619. }
  20620. if (this.onBeforeTransparentRendering) {
  20621. this.onBeforeTransparentRendering();
  20622. }
  20623. // Transparent
  20624. if (this._transparentSubMeshes.length !== 0) {
  20625. this._renderTransparent(this._transparentSubMeshes);
  20626. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20627. }
  20628. // Set back stencil to false in case it changes before the edge renderer.
  20629. engine.setStencilBuffer(false);
  20630. // Edges
  20631. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20632. this._edgesRenderers.data[edgesRendererIndex].render();
  20633. }
  20634. // Restore Stencil state.
  20635. engine.setStencilBuffer(stencilState);
  20636. };
  20637. /**
  20638. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20639. * @param subMeshes The submeshes to render
  20640. */
  20641. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20642. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20643. };
  20644. /**
  20645. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20646. * @param subMeshes The submeshes to render
  20647. */
  20648. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20649. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20650. };
  20651. /**
  20652. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20653. * @param subMeshes The submeshes to render
  20654. */
  20655. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20656. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20657. };
  20658. /**
  20659. * Renders the submeshes in a specified order.
  20660. * @param subMeshes The submeshes to sort before render
  20661. * @param sortCompareFn The comparison function use to sort
  20662. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20663. * @param transparent Specifies to activate blending if true
  20664. */
  20665. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20666. var subIndex = 0;
  20667. var subMesh;
  20668. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20669. for (; subIndex < subMeshes.length; subIndex++) {
  20670. subMesh = subMeshes.data[subIndex];
  20671. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20672. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20673. }
  20674. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20675. if (sortCompareFn) {
  20676. sortedArray.sort(sortCompareFn);
  20677. }
  20678. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20679. subMesh = sortedArray[subIndex];
  20680. if (transparent) {
  20681. var material = subMesh.getMaterial();
  20682. if (material && material.needDepthPrePass) {
  20683. var engine = material.getScene().getEngine();
  20684. engine.setColorWrite(false);
  20685. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20686. subMesh.render(false);
  20687. engine.setColorWrite(true);
  20688. }
  20689. }
  20690. subMesh.render(transparent);
  20691. }
  20692. };
  20693. /**
  20694. * Renders the submeshes in the order they were dispatched (no sort applied).
  20695. * @param subMeshes The submeshes to render
  20696. */
  20697. RenderingGroup.renderUnsorted = function (subMeshes) {
  20698. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20699. var submesh = subMeshes.data[subIndex];
  20700. submesh.render(false);
  20701. }
  20702. };
  20703. /**
  20704. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20705. * are rendered back to front if in the same alpha index.
  20706. *
  20707. * @param a The first submesh
  20708. * @param b The second submesh
  20709. * @returns The result of the comparison
  20710. */
  20711. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20712. // Alpha index first
  20713. if (a._alphaIndex > b._alphaIndex) {
  20714. return 1;
  20715. }
  20716. if (a._alphaIndex < b._alphaIndex) {
  20717. return -1;
  20718. }
  20719. // Then distance to camera
  20720. return RenderingGroup.backToFrontSortCompare(a, b);
  20721. };
  20722. /**
  20723. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20724. * are rendered back to front.
  20725. *
  20726. * @param a The first submesh
  20727. * @param b The second submesh
  20728. * @returns The result of the comparison
  20729. */
  20730. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20731. // Then distance to camera
  20732. if (a._distanceToCamera < b._distanceToCamera) {
  20733. return 1;
  20734. }
  20735. if (a._distanceToCamera > b._distanceToCamera) {
  20736. return -1;
  20737. }
  20738. return 0;
  20739. };
  20740. /**
  20741. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20742. * are rendered front to back (prevent overdraw).
  20743. *
  20744. * @param a The first submesh
  20745. * @param b The second submesh
  20746. * @returns The result of the comparison
  20747. */
  20748. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20749. // Then distance to camera
  20750. if (a._distanceToCamera < b._distanceToCamera) {
  20751. return -1;
  20752. }
  20753. if (a._distanceToCamera > b._distanceToCamera) {
  20754. return 1;
  20755. }
  20756. return 0;
  20757. };
  20758. /**
  20759. * Resets the different lists of submeshes to prepare a new frame.
  20760. */
  20761. RenderingGroup.prototype.prepare = function () {
  20762. this._opaqueSubMeshes.reset();
  20763. this._transparentSubMeshes.reset();
  20764. this._alphaTestSubMeshes.reset();
  20765. this._depthOnlySubMeshes.reset();
  20766. this._particleSystems.reset();
  20767. this._spriteManagers.reset();
  20768. this._edgesRenderers.reset();
  20769. };
  20770. RenderingGroup.prototype.dispose = function () {
  20771. this._opaqueSubMeshes.dispose();
  20772. this._transparentSubMeshes.dispose();
  20773. this._alphaTestSubMeshes.dispose();
  20774. this._depthOnlySubMeshes.dispose();
  20775. this._particleSystems.dispose();
  20776. this._spriteManagers.dispose();
  20777. this._edgesRenderers.dispose();
  20778. };
  20779. /**
  20780. * Inserts the submesh in its correct queue depending on its material.
  20781. * @param subMesh The submesh to dispatch
  20782. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20783. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20784. */
  20785. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20786. // Get mesh and materials if not provided
  20787. if (mesh === undefined) {
  20788. mesh = subMesh.getMesh();
  20789. }
  20790. if (material === undefined) {
  20791. material = subMesh.getMaterial();
  20792. }
  20793. if (material === null || material === undefined) {
  20794. return;
  20795. }
  20796. if (material.needAlphaBlendingForMesh(mesh)) {
  20797. this._transparentSubMeshes.push(subMesh);
  20798. }
  20799. else if (material.needAlphaTesting()) {
  20800. if (material.needDepthPrePass) {
  20801. this._depthOnlySubMeshes.push(subMesh);
  20802. }
  20803. this._alphaTestSubMeshes.push(subMesh);
  20804. }
  20805. else {
  20806. if (material.needDepthPrePass) {
  20807. this._depthOnlySubMeshes.push(subMesh);
  20808. }
  20809. this._opaqueSubMeshes.push(subMesh); // Opaque
  20810. }
  20811. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20812. this._edgesRenderers.push(mesh._edgesRenderer);
  20813. }
  20814. };
  20815. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20816. this._spriteManagers.push(spriteManager);
  20817. };
  20818. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20819. this._particleSystems.push(particleSystem);
  20820. };
  20821. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20822. if (this._particleSystems.length === 0) {
  20823. return;
  20824. }
  20825. // Particles
  20826. var activeCamera = this._scene.activeCamera;
  20827. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20828. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20829. var particleSystem = this._particleSystems.data[particleIndex];
  20830. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20831. continue;
  20832. }
  20833. var emitter = particleSystem.emitter;
  20834. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20835. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20836. }
  20837. }
  20838. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20839. };
  20840. RenderingGroup.prototype._renderSprites = function () {
  20841. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20842. return;
  20843. }
  20844. // Sprites
  20845. var activeCamera = this._scene.activeCamera;
  20846. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20847. for (var id = 0; id < this._spriteManagers.length; id++) {
  20848. var spriteManager = this._spriteManagers.data[id];
  20849. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20850. spriteManager.render();
  20851. }
  20852. }
  20853. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20854. };
  20855. return RenderingGroup;
  20856. }());
  20857. BABYLON.RenderingGroup = RenderingGroup;
  20858. })(BABYLON || (BABYLON = {}));
  20859. //# sourceMappingURL=babylon.renderingGroup.js.map
  20860. var BABYLON;
  20861. (function (BABYLON) {
  20862. var ClickInfo = /** @class */ (function () {
  20863. function ClickInfo() {
  20864. this._singleClick = false;
  20865. this._doubleClick = false;
  20866. this._hasSwiped = false;
  20867. this._ignore = false;
  20868. }
  20869. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20870. get: function () {
  20871. return this._singleClick;
  20872. },
  20873. set: function (b) {
  20874. this._singleClick = b;
  20875. },
  20876. enumerable: true,
  20877. configurable: true
  20878. });
  20879. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20880. get: function () {
  20881. return this._doubleClick;
  20882. },
  20883. set: function (b) {
  20884. this._doubleClick = b;
  20885. },
  20886. enumerable: true,
  20887. configurable: true
  20888. });
  20889. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20890. get: function () {
  20891. return this._hasSwiped;
  20892. },
  20893. set: function (b) {
  20894. this._hasSwiped = b;
  20895. },
  20896. enumerable: true,
  20897. configurable: true
  20898. });
  20899. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20900. get: function () {
  20901. return this._ignore;
  20902. },
  20903. set: function (b) {
  20904. this._ignore = b;
  20905. },
  20906. enumerable: true,
  20907. configurable: true
  20908. });
  20909. return ClickInfo;
  20910. }());
  20911. /**
  20912. * This class is used by the onRenderingGroupObservable
  20913. */
  20914. var RenderingGroupInfo = /** @class */ (function () {
  20915. function RenderingGroupInfo() {
  20916. }
  20917. /**
  20918. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20919. * This stage will be fired no matter what
  20920. */
  20921. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20922. /**
  20923. * Called before opaque object are rendered.
  20924. * This stage will be fired only if there's 3D Opaque content to render
  20925. */
  20926. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20927. /**
  20928. * Called after the opaque objects are rendered and before the transparent ones
  20929. * This stage will be fired only if there's 3D transparent content to render
  20930. */
  20931. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20932. /**
  20933. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20934. * This stage will be fired no matter what
  20935. */
  20936. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20937. return RenderingGroupInfo;
  20938. }());
  20939. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20940. /**
  20941. * Represents a scene to be rendered by the engine.
  20942. * @see http://doc.babylonjs.com/page.php?p=21911
  20943. */
  20944. var Scene = /** @class */ (function () {
  20945. /**
  20946. * @constructor
  20947. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20948. */
  20949. function Scene(engine) {
  20950. // Members
  20951. this.autoClear = true;
  20952. this.autoClearDepthAndStencil = true;
  20953. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20954. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20955. this.forceWireframe = false;
  20956. this._forcePointsCloud = false;
  20957. this.forceShowBoundingBoxes = false;
  20958. this.animationsEnabled = true;
  20959. this.useConstantAnimationDeltaTime = false;
  20960. this.constantlyUpdateMeshUnderPointer = false;
  20961. this.hoverCursor = "pointer";
  20962. this.defaultCursor = "";
  20963. /**
  20964. * This is used to call preventDefault() on pointer down
  20965. * in order to block unwanted artifacts like system double clicks
  20966. */
  20967. this.preventDefaultOnPointerDown = true;
  20968. // Metadata
  20969. this.metadata = null;
  20970. /**
  20971. * An event triggered when the scene is disposed.
  20972. * @type {BABYLON.Observable}
  20973. */
  20974. this.onDisposeObservable = new BABYLON.Observable();
  20975. /**
  20976. * An event triggered before rendering the scene (right after animations and physics)
  20977. * @type {BABYLON.Observable}
  20978. */
  20979. this.onBeforeRenderObservable = new BABYLON.Observable();
  20980. /**
  20981. * An event triggered after rendering the scene
  20982. * @type {BABYLON.Observable}
  20983. */
  20984. this.onAfterRenderObservable = new BABYLON.Observable();
  20985. /**
  20986. * An event triggered before animating the scene
  20987. * @type {BABYLON.Observable}
  20988. */
  20989. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20990. /**
  20991. * An event triggered after animations processing
  20992. * @type {BABYLON.Observable}
  20993. */
  20994. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20995. /**
  20996. * An event triggered before draw calls are ready to be sent
  20997. * @type {BABYLON.Observable}
  20998. */
  20999. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21000. /**
  21001. * An event triggered after draw calls have been sent
  21002. * @type {BABYLON.Observable}
  21003. */
  21004. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21005. /**
  21006. * An event triggered when physic simulation is about to be run
  21007. * @type {BABYLON.Observable}
  21008. */
  21009. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21010. /**
  21011. * An event triggered when physic simulation has been done
  21012. * @type {BABYLON.Observable}
  21013. */
  21014. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21015. /**
  21016. * An event triggered when the scene is ready
  21017. * @type {BABYLON.Observable}
  21018. */
  21019. this.onReadyObservable = new BABYLON.Observable();
  21020. /**
  21021. * An event triggered before rendering a camera
  21022. * @type {BABYLON.Observable}
  21023. */
  21024. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21025. /**
  21026. * An event triggered after rendering a camera
  21027. * @type {BABYLON.Observable}
  21028. */
  21029. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21030. /**
  21031. * An event triggered when active meshes evaluation is about to start
  21032. * @type {BABYLON.Observable}
  21033. */
  21034. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21035. /**
  21036. * An event triggered when active meshes evaluation is done
  21037. * @type {BABYLON.Observable}
  21038. */
  21039. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21040. /**
  21041. * An event triggered when particles rendering is about to start
  21042. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21043. * @type {BABYLON.Observable}
  21044. */
  21045. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21046. /**
  21047. * An event triggered when particles rendering is done
  21048. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21049. * @type {BABYLON.Observable}
  21050. */
  21051. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21052. /**
  21053. * An event triggered when sprites rendering is about to start
  21054. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21055. * @type {BABYLON.Observable}
  21056. */
  21057. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21058. /**
  21059. * An event triggered when sprites rendering is done
  21060. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21061. * @type {BABYLON.Observable}
  21062. */
  21063. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21064. /**
  21065. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21066. * @type {BABYLON.Observable}
  21067. */
  21068. this.onDataLoadedObservable = new BABYLON.Observable();
  21069. /**
  21070. * An event triggered when a camera is created
  21071. * @type {BABYLON.Observable}
  21072. */
  21073. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21074. /**
  21075. * An event triggered when a camera is removed
  21076. * @type {BABYLON.Observable}
  21077. */
  21078. this.onCameraRemovedObservable = new BABYLON.Observable();
  21079. /**
  21080. * An event triggered when a light is created
  21081. * @type {BABYLON.Observable}
  21082. */
  21083. this.onNewLightAddedObservable = new BABYLON.Observable();
  21084. /**
  21085. * An event triggered when a light is removed
  21086. * @type {BABYLON.Observable}
  21087. */
  21088. this.onLightRemovedObservable = new BABYLON.Observable();
  21089. /**
  21090. * An event triggered when a geometry is created
  21091. * @type {BABYLON.Observable}
  21092. */
  21093. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21094. /**
  21095. * An event triggered when a geometry is removed
  21096. * @type {BABYLON.Observable}
  21097. */
  21098. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21099. /**
  21100. * An event triggered when a transform node is created
  21101. * @type {BABYLON.Observable}
  21102. */
  21103. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21104. /**
  21105. * An event triggered when a transform node is removed
  21106. * @type {BABYLON.Observable}
  21107. */
  21108. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21109. /**
  21110. * An event triggered when a mesh is created
  21111. * @type {BABYLON.Observable}
  21112. */
  21113. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21114. /**
  21115. * An event triggered when a mesh is removed
  21116. * @type {BABYLON.Observable}
  21117. */
  21118. this.onMeshRemovedObservable = new BABYLON.Observable();
  21119. /**
  21120. * An event triggered when render targets are about to be rendered
  21121. * Can happen multiple times per frame.
  21122. * @type {BABYLON.Observable}
  21123. */
  21124. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21125. /**
  21126. * An event triggered when render targets were rendered.
  21127. * Can happen multiple times per frame.
  21128. * @type {BABYLON.Observable}
  21129. */
  21130. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21131. /**
  21132. * An event triggered before calculating deterministic simulation step
  21133. * @type {BABYLON.Observable}
  21134. */
  21135. this.onBeforeStepObservable = new BABYLON.Observable();
  21136. /**
  21137. * An event triggered after calculating deterministic simulation step
  21138. * @type {BABYLON.Observable}
  21139. */
  21140. this.onAfterStepObservable = new BABYLON.Observable();
  21141. /**
  21142. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21143. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21144. * 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)
  21145. */
  21146. this.onRenderingGroupObservable = new BABYLON.Observable();
  21147. // Animations
  21148. this.animations = [];
  21149. /**
  21150. * 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).
  21151. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21152. */
  21153. this.onPrePointerObservable = new BABYLON.Observable();
  21154. /**
  21155. * Observable event triggered each time an input event is received from the rendering canvas
  21156. */
  21157. this.onPointerObservable = new BABYLON.Observable();
  21158. this._meshPickProceed = false;
  21159. this._currentPickResult = null;
  21160. this._previousPickResult = null;
  21161. this._totalPointersPressed = 0;
  21162. this._doubleClickOccured = false;
  21163. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21164. this.cameraToUseForPointers = null;
  21165. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21166. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21167. this._startingPointerTime = 0;
  21168. this._previousStartingPointerTime = 0;
  21169. // Deterministic lockstep
  21170. this._timeAccumulator = 0;
  21171. this._currentStepId = 0;
  21172. this._currentInternalStep = 0;
  21173. // Keyboard
  21174. /**
  21175. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21176. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21177. */
  21178. this.onPreKeyboardObservable = new BABYLON.Observable();
  21179. /**
  21180. * Observable event triggered each time an keyboard event is received from the hosting window
  21181. */
  21182. this.onKeyboardObservable = new BABYLON.Observable();
  21183. // Coordinate system
  21184. /**
  21185. * use right-handed coordinate system on this scene.
  21186. * @type {boolean}
  21187. */
  21188. this._useRightHandedSystem = false;
  21189. // Fog
  21190. this._fogEnabled = true;
  21191. this._fogMode = Scene.FOGMODE_NONE;
  21192. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21193. this.fogDensity = 0.1;
  21194. this.fogStart = 0;
  21195. this.fogEnd = 1000.0;
  21196. // Lights
  21197. /**
  21198. * is shadow enabled on this scene.
  21199. * @type {boolean}
  21200. */
  21201. this._shadowsEnabled = true;
  21202. /**
  21203. * is light enabled on this scene.
  21204. * @type {boolean}
  21205. */
  21206. this._lightsEnabled = true;
  21207. /**
  21208. * All of the lights added to this scene.
  21209. * @see BABYLON.Light
  21210. * @type {BABYLON.Light[]}
  21211. */
  21212. this.lights = new Array();
  21213. // Cameras
  21214. /** All of the cameras added to this scene. */
  21215. this.cameras = new Array();
  21216. /** All of the active cameras added to this scene. */
  21217. this.activeCameras = new Array();
  21218. // Meshes
  21219. /**
  21220. * All of the tranform nodes added to this scene.
  21221. * @see BABYLON.TransformNode
  21222. * @type {BABYLON.TransformNode[]}
  21223. */
  21224. this.transformNodes = new Array();
  21225. /**
  21226. * All of the (abstract) meshes added to this scene.
  21227. * @see BABYLON.AbstractMesh
  21228. * @type {BABYLON.AbstractMesh[]}
  21229. */
  21230. this.meshes = new Array();
  21231. /**
  21232. * All of the animation groups added to this scene.
  21233. * @see BABYLON.AnimationGroup
  21234. * @type {BABYLON.AnimationGroup[]}
  21235. */
  21236. this.animationGroups = new Array();
  21237. // Geometries
  21238. this._geometries = new Array();
  21239. this.materials = new Array();
  21240. this.multiMaterials = new Array();
  21241. // Textures
  21242. this._texturesEnabled = true;
  21243. this.textures = new Array();
  21244. // Particles
  21245. this.particlesEnabled = true;
  21246. this.particleSystems = new Array();
  21247. // Sprites
  21248. this.spritesEnabled = true;
  21249. this.spriteManagers = new Array();
  21250. /**
  21251. * The list of layers (background and foreground) of the scene.
  21252. */
  21253. this.layers = new Array();
  21254. /**
  21255. * The list of effect layers (highlights/glow) contained in the scene.
  21256. */
  21257. this.effectLayers = new Array();
  21258. // Skeletons
  21259. this._skeletonsEnabled = true;
  21260. this.skeletons = new Array();
  21261. // Morph targets
  21262. this.morphTargetManagers = new Array();
  21263. // Lens flares
  21264. this.lensFlaresEnabled = true;
  21265. this.lensFlareSystems = new Array();
  21266. // Collisions
  21267. this.collisionsEnabled = true;
  21268. /** Defines the gravity applied to this scene */
  21269. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21270. // Postprocesses
  21271. this.postProcesses = new Array();
  21272. this.postProcessesEnabled = true;
  21273. // Customs render targets
  21274. this.renderTargetsEnabled = true;
  21275. this.dumpNextRenderTargets = false;
  21276. this.customRenderTargets = new Array();
  21277. // Imported meshes
  21278. this.importedMeshesFiles = new Array();
  21279. // Probes
  21280. this.probesEnabled = true;
  21281. this.reflectionProbes = new Array();
  21282. this._actionManagers = new Array();
  21283. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21284. // Procedural textures
  21285. this.proceduralTexturesEnabled = true;
  21286. this._proceduralTextures = new Array();
  21287. this.soundTracks = new Array();
  21288. this._audioEnabled = true;
  21289. this._headphone = false;
  21290. // Performance counters
  21291. this._totalVertices = new BABYLON.PerfCounter();
  21292. this._activeIndices = new BABYLON.PerfCounter();
  21293. this._activeParticles = new BABYLON.PerfCounter();
  21294. this._activeBones = new BABYLON.PerfCounter();
  21295. this._animationTime = 0;
  21296. this.animationTimeScale = 1;
  21297. this._renderId = 0;
  21298. this._executeWhenReadyTimeoutId = -1;
  21299. this._intermediateRendering = false;
  21300. this._viewUpdateFlag = -1;
  21301. this._projectionUpdateFlag = -1;
  21302. this._alternateViewUpdateFlag = -1;
  21303. this._alternateProjectionUpdateFlag = -1;
  21304. this._toBeDisposed = new BABYLON.SmartArray(256);
  21305. this._activeRequests = new Array();
  21306. this._pendingData = new Array();
  21307. this._isDisposed = false;
  21308. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21309. this._activeMeshes = new BABYLON.SmartArray(256);
  21310. this._processedMaterials = new BABYLON.SmartArray(256);
  21311. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21312. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21313. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21314. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21315. this._activeAnimatables = new Array();
  21316. this._transformMatrix = BABYLON.Matrix.Zero();
  21317. this._useAlternateCameraConfiguration = false;
  21318. this._alternateRendering = false;
  21319. this.requireLightSorting = false;
  21320. this._activeMeshesFrozen = false;
  21321. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21322. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21323. this._engine.scenes.push(this);
  21324. this._uid = null;
  21325. this._renderingManager = new BABYLON.RenderingManager(this);
  21326. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21327. if (BABYLON.OutlineRenderer) {
  21328. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21329. }
  21330. if (BABYLON.Tools.IsWindowObjectExist()) {
  21331. this.attachControl();
  21332. }
  21333. //simplification queue
  21334. if (BABYLON.SimplificationQueue) {
  21335. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21336. }
  21337. //collision coordinator initialization. For now legacy per default.
  21338. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21339. // Uniform Buffer
  21340. this._createUbo();
  21341. // Default Image processing definition.
  21342. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21343. }
  21344. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21345. /** The fog is deactivated */
  21346. get: function () {
  21347. return Scene._FOGMODE_NONE;
  21348. },
  21349. enumerable: true,
  21350. configurable: true
  21351. });
  21352. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21353. /** The fog density is following an exponential function */
  21354. get: function () {
  21355. return Scene._FOGMODE_EXP;
  21356. },
  21357. enumerable: true,
  21358. configurable: true
  21359. });
  21360. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21361. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21362. get: function () {
  21363. return Scene._FOGMODE_EXP2;
  21364. },
  21365. enumerable: true,
  21366. configurable: true
  21367. });
  21368. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21369. /** The fog density is following a linear function. */
  21370. get: function () {
  21371. return Scene._FOGMODE_LINEAR;
  21372. },
  21373. enumerable: true,
  21374. configurable: true
  21375. });
  21376. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21377. /**
  21378. * Texture used in all pbr material as the reflection texture.
  21379. * As in the majority of the scene they are the same (exception for multi room and so on),
  21380. * this is easier to reference from here than from all the materials.
  21381. */
  21382. get: function () {
  21383. return this._environmentTexture;
  21384. },
  21385. /**
  21386. * Texture used in all pbr material as the reflection texture.
  21387. * As in the majority of the scene they are the same (exception for multi room and so on),
  21388. * this is easier to set here than in all the materials.
  21389. */
  21390. set: function (value) {
  21391. if (this._environmentTexture === value) {
  21392. return;
  21393. }
  21394. this._environmentTexture = value;
  21395. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21401. /**
  21402. * Default image processing configuration used either in the rendering
  21403. * Forward main pass or through the imageProcessingPostProcess if present.
  21404. * As in the majority of the scene they are the same (exception for multi camera),
  21405. * this is easier to reference from here than from all the materials and post process.
  21406. *
  21407. * No setter as we it is a shared configuration, you can set the values instead.
  21408. */
  21409. get: function () {
  21410. return this._imageProcessingConfiguration;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21416. get: function () {
  21417. return this._forcePointsCloud;
  21418. },
  21419. set: function (value) {
  21420. if (this._forcePointsCloud === value) {
  21421. return;
  21422. }
  21423. this._forcePointsCloud = value;
  21424. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21425. },
  21426. enumerable: true,
  21427. configurable: true
  21428. });
  21429. Object.defineProperty(Scene.prototype, "onDispose", {
  21430. /** A function to be executed when this scene is disposed. */
  21431. set: function (callback) {
  21432. if (this._onDisposeObserver) {
  21433. this.onDisposeObservable.remove(this._onDisposeObserver);
  21434. }
  21435. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21436. },
  21437. enumerable: true,
  21438. configurable: true
  21439. });
  21440. Object.defineProperty(Scene.prototype, "beforeRender", {
  21441. /** A function to be executed before rendering this scene */
  21442. set: function (callback) {
  21443. if (this._onBeforeRenderObserver) {
  21444. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21445. }
  21446. if (callback) {
  21447. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21448. }
  21449. },
  21450. enumerable: true,
  21451. configurable: true
  21452. });
  21453. Object.defineProperty(Scene.prototype, "afterRender", {
  21454. /** A function to be executed after rendering this scene */
  21455. set: function (callback) {
  21456. if (this._onAfterRenderObserver) {
  21457. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21458. }
  21459. if (callback) {
  21460. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21461. }
  21462. },
  21463. enumerable: true,
  21464. configurable: true
  21465. });
  21466. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21467. set: function (callback) {
  21468. if (this._onBeforeCameraRenderObserver) {
  21469. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21470. }
  21471. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21472. },
  21473. enumerable: true,
  21474. configurable: true
  21475. });
  21476. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21477. set: function (callback) {
  21478. if (this._onAfterCameraRenderObserver) {
  21479. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21480. }
  21481. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21482. },
  21483. enumerable: true,
  21484. configurable: true
  21485. });
  21486. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21487. get: function () {
  21488. if (!this._gamepadManager) {
  21489. this._gamepadManager = new BABYLON.GamepadManager(this);
  21490. }
  21491. return this._gamepadManager;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21497. get: function () {
  21498. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21504. get: function () {
  21505. return this._useRightHandedSystem;
  21506. },
  21507. set: function (value) {
  21508. if (this._useRightHandedSystem === value) {
  21509. return;
  21510. }
  21511. this._useRightHandedSystem = value;
  21512. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Scene.prototype.setStepId = function (newStepId) {
  21518. this._currentStepId = newStepId;
  21519. };
  21520. ;
  21521. Scene.prototype.getStepId = function () {
  21522. return this._currentStepId;
  21523. };
  21524. ;
  21525. Scene.prototype.getInternalStep = function () {
  21526. return this._currentInternalStep;
  21527. };
  21528. ;
  21529. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21530. get: function () {
  21531. return this._fogEnabled;
  21532. },
  21533. /**
  21534. * is fog enabled on this scene.
  21535. */
  21536. set: function (value) {
  21537. if (this._fogEnabled === value) {
  21538. return;
  21539. }
  21540. this._fogEnabled = value;
  21541. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21542. },
  21543. enumerable: true,
  21544. configurable: true
  21545. });
  21546. Object.defineProperty(Scene.prototype, "fogMode", {
  21547. get: function () {
  21548. return this._fogMode;
  21549. },
  21550. set: function (value) {
  21551. if (this._fogMode === value) {
  21552. return;
  21553. }
  21554. this._fogMode = value;
  21555. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21561. get: function () {
  21562. return this._shadowsEnabled;
  21563. },
  21564. set: function (value) {
  21565. if (this._shadowsEnabled === value) {
  21566. return;
  21567. }
  21568. this._shadowsEnabled = value;
  21569. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21570. },
  21571. enumerable: true,
  21572. configurable: true
  21573. });
  21574. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21575. get: function () {
  21576. return this._lightsEnabled;
  21577. },
  21578. set: function (value) {
  21579. if (this._lightsEnabled === value) {
  21580. return;
  21581. }
  21582. this._lightsEnabled = value;
  21583. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21584. },
  21585. enumerable: true,
  21586. configurable: true
  21587. });
  21588. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21589. /** The default material used on meshes when no material is affected */
  21590. get: function () {
  21591. if (!this._defaultMaterial) {
  21592. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21593. }
  21594. return this._defaultMaterial;
  21595. },
  21596. /** The default material used on meshes when no material is affected */
  21597. set: function (value) {
  21598. this._defaultMaterial = value;
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21604. get: function () {
  21605. return this._texturesEnabled;
  21606. },
  21607. set: function (value) {
  21608. if (this._texturesEnabled === value) {
  21609. return;
  21610. }
  21611. this._texturesEnabled = value;
  21612. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21613. },
  21614. enumerable: true,
  21615. configurable: true
  21616. });
  21617. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21618. get: function () {
  21619. return this._skeletonsEnabled;
  21620. },
  21621. set: function (value) {
  21622. if (this._skeletonsEnabled === value) {
  21623. return;
  21624. }
  21625. this._skeletonsEnabled = value;
  21626. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21627. },
  21628. enumerable: true,
  21629. configurable: true
  21630. });
  21631. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21632. get: function () {
  21633. if (!this._postProcessRenderPipelineManager) {
  21634. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21635. }
  21636. return this._postProcessRenderPipelineManager;
  21637. },
  21638. enumerable: true,
  21639. configurable: true
  21640. });
  21641. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21642. get: function () {
  21643. if (!this._mainSoundTrack) {
  21644. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21645. }
  21646. return this._mainSoundTrack;
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21652. get: function () {
  21653. return this._alternateRendering;
  21654. },
  21655. enumerable: true,
  21656. configurable: true
  21657. });
  21658. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21659. get: function () {
  21660. return this._frustumPlanes;
  21661. },
  21662. enumerable: true,
  21663. configurable: true
  21664. });
  21665. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21666. /**
  21667. * Gets the current geometry buffer associated to the scene.
  21668. */
  21669. get: function () {
  21670. return this._geometryBufferRenderer;
  21671. },
  21672. /**
  21673. * Sets the current geometry buffer for the scene.
  21674. */
  21675. set: function (geometryBufferRenderer) {
  21676. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21677. this._geometryBufferRenderer = geometryBufferRenderer;
  21678. }
  21679. },
  21680. enumerable: true,
  21681. configurable: true
  21682. });
  21683. Object.defineProperty(Scene.prototype, "debugLayer", {
  21684. // Properties
  21685. get: function () {
  21686. if (!this._debugLayer) {
  21687. this._debugLayer = new BABYLON.DebugLayer(this);
  21688. }
  21689. return this._debugLayer;
  21690. },
  21691. enumerable: true,
  21692. configurable: true
  21693. });
  21694. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21695. get: function () {
  21696. return this._workerCollisions;
  21697. },
  21698. set: function (enabled) {
  21699. if (!BABYLON.CollisionCoordinatorLegacy) {
  21700. return;
  21701. }
  21702. enabled = (enabled && !!Worker);
  21703. this._workerCollisions = enabled;
  21704. if (this.collisionCoordinator) {
  21705. this.collisionCoordinator.destroy();
  21706. }
  21707. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21708. this.collisionCoordinator.init(this);
  21709. },
  21710. enumerable: true,
  21711. configurable: true
  21712. });
  21713. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21714. get: function () {
  21715. return this._selectionOctree;
  21716. },
  21717. enumerable: true,
  21718. configurable: true
  21719. });
  21720. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21721. /**
  21722. * The mesh that is currently under the pointer.
  21723. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21724. */
  21725. get: function () {
  21726. return this._pointerOverMesh;
  21727. },
  21728. enumerable: true,
  21729. configurable: true
  21730. });
  21731. Object.defineProperty(Scene.prototype, "pointerX", {
  21732. /**
  21733. * Current on-screen X position of the pointer
  21734. * @return {number} X position of the pointer
  21735. */
  21736. get: function () {
  21737. return this._pointerX;
  21738. },
  21739. enumerable: true,
  21740. configurable: true
  21741. });
  21742. Object.defineProperty(Scene.prototype, "pointerY", {
  21743. /**
  21744. * Current on-screen Y position of the pointer
  21745. * @return {number} Y position of the pointer
  21746. */
  21747. get: function () {
  21748. return this._pointerY;
  21749. },
  21750. enumerable: true,
  21751. configurable: true
  21752. });
  21753. Scene.prototype.getCachedMaterial = function () {
  21754. return this._cachedMaterial;
  21755. };
  21756. Scene.prototype.getCachedEffect = function () {
  21757. return this._cachedEffect;
  21758. };
  21759. Scene.prototype.getCachedVisibility = function () {
  21760. return this._cachedVisibility;
  21761. };
  21762. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21763. if (visibility === void 0) { visibility = 1; }
  21764. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21765. };
  21766. Scene.prototype.getBoundingBoxRenderer = function () {
  21767. if (!this._boundingBoxRenderer) {
  21768. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21769. }
  21770. return this._boundingBoxRenderer;
  21771. };
  21772. Scene.prototype.getOutlineRenderer = function () {
  21773. return this._outlineRenderer;
  21774. };
  21775. Scene.prototype.getEngine = function () {
  21776. return this._engine;
  21777. };
  21778. Scene.prototype.getTotalVertices = function () {
  21779. return this._totalVertices.current;
  21780. };
  21781. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21782. get: function () {
  21783. return this._totalVertices;
  21784. },
  21785. enumerable: true,
  21786. configurable: true
  21787. });
  21788. Scene.prototype.getActiveIndices = function () {
  21789. return this._activeIndices.current;
  21790. };
  21791. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21792. get: function () {
  21793. return this._activeIndices;
  21794. },
  21795. enumerable: true,
  21796. configurable: true
  21797. });
  21798. Scene.prototype.getActiveParticles = function () {
  21799. return this._activeParticles.current;
  21800. };
  21801. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21802. get: function () {
  21803. return this._activeParticles;
  21804. },
  21805. enumerable: true,
  21806. configurable: true
  21807. });
  21808. Scene.prototype.getActiveBones = function () {
  21809. return this._activeBones.current;
  21810. };
  21811. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21812. get: function () {
  21813. return this._activeBones;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. // Stats
  21819. Scene.prototype.getInterFramePerfCounter = function () {
  21820. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21821. return 0;
  21822. };
  21823. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21824. get: function () {
  21825. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21826. return null;
  21827. },
  21828. enumerable: true,
  21829. configurable: true
  21830. });
  21831. Scene.prototype.getLastFrameDuration = function () {
  21832. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21833. return 0;
  21834. };
  21835. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21836. get: function () {
  21837. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21838. return null;
  21839. },
  21840. enumerable: true,
  21841. configurable: true
  21842. });
  21843. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21844. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21845. return 0;
  21846. };
  21847. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21848. get: function () {
  21849. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21850. return null;
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. Scene.prototype.getActiveMeshes = function () {
  21856. return this._activeMeshes;
  21857. };
  21858. Scene.prototype.getRenderTargetsDuration = function () {
  21859. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21860. return 0;
  21861. };
  21862. Scene.prototype.getRenderDuration = function () {
  21863. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21864. return 0;
  21865. };
  21866. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21867. get: function () {
  21868. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21869. return null;
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. Scene.prototype.getParticlesDuration = function () {
  21875. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21876. return 0;
  21877. };
  21878. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21879. get: function () {
  21880. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21881. return null;
  21882. },
  21883. enumerable: true,
  21884. configurable: true
  21885. });
  21886. Scene.prototype.getSpritesDuration = function () {
  21887. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21888. return 0;
  21889. };
  21890. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21891. get: function () {
  21892. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21893. return null;
  21894. },
  21895. enumerable: true,
  21896. configurable: true
  21897. });
  21898. Scene.prototype.getAnimationRatio = function () {
  21899. return this._animationRatio;
  21900. };
  21901. Scene.prototype.getRenderId = function () {
  21902. return this._renderId;
  21903. };
  21904. Scene.prototype.incrementRenderId = function () {
  21905. this._renderId++;
  21906. };
  21907. Scene.prototype._updatePointerPosition = function (evt) {
  21908. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21909. if (!canvasRect) {
  21910. return;
  21911. }
  21912. this._pointerX = evt.clientX - canvasRect.left;
  21913. this._pointerY = evt.clientY - canvasRect.top;
  21914. this._unTranslatedPointerX = this._pointerX;
  21915. this._unTranslatedPointerY = this._pointerY;
  21916. };
  21917. Scene.prototype._createUbo = function () {
  21918. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21919. this._sceneUbo.addUniform("viewProjection", 16);
  21920. this._sceneUbo.addUniform("view", 16);
  21921. };
  21922. Scene.prototype._createAlternateUbo = function () {
  21923. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21924. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21925. this._alternateSceneUbo.addUniform("view", 16);
  21926. };
  21927. // Pointers handling
  21928. /**
  21929. * Use this method to simulate a pointer move on a mesh
  21930. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21931. */
  21932. Scene.prototype.simulatePointerMove = function (pickResult) {
  21933. var evt = new PointerEvent("pointermove");
  21934. return this._processPointerMove(pickResult, evt);
  21935. };
  21936. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21937. var canvas = this._engine.getRenderingCanvas();
  21938. if (!canvas) {
  21939. return this;
  21940. }
  21941. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21942. this.setPointerOverSprite(null);
  21943. this.setPointerOverMesh(pickResult.pickedMesh);
  21944. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21945. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21946. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21947. }
  21948. else {
  21949. canvas.style.cursor = this.hoverCursor;
  21950. }
  21951. }
  21952. else {
  21953. canvas.style.cursor = this.defaultCursor;
  21954. }
  21955. }
  21956. else {
  21957. this.setPointerOverMesh(null);
  21958. // Sprites
  21959. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21960. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21961. this.setPointerOverSprite(pickResult.pickedSprite);
  21962. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21963. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21964. }
  21965. else {
  21966. canvas.style.cursor = this.hoverCursor;
  21967. }
  21968. }
  21969. else {
  21970. this.setPointerOverSprite(null);
  21971. // Restore pointer
  21972. canvas.style.cursor = this.defaultCursor;
  21973. }
  21974. }
  21975. if (pickResult) {
  21976. if (this.onPointerMove) {
  21977. this.onPointerMove(evt, pickResult);
  21978. }
  21979. if (this.onPointerObservable.hasObservers()) {
  21980. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21981. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21982. this.onPointerObservable.notifyObservers(pi, type);
  21983. }
  21984. }
  21985. return this;
  21986. };
  21987. /**
  21988. * Use this method to simulate a pointer down on a mesh
  21989. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21990. */
  21991. Scene.prototype.simulatePointerDown = function (pickResult) {
  21992. var evt = new PointerEvent("pointerdown");
  21993. return this._processPointerDown(pickResult, evt);
  21994. };
  21995. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21996. var _this = this;
  21997. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21998. this._pickedDownMesh = pickResult.pickedMesh;
  21999. var actionManager = pickResult.pickedMesh.actionManager;
  22000. if (actionManager) {
  22001. if (actionManager.hasPickTriggers) {
  22002. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22003. switch (evt.button) {
  22004. case 0:
  22005. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22006. break;
  22007. case 1:
  22008. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22009. break;
  22010. case 2:
  22011. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22012. break;
  22013. }
  22014. }
  22015. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22016. window.setTimeout(function () {
  22017. 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);
  22018. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22019. if (_this._totalPointersPressed !== 0 &&
  22020. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22021. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22022. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22023. _this._startingPointerTime = 0;
  22024. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22025. }
  22026. }
  22027. }, Scene.LongPressDelay);
  22028. }
  22029. }
  22030. }
  22031. if (pickResult) {
  22032. if (this.onPointerDown) {
  22033. this.onPointerDown(evt, pickResult);
  22034. }
  22035. if (this.onPointerObservable.hasObservers()) {
  22036. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22037. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22038. this.onPointerObservable.notifyObservers(pi, type);
  22039. }
  22040. }
  22041. return this;
  22042. };
  22043. /**
  22044. * Use this method to simulate a pointer up on a mesh
  22045. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22046. */
  22047. Scene.prototype.simulatePointerUp = function (pickResult) {
  22048. var evt = new PointerEvent("pointerup");
  22049. var clickInfo = new ClickInfo();
  22050. clickInfo.singleClick = true;
  22051. clickInfo.ignore = true;
  22052. return this._processPointerUp(pickResult, evt, clickInfo);
  22053. };
  22054. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22055. if (pickResult && pickResult && pickResult.pickedMesh) {
  22056. this._pickedUpMesh = pickResult.pickedMesh;
  22057. if (this._pickedDownMesh === this._pickedUpMesh) {
  22058. if (this.onPointerPick) {
  22059. this.onPointerPick(evt, pickResult);
  22060. }
  22061. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22062. var type = BABYLON.PointerEventTypes.POINTERPICK;
  22063. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22064. this.onPointerObservable.notifyObservers(pi, type);
  22065. }
  22066. }
  22067. if (pickResult.pickedMesh.actionManager) {
  22068. if (clickInfo.ignore) {
  22069. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22070. }
  22071. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22072. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22073. }
  22074. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22075. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22076. }
  22077. }
  22078. }
  22079. if (this._pickedDownMesh &&
  22080. this._pickedDownMesh.actionManager &&
  22081. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22082. this._pickedDownMesh !== this._pickedUpMesh) {
  22083. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22084. }
  22085. if (this.onPointerUp) {
  22086. this.onPointerUp(evt, pickResult);
  22087. }
  22088. if (this.onPointerObservable.hasObservers()) {
  22089. if (!clickInfo.ignore) {
  22090. if (!clickInfo.hasSwiped) {
  22091. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22092. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22093. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22094. this.onPointerObservable.notifyObservers(pi, type);
  22095. }
  22096. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22097. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22098. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22099. this.onPointerObservable.notifyObservers(pi, type);
  22100. }
  22101. }
  22102. }
  22103. else {
  22104. var type = BABYLON.PointerEventTypes.POINTERUP;
  22105. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22106. this.onPointerObservable.notifyObservers(pi, type);
  22107. }
  22108. }
  22109. return this;
  22110. };
  22111. /**
  22112. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22113. * @param attachUp defines if you want to attach events to pointerup
  22114. * @param attachDown defines if you want to attach events to pointerdown
  22115. * @param attachMove defines if you want to attach events to pointermove
  22116. */
  22117. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22118. var _this = this;
  22119. if (attachUp === void 0) { attachUp = true; }
  22120. if (attachDown === void 0) { attachDown = true; }
  22121. if (attachMove === void 0) { attachMove = true; }
  22122. this._initActionManager = function (act, clickInfo) {
  22123. if (!_this._meshPickProceed) {
  22124. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22125. _this._currentPickResult = pickResult;
  22126. if (pickResult) {
  22127. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22128. }
  22129. _this._meshPickProceed = true;
  22130. }
  22131. return act;
  22132. };
  22133. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22134. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22135. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22136. btn !== _this._previousButtonPressed) {
  22137. _this._doubleClickOccured = false;
  22138. clickInfo.singleClick = true;
  22139. clickInfo.ignore = false;
  22140. cb(clickInfo, _this._currentPickResult);
  22141. }
  22142. };
  22143. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22144. var clickInfo = new ClickInfo();
  22145. _this._currentPickResult = null;
  22146. var act = null;
  22147. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22148. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22149. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22150. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22151. act = _this._initActionManager(act, clickInfo);
  22152. if (act)
  22153. checkPicking = act.hasPickTriggers;
  22154. }
  22155. if (checkPicking) {
  22156. var btn = evt.button;
  22157. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22158. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22159. if (!clickInfo.hasSwiped) {
  22160. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22161. if (!checkSingleClickImmediately) {
  22162. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22163. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22164. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22165. act = _this._initActionManager(act, clickInfo);
  22166. if (act)
  22167. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22168. }
  22169. }
  22170. if (checkSingleClickImmediately) {
  22171. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22172. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22173. btn !== _this._previousButtonPressed) {
  22174. clickInfo.singleClick = true;
  22175. cb(clickInfo, _this._currentPickResult);
  22176. }
  22177. }
  22178. else {
  22179. // wait that no double click has been raised during the double click delay
  22180. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22181. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22182. }
  22183. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22184. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22185. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22186. act = _this._initActionManager(act, clickInfo);
  22187. if (act)
  22188. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22189. }
  22190. if (checkDoubleClick) {
  22191. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22192. if (btn === _this._previousButtonPressed &&
  22193. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22194. !_this._doubleClickOccured) {
  22195. // pointer has not moved for 2 clicks, it's a double click
  22196. if (!clickInfo.hasSwiped &&
  22197. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22198. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22199. _this._previousStartingPointerTime = 0;
  22200. _this._doubleClickOccured = true;
  22201. clickInfo.doubleClick = true;
  22202. clickInfo.ignore = false;
  22203. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22204. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22205. }
  22206. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22207. cb(clickInfo, _this._currentPickResult);
  22208. }
  22209. else {
  22210. _this._doubleClickOccured = false;
  22211. _this._previousStartingPointerTime = _this._startingPointerTime;
  22212. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22213. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22214. _this._previousButtonPressed = btn;
  22215. if (Scene.ExclusiveDoubleClickMode) {
  22216. if (_this._previousDelayedSimpleClickTimeout) {
  22217. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22218. }
  22219. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22220. cb(clickInfo, _this._previousPickResult);
  22221. }
  22222. else {
  22223. cb(clickInfo, _this._currentPickResult);
  22224. }
  22225. }
  22226. }
  22227. else {
  22228. _this._doubleClickOccured = false;
  22229. _this._previousStartingPointerTime = _this._startingPointerTime;
  22230. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22231. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22232. _this._previousButtonPressed = btn;
  22233. }
  22234. }
  22235. }
  22236. }
  22237. clickInfo.ignore = true;
  22238. cb(clickInfo, _this._currentPickResult);
  22239. };
  22240. this._spritePredicate = function (sprite) {
  22241. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22242. };
  22243. this._onPointerMove = function (evt) {
  22244. _this._updatePointerPosition(evt);
  22245. // PreObservable support
  22246. if (_this.onPrePointerObservable.hasObservers()) {
  22247. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22248. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22249. _this.onPrePointerObservable.notifyObservers(pi, type);
  22250. if (pi.skipOnPointerObservable) {
  22251. return;
  22252. }
  22253. }
  22254. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22255. return;
  22256. }
  22257. if (!_this.pointerMovePredicate) {
  22258. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22259. }
  22260. // Meshes
  22261. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22262. _this._processPointerMove(pickResult, evt);
  22263. };
  22264. this._onPointerDown = function (evt) {
  22265. _this._totalPointersPressed++;
  22266. _this._pickedDownMesh = null;
  22267. _this._meshPickProceed = false;
  22268. _this._updatePointerPosition(evt);
  22269. if (_this.preventDefaultOnPointerDown && canvas) {
  22270. evt.preventDefault();
  22271. canvas.focus();
  22272. }
  22273. // PreObservable support
  22274. if (_this.onPrePointerObservable.hasObservers()) {
  22275. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22276. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22277. _this.onPrePointerObservable.notifyObservers(pi, type);
  22278. if (pi.skipOnPointerObservable) {
  22279. return;
  22280. }
  22281. }
  22282. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22283. return;
  22284. }
  22285. _this._startingPointerPosition.x = _this._pointerX;
  22286. _this._startingPointerPosition.y = _this._pointerY;
  22287. _this._startingPointerTime = new Date().getTime();
  22288. if (!_this.pointerDownPredicate) {
  22289. _this.pointerDownPredicate = function (mesh) {
  22290. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22291. };
  22292. }
  22293. // Meshes
  22294. _this._pickedDownMesh = null;
  22295. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22296. _this._processPointerDown(pickResult, evt);
  22297. // Sprites
  22298. _this._pickedDownSprite = null;
  22299. if (_this.spriteManagers.length > 0) {
  22300. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22301. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22302. if (pickResult.pickedSprite.actionManager) {
  22303. _this._pickedDownSprite = pickResult.pickedSprite;
  22304. switch (evt.button) {
  22305. case 0:
  22306. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22307. break;
  22308. case 1:
  22309. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22310. break;
  22311. case 2:
  22312. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22313. break;
  22314. }
  22315. if (pickResult.pickedSprite.actionManager) {
  22316. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22317. }
  22318. }
  22319. }
  22320. }
  22321. };
  22322. this._onPointerUp = function (evt) {
  22323. if (_this._totalPointersPressed === 0) {
  22324. return; // So we need to test it the pointer down was pressed before.
  22325. }
  22326. _this._totalPointersPressed--;
  22327. _this._pickedUpMesh = null;
  22328. _this._meshPickProceed = false;
  22329. _this._updatePointerPosition(evt);
  22330. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22331. // PreObservable support
  22332. if (_this.onPrePointerObservable.hasObservers()) {
  22333. if (!clickInfo.ignore) {
  22334. if (!clickInfo.hasSwiped) {
  22335. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22336. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22337. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22338. _this.onPrePointerObservable.notifyObservers(pi, type);
  22339. if (pi.skipOnPointerObservable) {
  22340. return;
  22341. }
  22342. }
  22343. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22344. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22345. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22346. _this.onPrePointerObservable.notifyObservers(pi, type);
  22347. if (pi.skipOnPointerObservable) {
  22348. return;
  22349. }
  22350. }
  22351. }
  22352. }
  22353. else {
  22354. var type = BABYLON.PointerEventTypes.POINTERUP;
  22355. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22356. _this.onPrePointerObservable.notifyObservers(pi, type);
  22357. if (pi.skipOnPointerObservable) {
  22358. return;
  22359. }
  22360. }
  22361. }
  22362. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22363. return;
  22364. }
  22365. if (!_this.pointerUpPredicate) {
  22366. _this.pointerUpPredicate = function (mesh) {
  22367. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22368. };
  22369. }
  22370. // Meshes
  22371. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22372. _this._initActionManager(null, clickInfo);
  22373. }
  22374. if (!pickResult) {
  22375. pickResult = _this._currentPickResult;
  22376. }
  22377. _this._processPointerUp(pickResult, evt, clickInfo);
  22378. // Sprites
  22379. if (_this.spriteManagers.length > 0) {
  22380. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22381. if (spritePickResult) {
  22382. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22383. if (spritePickResult.pickedSprite.actionManager) {
  22384. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22385. if (spritePickResult.pickedSprite.actionManager) {
  22386. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22387. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22388. }
  22389. }
  22390. }
  22391. }
  22392. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22393. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22394. }
  22395. }
  22396. }
  22397. _this._previousPickResult = _this._currentPickResult;
  22398. });
  22399. };
  22400. this._onKeyDown = function (evt) {
  22401. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22402. if (_this.onPreKeyboardObservable.hasObservers()) {
  22403. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22404. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22405. if (pi.skipOnPointerObservable) {
  22406. return;
  22407. }
  22408. }
  22409. if (_this.onKeyboardObservable.hasObservers()) {
  22410. var pi = new BABYLON.KeyboardInfo(type, evt);
  22411. _this.onKeyboardObservable.notifyObservers(pi, type);
  22412. }
  22413. if (_this.actionManager) {
  22414. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22415. }
  22416. };
  22417. this._onKeyUp = function (evt) {
  22418. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22419. if (_this.onPreKeyboardObservable.hasObservers()) {
  22420. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22421. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22422. if (pi.skipOnPointerObservable) {
  22423. return;
  22424. }
  22425. }
  22426. if (_this.onKeyboardObservable.hasObservers()) {
  22427. var pi = new BABYLON.KeyboardInfo(type, evt);
  22428. _this.onKeyboardObservable.notifyObservers(pi, type);
  22429. }
  22430. if (_this.actionManager) {
  22431. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22432. }
  22433. };
  22434. var engine = this.getEngine();
  22435. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22436. if (!canvas) {
  22437. return;
  22438. }
  22439. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22440. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22441. });
  22442. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22443. if (!canvas) {
  22444. return;
  22445. }
  22446. canvas.removeEventListener("keydown", _this._onKeyDown);
  22447. canvas.removeEventListener("keyup", _this._onKeyUp);
  22448. });
  22449. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22450. var canvas = this._engine.getRenderingCanvas();
  22451. if (!canvas) {
  22452. return;
  22453. }
  22454. if (attachMove) {
  22455. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22456. // Wheel
  22457. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22458. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22459. }
  22460. if (attachDown) {
  22461. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22462. }
  22463. if (attachUp) {
  22464. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22465. }
  22466. canvas.tabIndex = 1;
  22467. };
  22468. Scene.prototype.detachControl = function () {
  22469. var engine = this.getEngine();
  22470. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22471. var canvas = engine.getRenderingCanvas();
  22472. if (!canvas) {
  22473. return;
  22474. }
  22475. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22476. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22477. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22478. if (this._onCanvasBlurObserver) {
  22479. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22480. }
  22481. if (this._onCanvasFocusObserver) {
  22482. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22483. }
  22484. // Wheel
  22485. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22486. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22487. // Keyboard
  22488. canvas.removeEventListener("keydown", this._onKeyDown);
  22489. canvas.removeEventListener("keyup", this._onKeyUp);
  22490. // Observables
  22491. this.onKeyboardObservable.clear();
  22492. this.onPreKeyboardObservable.clear();
  22493. this.onPointerObservable.clear();
  22494. this.onPrePointerObservable.clear();
  22495. };
  22496. /**
  22497. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22498. * Delay loaded resources are not taking in account
  22499. * @return true if all required resources are ready
  22500. */
  22501. Scene.prototype.isReady = function () {
  22502. if (this._isDisposed) {
  22503. return false;
  22504. }
  22505. if (this._pendingData.length > 0) {
  22506. return false;
  22507. }
  22508. var index;
  22509. var engine = this.getEngine();
  22510. // Geometries
  22511. for (index = 0; index < this._geometries.length; index++) {
  22512. var geometry = this._geometries[index];
  22513. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22514. return false;
  22515. }
  22516. }
  22517. // Meshes
  22518. for (index = 0; index < this.meshes.length; index++) {
  22519. var mesh = this.meshes[index];
  22520. if (!mesh.isEnabled()) {
  22521. continue;
  22522. }
  22523. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22524. continue;
  22525. }
  22526. if (!mesh.isReady(true)) {
  22527. return false;
  22528. }
  22529. // Effect layers
  22530. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22531. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22532. var layer = _a[_i];
  22533. if (!layer.hasMesh(mesh)) {
  22534. continue;
  22535. }
  22536. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22537. var subMesh = _c[_b];
  22538. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22539. return false;
  22540. }
  22541. }
  22542. }
  22543. }
  22544. return true;
  22545. };
  22546. Scene.prototype.resetCachedMaterial = function () {
  22547. this._cachedMaterial = null;
  22548. this._cachedEffect = null;
  22549. this._cachedVisibility = null;
  22550. };
  22551. Scene.prototype.registerBeforeRender = function (func) {
  22552. this.onBeforeRenderObservable.add(func);
  22553. };
  22554. Scene.prototype.unregisterBeforeRender = function (func) {
  22555. this.onBeforeRenderObservable.removeCallback(func);
  22556. };
  22557. Scene.prototype.registerAfterRender = function (func) {
  22558. this.onAfterRenderObservable.add(func);
  22559. };
  22560. Scene.prototype.unregisterAfterRender = function (func) {
  22561. this.onAfterRenderObservable.removeCallback(func);
  22562. };
  22563. Scene.prototype._executeOnceBeforeRender = function (func) {
  22564. var _this = this;
  22565. var execFunc = function () {
  22566. func();
  22567. setTimeout(function () {
  22568. _this.unregisterBeforeRender(execFunc);
  22569. });
  22570. };
  22571. this.registerBeforeRender(execFunc);
  22572. };
  22573. /**
  22574. * The provided function will run before render once and will be disposed afterwards.
  22575. * A timeout delay can be provided so that the function will be executed in N ms.
  22576. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22577. * @param func The function to be executed.
  22578. * @param timeout optional delay in ms
  22579. */
  22580. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22581. var _this = this;
  22582. if (timeout !== undefined) {
  22583. setTimeout(function () {
  22584. _this._executeOnceBeforeRender(func);
  22585. }, timeout);
  22586. }
  22587. else {
  22588. this._executeOnceBeforeRender(func);
  22589. }
  22590. };
  22591. Scene.prototype._addPendingData = function (data) {
  22592. this._pendingData.push(data);
  22593. };
  22594. Scene.prototype._removePendingData = function (data) {
  22595. var wasLoading = this.isLoading;
  22596. var index = this._pendingData.indexOf(data);
  22597. if (index !== -1) {
  22598. this._pendingData.splice(index, 1);
  22599. }
  22600. if (wasLoading && !this.isLoading) {
  22601. this.onDataLoadedObservable.notifyObservers(this);
  22602. }
  22603. };
  22604. Scene.prototype.getWaitingItemsCount = function () {
  22605. return this._pendingData.length;
  22606. };
  22607. Object.defineProperty(Scene.prototype, "isLoading", {
  22608. get: function () {
  22609. return this._pendingData.length > 0;
  22610. },
  22611. enumerable: true,
  22612. configurable: true
  22613. });
  22614. /**
  22615. * Registers a function to be executed when the scene is ready.
  22616. * @param {Function} func - the function to be executed.
  22617. */
  22618. Scene.prototype.executeWhenReady = function (func) {
  22619. var _this = this;
  22620. this.onReadyObservable.add(func);
  22621. if (this._executeWhenReadyTimeoutId !== -1) {
  22622. return;
  22623. }
  22624. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22625. _this._checkIsReady();
  22626. }, 150);
  22627. };
  22628. /**
  22629. * Returns a promise that resolves when the scene is ready.
  22630. * @returns A promise that resolves when the scene is ready.
  22631. */
  22632. Scene.prototype.whenReadyAsync = function () {
  22633. var _this = this;
  22634. return new Promise(function (resolve) {
  22635. _this.executeWhenReady(function () {
  22636. resolve();
  22637. });
  22638. });
  22639. };
  22640. Scene.prototype._checkIsReady = function () {
  22641. var _this = this;
  22642. if (this.isReady()) {
  22643. this.onReadyObservable.notifyObservers(this);
  22644. this.onReadyObservable.clear();
  22645. this._executeWhenReadyTimeoutId = -1;
  22646. return;
  22647. }
  22648. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22649. _this._checkIsReady();
  22650. }, 150);
  22651. };
  22652. // Animations
  22653. /**
  22654. * Will start the animation sequence of a given target
  22655. * @param target - the target
  22656. * @param {number} from - from which frame should animation start
  22657. * @param {number} to - till which frame should animation run.
  22658. * @param {boolean} [loop] - should the animation loop
  22659. * @param {number} [speedRatio] - the speed in which to run the animation
  22660. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22661. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22662. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22663. * See BABYLON.Animatable
  22664. */
  22665. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22666. if (speedRatio === void 0) { speedRatio = 1.0; }
  22667. if (from > to && speedRatio > 0) {
  22668. speedRatio *= -1;
  22669. }
  22670. this.stopAnimation(target);
  22671. if (!animatable) {
  22672. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22673. }
  22674. // Local animations
  22675. if (target.animations) {
  22676. animatable.appendAnimations(target, target.animations);
  22677. }
  22678. // Children animations
  22679. if (target.getAnimatables) {
  22680. var animatables = target.getAnimatables();
  22681. for (var index = 0; index < animatables.length; index++) {
  22682. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22683. }
  22684. }
  22685. animatable.reset();
  22686. return animatable;
  22687. };
  22688. /**
  22689. * Begin a new animation on a given node
  22690. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22691. * @param {BABYLON.Animation[]} defines the list of animations to start
  22692. * @param {number} from defines the initial value
  22693. * @param {number} to defines the final value
  22694. * @param {boolean} loop defines if you want animation to loop (off by default)
  22695. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22696. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22697. * @returns the list of created animatables
  22698. */
  22699. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22700. if (speedRatio === undefined) {
  22701. speedRatio = 1.0;
  22702. }
  22703. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22704. return animatable;
  22705. };
  22706. /**
  22707. * Begin a new animation on a given node and its hierarchy
  22708. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22709. * @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.
  22710. * @param {BABYLON.Animation[]} defines the list of animations to start
  22711. * @param {number} from defines the initial value
  22712. * @param {number} to defines the final value
  22713. * @param {boolean} loop defines if you want animation to loop (off by default)
  22714. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22715. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22716. * @returns the list of animatables created for all nodes
  22717. */
  22718. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22719. var children = target.getDescendants(directDescendantsOnly);
  22720. var result = [];
  22721. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22722. var child = children_1[_i];
  22723. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22724. }
  22725. return result;
  22726. };
  22727. Scene.prototype.getAnimatableByTarget = function (target) {
  22728. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22729. if (this._activeAnimatables[index].target === target) {
  22730. return this._activeAnimatables[index];
  22731. }
  22732. }
  22733. return null;
  22734. };
  22735. Object.defineProperty(Scene.prototype, "animatables", {
  22736. get: function () {
  22737. return this._activeAnimatables;
  22738. },
  22739. enumerable: true,
  22740. configurable: true
  22741. });
  22742. /**
  22743. * Will stop the animation of the given target
  22744. * @param target - the target
  22745. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22746. * @see beginAnimation
  22747. */
  22748. Scene.prototype.stopAnimation = function (target, animationName) {
  22749. var animatable = this.getAnimatableByTarget(target);
  22750. if (animatable) {
  22751. animatable.stop(animationName);
  22752. }
  22753. };
  22754. /**
  22755. * Stops and removes all animations that have been applied to the scene
  22756. */
  22757. Scene.prototype.stopAllAnimations = function () {
  22758. if (this._activeAnimatables) {
  22759. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22760. this._activeAnimatables[i].stop();
  22761. }
  22762. this._activeAnimatables = [];
  22763. }
  22764. };
  22765. Scene.prototype._animate = function () {
  22766. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22767. return;
  22768. }
  22769. // Getting time
  22770. var now = BABYLON.Tools.Now;
  22771. if (!this._animationTimeLast) {
  22772. if (this._pendingData.length > 0) {
  22773. return;
  22774. }
  22775. this._animationTimeLast = now;
  22776. }
  22777. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22778. this._animationTime += deltaTime;
  22779. this._animationTimeLast = now;
  22780. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22781. this._activeAnimatables[index]._animate(this._animationTime);
  22782. }
  22783. };
  22784. // Matrix
  22785. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22786. this._useAlternateCameraConfiguration = active;
  22787. };
  22788. Scene.prototype.getViewMatrix = function () {
  22789. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22790. };
  22791. Scene.prototype.getProjectionMatrix = function () {
  22792. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22793. };
  22794. Scene.prototype.getTransformMatrix = function () {
  22795. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22796. };
  22797. Scene.prototype.setTransformMatrix = function (view, projection) {
  22798. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22799. return;
  22800. }
  22801. this._viewUpdateFlag = view.updateFlag;
  22802. this._projectionUpdateFlag = projection.updateFlag;
  22803. this._viewMatrix = view;
  22804. this._projectionMatrix = projection;
  22805. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22806. // Update frustum
  22807. if (!this._frustumPlanes) {
  22808. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22809. }
  22810. else {
  22811. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22812. }
  22813. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22814. var otherCamera = this.activeCamera._alternateCamera;
  22815. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22816. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22817. }
  22818. if (this._sceneUbo.useUbo) {
  22819. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22820. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22821. this._sceneUbo.update();
  22822. }
  22823. };
  22824. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22825. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22826. return;
  22827. }
  22828. this._alternateViewUpdateFlag = view.updateFlag;
  22829. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22830. this._alternateViewMatrix = view;
  22831. this._alternateProjectionMatrix = projection;
  22832. if (!this._alternateTransformMatrix) {
  22833. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22834. }
  22835. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22836. if (!this._alternateSceneUbo) {
  22837. this._createAlternateUbo();
  22838. }
  22839. if (this._alternateSceneUbo.useUbo) {
  22840. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22841. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22842. this._alternateSceneUbo.update();
  22843. }
  22844. };
  22845. Scene.prototype.getSceneUniformBuffer = function () {
  22846. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22847. };
  22848. // Methods
  22849. Scene.prototype.getUniqueId = function () {
  22850. var result = Scene._uniqueIdCounter;
  22851. Scene._uniqueIdCounter++;
  22852. return result;
  22853. };
  22854. Scene.prototype.addMesh = function (newMesh) {
  22855. this.meshes.push(newMesh);
  22856. //notify the collision coordinator
  22857. if (this.collisionCoordinator) {
  22858. this.collisionCoordinator.onMeshAdded(newMesh);
  22859. }
  22860. newMesh._resyncLightSources();
  22861. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22862. };
  22863. Scene.prototype.removeMesh = function (toRemove) {
  22864. var index = this.meshes.indexOf(toRemove);
  22865. if (index !== -1) {
  22866. // Remove from the scene if mesh found
  22867. this.meshes.splice(index, 1);
  22868. }
  22869. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22870. return index;
  22871. };
  22872. Scene.prototype.addTransformNode = function (newTransformNode) {
  22873. this.transformNodes.push(newTransformNode);
  22874. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22875. };
  22876. Scene.prototype.removeTransformNode = function (toRemove) {
  22877. var index = this.transformNodes.indexOf(toRemove);
  22878. if (index !== -1) {
  22879. // Remove from the scene if found
  22880. this.transformNodes.splice(index, 1);
  22881. }
  22882. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22883. return index;
  22884. };
  22885. Scene.prototype.removeSkeleton = function (toRemove) {
  22886. var index = this.skeletons.indexOf(toRemove);
  22887. if (index !== -1) {
  22888. // Remove from the scene if found
  22889. this.skeletons.splice(index, 1);
  22890. }
  22891. return index;
  22892. };
  22893. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22894. var index = this.morphTargetManagers.indexOf(toRemove);
  22895. if (index !== -1) {
  22896. // Remove from the scene if found
  22897. this.morphTargetManagers.splice(index, 1);
  22898. }
  22899. return index;
  22900. };
  22901. Scene.prototype.removeLight = function (toRemove) {
  22902. var index = this.lights.indexOf(toRemove);
  22903. if (index !== -1) {
  22904. // Remove from meshes
  22905. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22906. var mesh = _a[_i];
  22907. mesh._removeLightSource(toRemove);
  22908. }
  22909. // Remove from the scene if mesh found
  22910. this.lights.splice(index, 1);
  22911. this.sortLightsByPriority();
  22912. }
  22913. this.onLightRemovedObservable.notifyObservers(toRemove);
  22914. return index;
  22915. };
  22916. Scene.prototype.removeCamera = function (toRemove) {
  22917. var index = this.cameras.indexOf(toRemove);
  22918. if (index !== -1) {
  22919. // Remove from the scene if mesh found
  22920. this.cameras.splice(index, 1);
  22921. }
  22922. // Remove from activeCameras
  22923. var index2 = this.activeCameras.indexOf(toRemove);
  22924. if (index2 !== -1) {
  22925. // Remove from the scene if mesh found
  22926. this.activeCameras.splice(index2, 1);
  22927. }
  22928. // Reset the activeCamera
  22929. if (this.activeCamera === toRemove) {
  22930. if (this.cameras.length > 0) {
  22931. this.activeCamera = this.cameras[0];
  22932. }
  22933. else {
  22934. this.activeCamera = null;
  22935. }
  22936. }
  22937. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22938. return index;
  22939. };
  22940. Scene.prototype.removeParticleSystem = function (toRemove) {
  22941. var index = this.particleSystems.indexOf(toRemove);
  22942. if (index !== -1) {
  22943. this.particleSystems.splice(index, 1);
  22944. }
  22945. return index;
  22946. };
  22947. ;
  22948. Scene.prototype.removeAnimation = function (toRemove) {
  22949. var index = this.animations.indexOf(toRemove);
  22950. if (index !== -1) {
  22951. this.animations.splice(index, 1);
  22952. }
  22953. return index;
  22954. };
  22955. ;
  22956. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22957. var index = this.multiMaterials.indexOf(toRemove);
  22958. if (index !== -1) {
  22959. this.multiMaterials.splice(index, 1);
  22960. }
  22961. return index;
  22962. };
  22963. ;
  22964. Scene.prototype.removeMaterial = function (toRemove) {
  22965. var index = this.materials.indexOf(toRemove);
  22966. if (index !== -1) {
  22967. this.materials.splice(index, 1);
  22968. }
  22969. return index;
  22970. };
  22971. ;
  22972. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22973. var index = this.lensFlareSystems.indexOf(toRemove);
  22974. if (index !== -1) {
  22975. this.lensFlareSystems.splice(index, 1);
  22976. }
  22977. return index;
  22978. };
  22979. ;
  22980. Scene.prototype.removeActionManager = function (toRemove) {
  22981. var index = this._actionManagers.indexOf(toRemove);
  22982. if (index !== -1) {
  22983. this._actionManagers.splice(index, 1);
  22984. }
  22985. return index;
  22986. };
  22987. ;
  22988. Scene.prototype.addLight = function (newLight) {
  22989. this.lights.push(newLight);
  22990. this.sortLightsByPriority();
  22991. // Add light to all meshes (To support if the light is removed and then readded)
  22992. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22993. var mesh = _a[_i];
  22994. if (mesh._lightSources.indexOf(newLight) === -1) {
  22995. mesh._lightSources.push(newLight);
  22996. mesh._resyncLightSources();
  22997. }
  22998. }
  22999. this.onNewLightAddedObservable.notifyObservers(newLight);
  23000. };
  23001. Scene.prototype.sortLightsByPriority = function () {
  23002. if (this.requireLightSorting) {
  23003. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23004. }
  23005. };
  23006. Scene.prototype.addCamera = function (newCamera) {
  23007. this.cameras.push(newCamera);
  23008. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23009. };
  23010. Scene.prototype.addSkeleton = function (newSkeleton) {
  23011. this.skeletons.push(newSkeleton);
  23012. };
  23013. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23014. this.particleSystems.push(newParticleSystem);
  23015. };
  23016. Scene.prototype.addAnimation = function (newAnimation) {
  23017. this.animations.push(newAnimation);
  23018. };
  23019. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23020. this.multiMaterials.push(newMultiMaterial);
  23021. };
  23022. Scene.prototype.addMaterial = function (newMaterial) {
  23023. this.materials.push(newMaterial);
  23024. };
  23025. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23026. this.morphTargetManagers.push(newMorphTargetManager);
  23027. };
  23028. Scene.prototype.addGeometry = function (newGeometrie) {
  23029. this._geometries.push(newGeometrie);
  23030. };
  23031. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23032. this.lensFlareSystems.push(newLensFlareSystem);
  23033. };
  23034. Scene.prototype.addActionManager = function (newActionManager) {
  23035. this._actionManagers.push(newActionManager);
  23036. };
  23037. /**
  23038. * Switch active camera
  23039. * @param {Camera} newCamera - new active camera
  23040. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23041. */
  23042. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23043. if (attachControl === void 0) { attachControl = true; }
  23044. var canvas = this._engine.getRenderingCanvas();
  23045. if (!canvas) {
  23046. return;
  23047. }
  23048. if (this.activeCamera) {
  23049. this.activeCamera.detachControl(canvas);
  23050. }
  23051. this.activeCamera = newCamera;
  23052. if (attachControl) {
  23053. newCamera.attachControl(canvas);
  23054. }
  23055. };
  23056. /**
  23057. * sets the active camera of the scene using its ID
  23058. * @param {string} id - the camera's ID
  23059. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23060. * @see activeCamera
  23061. */
  23062. Scene.prototype.setActiveCameraByID = function (id) {
  23063. var camera = this.getCameraByID(id);
  23064. if (camera) {
  23065. this.activeCamera = camera;
  23066. return camera;
  23067. }
  23068. return null;
  23069. };
  23070. /**
  23071. * sets the active camera of the scene using its name
  23072. * @param {string} name - the camera's name
  23073. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23074. * @see activeCamera
  23075. */
  23076. Scene.prototype.setActiveCameraByName = function (name) {
  23077. var camera = this.getCameraByName(name);
  23078. if (camera) {
  23079. this.activeCamera = camera;
  23080. return camera;
  23081. }
  23082. return null;
  23083. };
  23084. /**
  23085. * get an animation group using its name
  23086. * @param {string} the material's name
  23087. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23088. */
  23089. Scene.prototype.getAnimationGroupByName = function (name) {
  23090. for (var index = 0; index < this.animationGroups.length; index++) {
  23091. if (this.animationGroups[index].name === name) {
  23092. return this.animationGroups[index];
  23093. }
  23094. }
  23095. return null;
  23096. };
  23097. /**
  23098. * get a material using its id
  23099. * @param {string} the material's ID
  23100. * @return {BABYLON.Material|null} the material or null if none found.
  23101. */
  23102. Scene.prototype.getMaterialByID = function (id) {
  23103. for (var index = 0; index < this.materials.length; index++) {
  23104. if (this.materials[index].id === id) {
  23105. return this.materials[index];
  23106. }
  23107. }
  23108. return null;
  23109. };
  23110. /**
  23111. * get a material using its name
  23112. * @param {string} the material's name
  23113. * @return {BABYLON.Material|null} the material or null if none found.
  23114. */
  23115. Scene.prototype.getMaterialByName = function (name) {
  23116. for (var index = 0; index < this.materials.length; index++) {
  23117. if (this.materials[index].name === name) {
  23118. return this.materials[index];
  23119. }
  23120. }
  23121. return null;
  23122. };
  23123. Scene.prototype.getLensFlareSystemByName = function (name) {
  23124. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23125. if (this.lensFlareSystems[index].name === name) {
  23126. return this.lensFlareSystems[index];
  23127. }
  23128. }
  23129. return null;
  23130. };
  23131. Scene.prototype.getLensFlareSystemByID = function (id) {
  23132. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23133. if (this.lensFlareSystems[index].id === id) {
  23134. return this.lensFlareSystems[index];
  23135. }
  23136. }
  23137. return null;
  23138. };
  23139. Scene.prototype.getCameraByID = function (id) {
  23140. for (var index = 0; index < this.cameras.length; index++) {
  23141. if (this.cameras[index].id === id) {
  23142. return this.cameras[index];
  23143. }
  23144. }
  23145. return null;
  23146. };
  23147. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23148. for (var index = 0; index < this.cameras.length; index++) {
  23149. if (this.cameras[index].uniqueId === uniqueId) {
  23150. return this.cameras[index];
  23151. }
  23152. }
  23153. return null;
  23154. };
  23155. /**
  23156. * get a camera using its name
  23157. * @param {string} the camera's name
  23158. * @return {BABYLON.Camera|null} the camera or null if none found.
  23159. */
  23160. Scene.prototype.getCameraByName = function (name) {
  23161. for (var index = 0; index < this.cameras.length; index++) {
  23162. if (this.cameras[index].name === name) {
  23163. return this.cameras[index];
  23164. }
  23165. }
  23166. return null;
  23167. };
  23168. /**
  23169. * get a bone using its id
  23170. * @param {string} the bone's id
  23171. * @return {BABYLON.Bone|null} the bone or null if not found
  23172. */
  23173. Scene.prototype.getBoneByID = function (id) {
  23174. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23175. var skeleton = this.skeletons[skeletonIndex];
  23176. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23177. if (skeleton.bones[boneIndex].id === id) {
  23178. return skeleton.bones[boneIndex];
  23179. }
  23180. }
  23181. }
  23182. return null;
  23183. };
  23184. /**
  23185. * get a bone using its id
  23186. * @param {string} the bone's name
  23187. * @return {BABYLON.Bone|null} the bone or null if not found
  23188. */
  23189. Scene.prototype.getBoneByName = function (name) {
  23190. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23191. var skeleton = this.skeletons[skeletonIndex];
  23192. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23193. if (skeleton.bones[boneIndex].name === name) {
  23194. return skeleton.bones[boneIndex];
  23195. }
  23196. }
  23197. }
  23198. return null;
  23199. };
  23200. /**
  23201. * get a light node using its name
  23202. * @param {string} the light's name
  23203. * @return {BABYLON.Light|null} the light or null if none found.
  23204. */
  23205. Scene.prototype.getLightByName = function (name) {
  23206. for (var index = 0; index < this.lights.length; index++) {
  23207. if (this.lights[index].name === name) {
  23208. return this.lights[index];
  23209. }
  23210. }
  23211. return null;
  23212. };
  23213. /**
  23214. * get a light node using its ID
  23215. * @param {string} the light's id
  23216. * @return {BABYLON.Light|null} the light or null if none found.
  23217. */
  23218. Scene.prototype.getLightByID = function (id) {
  23219. for (var index = 0; index < this.lights.length; index++) {
  23220. if (this.lights[index].id === id) {
  23221. return this.lights[index];
  23222. }
  23223. }
  23224. return null;
  23225. };
  23226. /**
  23227. * get a light node using its scene-generated unique ID
  23228. * @param {number} the light's unique id
  23229. * @return {BABYLON.Light|null} the light or null if none found.
  23230. */
  23231. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23232. for (var index = 0; index < this.lights.length; index++) {
  23233. if (this.lights[index].uniqueId === uniqueId) {
  23234. return this.lights[index];
  23235. }
  23236. }
  23237. return null;
  23238. };
  23239. /**
  23240. * get a particle system by id
  23241. * @param id {number} the particle system id
  23242. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23243. */
  23244. Scene.prototype.getParticleSystemByID = function (id) {
  23245. for (var index = 0; index < this.particleSystems.length; index++) {
  23246. if (this.particleSystems[index].id === id) {
  23247. return this.particleSystems[index];
  23248. }
  23249. }
  23250. return null;
  23251. };
  23252. /**
  23253. * get a geometry using its ID
  23254. * @param {string} the geometry's id
  23255. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23256. */
  23257. Scene.prototype.getGeometryByID = function (id) {
  23258. for (var index = 0; index < this._geometries.length; index++) {
  23259. if (this._geometries[index].id === id) {
  23260. return this._geometries[index];
  23261. }
  23262. }
  23263. return null;
  23264. };
  23265. /**
  23266. * add a new geometry to this scene.
  23267. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23268. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23269. * @return {boolean} was the geometry added or not
  23270. */
  23271. Scene.prototype.pushGeometry = function (geometry, force) {
  23272. if (!force && this.getGeometryByID(geometry.id)) {
  23273. return false;
  23274. }
  23275. this._geometries.push(geometry);
  23276. //notify the collision coordinator
  23277. if (this.collisionCoordinator) {
  23278. this.collisionCoordinator.onGeometryAdded(geometry);
  23279. }
  23280. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23281. return true;
  23282. };
  23283. /**
  23284. * Removes an existing geometry
  23285. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23286. * @return {boolean} was the geometry removed or not
  23287. */
  23288. Scene.prototype.removeGeometry = function (geometry) {
  23289. var index = this._geometries.indexOf(geometry);
  23290. if (index > -1) {
  23291. this._geometries.splice(index, 1);
  23292. //notify the collision coordinator
  23293. if (this.collisionCoordinator) {
  23294. this.collisionCoordinator.onGeometryDeleted(geometry);
  23295. }
  23296. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23297. return true;
  23298. }
  23299. return false;
  23300. };
  23301. Scene.prototype.getGeometries = function () {
  23302. return this._geometries;
  23303. };
  23304. /**
  23305. * Get the first added mesh found of a given ID
  23306. * @param {string} id - the id to search for
  23307. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23308. */
  23309. Scene.prototype.getMeshByID = function (id) {
  23310. for (var index = 0; index < this.meshes.length; index++) {
  23311. if (this.meshes[index].id === id) {
  23312. return this.meshes[index];
  23313. }
  23314. }
  23315. return null;
  23316. };
  23317. Scene.prototype.getMeshesByID = function (id) {
  23318. return this.meshes.filter(function (m) {
  23319. return m.id === id;
  23320. });
  23321. };
  23322. /**
  23323. * Get the first added transform node found of a given ID
  23324. * @param {string} id - the id to search for
  23325. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23326. */
  23327. Scene.prototype.getTransformNodeByID = function (id) {
  23328. for (var index = 0; index < this.transformNodes.length; index++) {
  23329. if (this.transformNodes[index].id === id) {
  23330. return this.transformNodes[index];
  23331. }
  23332. }
  23333. return null;
  23334. };
  23335. Scene.prototype.getTransformNodesByID = function (id) {
  23336. return this.transformNodes.filter(function (m) {
  23337. return m.id === id;
  23338. });
  23339. };
  23340. /**
  23341. * Get a mesh with its auto-generated unique id
  23342. * @param {number} uniqueId - the unique id to search for
  23343. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23344. */
  23345. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23346. for (var index = 0; index < this.meshes.length; index++) {
  23347. if (this.meshes[index].uniqueId === uniqueId) {
  23348. return this.meshes[index];
  23349. }
  23350. }
  23351. return null;
  23352. };
  23353. /**
  23354. * Get a the last added mesh found of a given ID
  23355. * @param {string} id - the id to search for
  23356. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23357. */
  23358. Scene.prototype.getLastMeshByID = function (id) {
  23359. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23360. if (this.meshes[index].id === id) {
  23361. return this.meshes[index];
  23362. }
  23363. }
  23364. return null;
  23365. };
  23366. /**
  23367. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23368. * @param {string} id - the id to search for
  23369. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23370. */
  23371. Scene.prototype.getLastEntryByID = function (id) {
  23372. var index;
  23373. for (index = this.meshes.length - 1; index >= 0; index--) {
  23374. if (this.meshes[index].id === id) {
  23375. return this.meshes[index];
  23376. }
  23377. }
  23378. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23379. if (this.transformNodes[index].id === id) {
  23380. return this.transformNodes[index];
  23381. }
  23382. }
  23383. for (index = this.cameras.length - 1; index >= 0; index--) {
  23384. if (this.cameras[index].id === id) {
  23385. return this.cameras[index];
  23386. }
  23387. }
  23388. for (index = this.lights.length - 1; index >= 0; index--) {
  23389. if (this.lights[index].id === id) {
  23390. return this.lights[index];
  23391. }
  23392. }
  23393. return null;
  23394. };
  23395. Scene.prototype.getNodeByID = function (id) {
  23396. var mesh = this.getMeshByID(id);
  23397. if (mesh) {
  23398. return mesh;
  23399. }
  23400. var light = this.getLightByID(id);
  23401. if (light) {
  23402. return light;
  23403. }
  23404. var camera = this.getCameraByID(id);
  23405. if (camera) {
  23406. return camera;
  23407. }
  23408. var bone = this.getBoneByID(id);
  23409. return bone;
  23410. };
  23411. Scene.prototype.getNodeByName = function (name) {
  23412. var mesh = this.getMeshByName(name);
  23413. if (mesh) {
  23414. return mesh;
  23415. }
  23416. var light = this.getLightByName(name);
  23417. if (light) {
  23418. return light;
  23419. }
  23420. var camera = this.getCameraByName(name);
  23421. if (camera) {
  23422. return camera;
  23423. }
  23424. var bone = this.getBoneByName(name);
  23425. return bone;
  23426. };
  23427. Scene.prototype.getMeshByName = function (name) {
  23428. for (var index = 0; index < this.meshes.length; index++) {
  23429. if (this.meshes[index].name === name) {
  23430. return this.meshes[index];
  23431. }
  23432. }
  23433. return null;
  23434. };
  23435. Scene.prototype.getTransformNodeByName = function (name) {
  23436. for (var index = 0; index < this.transformNodes.length; index++) {
  23437. if (this.transformNodes[index].name === name) {
  23438. return this.transformNodes[index];
  23439. }
  23440. }
  23441. return null;
  23442. };
  23443. Scene.prototype.getSoundByName = function (name) {
  23444. var index;
  23445. if (BABYLON.AudioEngine) {
  23446. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23447. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23448. return this.mainSoundTrack.soundCollection[index];
  23449. }
  23450. }
  23451. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23452. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23453. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23454. return this.soundTracks[sdIndex].soundCollection[index];
  23455. }
  23456. }
  23457. }
  23458. }
  23459. return null;
  23460. };
  23461. Scene.prototype.getLastSkeletonByID = function (id) {
  23462. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23463. if (this.skeletons[index].id === id) {
  23464. return this.skeletons[index];
  23465. }
  23466. }
  23467. return null;
  23468. };
  23469. Scene.prototype.getSkeletonById = function (id) {
  23470. for (var index = 0; index < this.skeletons.length; index++) {
  23471. if (this.skeletons[index].id === id) {
  23472. return this.skeletons[index];
  23473. }
  23474. }
  23475. return null;
  23476. };
  23477. Scene.prototype.getSkeletonByName = function (name) {
  23478. for (var index = 0; index < this.skeletons.length; index++) {
  23479. if (this.skeletons[index].name === name) {
  23480. return this.skeletons[index];
  23481. }
  23482. }
  23483. return null;
  23484. };
  23485. Scene.prototype.getMorphTargetManagerById = function (id) {
  23486. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23487. if (this.morphTargetManagers[index].uniqueId === id) {
  23488. return this.morphTargetManagers[index];
  23489. }
  23490. }
  23491. return null;
  23492. };
  23493. Scene.prototype.isActiveMesh = function (mesh) {
  23494. return (this._activeMeshes.indexOf(mesh) !== -1);
  23495. };
  23496. /**
  23497. * Return a the first highlight layer of the scene with a given name.
  23498. * @param name The name of the highlight layer to look for.
  23499. * @return The highlight layer if found otherwise null.
  23500. */
  23501. Scene.prototype.getHighlightLayerByName = function (name) {
  23502. for (var index = 0; index < this.effectLayers.length; index++) {
  23503. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23504. return this.effectLayers[index];
  23505. }
  23506. }
  23507. return null;
  23508. };
  23509. /**
  23510. * Return a the first highlight layer of the scene with a given name.
  23511. * @param name The name of the highlight layer to look for.
  23512. * @return The highlight layer if found otherwise null.
  23513. */
  23514. Scene.prototype.getGlowLayerByName = function (name) {
  23515. for (var index = 0; index < this.effectLayers.length; index++) {
  23516. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23517. return this.effectLayers[index];
  23518. }
  23519. }
  23520. return null;
  23521. };
  23522. Object.defineProperty(Scene.prototype, "uid", {
  23523. /**
  23524. * Return a unique id as a string which can serve as an identifier for the scene
  23525. */
  23526. get: function () {
  23527. if (!this._uid) {
  23528. this._uid = BABYLON.Tools.RandomId();
  23529. }
  23530. return this._uid;
  23531. },
  23532. enumerable: true,
  23533. configurable: true
  23534. });
  23535. /**
  23536. * Add an externaly attached data from its key.
  23537. * This method call will fail and return false, if such key already exists.
  23538. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23539. * @param key the unique key that identifies the data
  23540. * @param data the data object to associate to the key for this Engine instance
  23541. * @return true if no such key were already present and the data was added successfully, false otherwise
  23542. */
  23543. Scene.prototype.addExternalData = function (key, data) {
  23544. if (!this._externalData) {
  23545. this._externalData = new BABYLON.StringDictionary();
  23546. }
  23547. return this._externalData.add(key, data);
  23548. };
  23549. /**
  23550. * Get an externaly attached data from its key
  23551. * @param key the unique key that identifies the data
  23552. * @return the associated data, if present (can be null), or undefined if not present
  23553. */
  23554. Scene.prototype.getExternalData = function (key) {
  23555. if (!this._externalData) {
  23556. return null;
  23557. }
  23558. return this._externalData.get(key);
  23559. };
  23560. /**
  23561. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23562. * @param key the unique key that identifies the data
  23563. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23564. * @return the associated data, can be null if the factory returned null.
  23565. */
  23566. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23567. if (!this._externalData) {
  23568. this._externalData = new BABYLON.StringDictionary();
  23569. }
  23570. return this._externalData.getOrAddWithFactory(key, factory);
  23571. };
  23572. /**
  23573. * Remove an externaly attached data from the Engine instance
  23574. * @param key the unique key that identifies the data
  23575. * @return true if the data was successfully removed, false if it doesn't exist
  23576. */
  23577. Scene.prototype.removeExternalData = function (key) {
  23578. return this._externalData.remove(key);
  23579. };
  23580. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23581. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23582. if (mesh.showSubMeshesBoundingBox) {
  23583. var boundingInfo = subMesh.getBoundingInfo();
  23584. if (boundingInfo !== null && boundingInfo !== undefined) {
  23585. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23586. }
  23587. }
  23588. var material = subMesh.getMaterial();
  23589. if (material !== null && material !== undefined) {
  23590. // Render targets
  23591. if (material.getRenderTargetTextures !== undefined) {
  23592. if (this._processedMaterials.indexOf(material) === -1) {
  23593. this._processedMaterials.push(material);
  23594. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23595. }
  23596. }
  23597. // Dispatch
  23598. this._activeIndices.addCount(subMesh.indexCount, false);
  23599. this._renderingManager.dispatch(subMesh, mesh, material);
  23600. }
  23601. }
  23602. };
  23603. Scene.prototype._isInIntermediateRendering = function () {
  23604. return this._intermediateRendering;
  23605. };
  23606. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23607. this._activeMeshCandidateProvider = provider;
  23608. };
  23609. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23610. return this._activeMeshCandidateProvider;
  23611. };
  23612. /**
  23613. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23614. */
  23615. Scene.prototype.freezeActiveMeshes = function () {
  23616. this._evaluateActiveMeshes();
  23617. this._activeMeshesFrozen = true;
  23618. return this;
  23619. };
  23620. /**
  23621. * Use this function to restart evaluating active meshes on every frame
  23622. */
  23623. Scene.prototype.unfreezeActiveMeshes = function () {
  23624. this._activeMeshesFrozen = false;
  23625. return this;
  23626. };
  23627. Scene.prototype._evaluateActiveMeshes = function () {
  23628. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23629. return;
  23630. }
  23631. if (!this.activeCamera) {
  23632. return;
  23633. }
  23634. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23635. this.activeCamera._activeMeshes.reset();
  23636. this._activeMeshes.reset();
  23637. this._renderingManager.reset();
  23638. this._processedMaterials.reset();
  23639. this._activeParticleSystems.reset();
  23640. this._activeSkeletons.reset();
  23641. this._softwareSkinnedMeshes.reset();
  23642. if (this._boundingBoxRenderer) {
  23643. this._boundingBoxRenderer.reset();
  23644. }
  23645. // Meshes
  23646. var meshes;
  23647. var len;
  23648. var checkIsEnabled = true;
  23649. // Determine mesh candidates
  23650. if (this._activeMeshCandidateProvider !== undefined) {
  23651. // Use _activeMeshCandidateProvider
  23652. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23653. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23654. if (meshes !== undefined) {
  23655. len = meshes.length;
  23656. }
  23657. else {
  23658. len = 0;
  23659. }
  23660. }
  23661. else if (this._selectionOctree !== undefined) {
  23662. // Octree
  23663. var selection = this._selectionOctree.select(this._frustumPlanes);
  23664. meshes = selection.data;
  23665. len = selection.length;
  23666. }
  23667. else {
  23668. // Full scene traversal
  23669. len = this.meshes.length;
  23670. meshes = this.meshes;
  23671. }
  23672. // Check each mesh
  23673. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23674. mesh = meshes[meshIndex];
  23675. if (mesh.isBlocked) {
  23676. continue;
  23677. }
  23678. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23679. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23680. continue;
  23681. }
  23682. mesh.computeWorldMatrix();
  23683. // Intersections
  23684. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23685. this._meshesForIntersections.pushNoDuplicate(mesh);
  23686. }
  23687. // Switch to current LOD
  23688. meshLOD = mesh.getLOD(this.activeCamera);
  23689. if (meshLOD === undefined || meshLOD === null) {
  23690. continue;
  23691. }
  23692. mesh._preActivate();
  23693. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23694. this._activeMeshes.push(mesh);
  23695. this.activeCamera._activeMeshes.push(mesh);
  23696. mesh._activate(this._renderId);
  23697. if (meshLOD !== mesh) {
  23698. meshLOD._activate(this._renderId);
  23699. }
  23700. this._activeMesh(mesh, meshLOD);
  23701. }
  23702. }
  23703. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23704. // Particle systems
  23705. if (this.particlesEnabled) {
  23706. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23707. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23708. var particleSystem = this.particleSystems[particleIndex];
  23709. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23710. continue;
  23711. }
  23712. var emitter = particleSystem.emitter;
  23713. if (!emitter.position || emitter.isEnabled()) {
  23714. this._activeParticleSystems.push(particleSystem);
  23715. particleSystem.animate();
  23716. this._renderingManager.dispatchParticles(particleSystem);
  23717. }
  23718. }
  23719. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23720. }
  23721. };
  23722. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23723. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23724. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23725. mesh.skeleton.prepare();
  23726. }
  23727. if (!mesh.computeBonesUsingShaders) {
  23728. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23729. }
  23730. }
  23731. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23732. var boundingInfo = sourceMesh.getBoundingInfo();
  23733. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23734. }
  23735. if (mesh !== undefined && mesh !== null
  23736. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23737. // Submeshes Octrees
  23738. var len;
  23739. var subMeshes;
  23740. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23741. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23742. len = intersections.length;
  23743. subMeshes = intersections.data;
  23744. }
  23745. else {
  23746. subMeshes = mesh.subMeshes;
  23747. len = subMeshes.length;
  23748. }
  23749. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23750. subMesh = subMeshes[subIndex];
  23751. this._evaluateSubMesh(subMesh, mesh);
  23752. }
  23753. }
  23754. };
  23755. Scene.prototype.updateTransformMatrix = function (force) {
  23756. if (!this.activeCamera) {
  23757. return;
  23758. }
  23759. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23760. };
  23761. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23762. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23763. };
  23764. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23765. if (camera && camera._skipRendering) {
  23766. return;
  23767. }
  23768. var engine = this._engine;
  23769. this.activeCamera = camera;
  23770. if (!this.activeCamera)
  23771. throw new Error("Active camera not set");
  23772. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23773. // Viewport
  23774. engine.setViewport(this.activeCamera.viewport);
  23775. // Camera
  23776. this.resetCachedMaterial();
  23777. this._renderId++;
  23778. this.activeCamera.update();
  23779. this.updateTransformMatrix();
  23780. if (camera._alternateCamera) {
  23781. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23782. this._alternateRendering = true;
  23783. }
  23784. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23785. // Meshes
  23786. this._evaluateActiveMeshes();
  23787. // Software skinning
  23788. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23789. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23790. mesh.applySkeleton(mesh.skeleton);
  23791. }
  23792. // Render targets
  23793. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23794. var needsRestoreFrameBuffer = false;
  23795. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23796. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23797. }
  23798. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23799. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23800. }
  23801. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23802. this._intermediateRendering = true;
  23803. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23804. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23805. var renderTarget = this._renderTargets.data[renderIndex];
  23806. if (renderTarget._shouldRender()) {
  23807. this._renderId++;
  23808. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23809. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23810. }
  23811. }
  23812. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23813. this._intermediateRendering = false;
  23814. this._renderId++;
  23815. needsRestoreFrameBuffer = true; // Restore back buffer
  23816. }
  23817. // Render EffecttLayer Texture
  23818. var stencilState = this._engine.getStencilBuffer();
  23819. var renderEffects = false;
  23820. var needStencil = false;
  23821. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23822. this._intermediateRendering = true;
  23823. for (var i = 0; i < this.effectLayers.length; i++) {
  23824. var effectLayer = this.effectLayers[i];
  23825. if (effectLayer.shouldRender() &&
  23826. (!effectLayer.camera ||
  23827. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23828. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23829. renderEffects = true;
  23830. needStencil = needStencil || effectLayer.needStencil();
  23831. var renderTarget = effectLayer._mainTexture;
  23832. if (renderTarget._shouldRender()) {
  23833. this._renderId++;
  23834. renderTarget.render(false, false);
  23835. needsRestoreFrameBuffer = true;
  23836. }
  23837. }
  23838. }
  23839. this._intermediateRendering = false;
  23840. this._renderId++;
  23841. }
  23842. if (needsRestoreFrameBuffer) {
  23843. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23844. }
  23845. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23846. // Prepare Frame
  23847. this.postProcessManager._prepareFrame();
  23848. // Backgrounds
  23849. var layerIndex;
  23850. var layer;
  23851. if (this.layers.length) {
  23852. engine.setDepthBuffer(false);
  23853. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23854. layer = this.layers[layerIndex];
  23855. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23856. layer.render();
  23857. }
  23858. }
  23859. engine.setDepthBuffer(true);
  23860. }
  23861. // Activate effect Layer stencil
  23862. if (needStencil) {
  23863. this._engine.setStencilBuffer(true);
  23864. }
  23865. // Render
  23866. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23867. this._renderingManager.render(null, null, true, true);
  23868. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23869. // Restore effect Layer stencil
  23870. if (needStencil) {
  23871. this._engine.setStencilBuffer(stencilState);
  23872. }
  23873. // Bounding boxes
  23874. if (this._boundingBoxRenderer) {
  23875. this._boundingBoxRenderer.render();
  23876. }
  23877. // Lens flares
  23878. if (this.lensFlaresEnabled) {
  23879. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23880. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23881. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23882. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23883. lensFlareSystem.render();
  23884. }
  23885. }
  23886. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23887. }
  23888. // Foregrounds
  23889. if (this.layers.length) {
  23890. engine.setDepthBuffer(false);
  23891. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23892. layer = this.layers[layerIndex];
  23893. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23894. layer.render();
  23895. }
  23896. }
  23897. engine.setDepthBuffer(true);
  23898. }
  23899. // Effect Layer
  23900. if (renderEffects) {
  23901. engine.setDepthBuffer(false);
  23902. for (var i = 0; i < this.effectLayers.length; i++) {
  23903. if (this.effectLayers[i].shouldRender()) {
  23904. this.effectLayers[i].render();
  23905. }
  23906. }
  23907. engine.setDepthBuffer(true);
  23908. }
  23909. // Finalize frame
  23910. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23911. // Reset some special arrays
  23912. this._renderTargets.reset();
  23913. this._alternateRendering = false;
  23914. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23915. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23916. };
  23917. Scene.prototype._processSubCameras = function (camera) {
  23918. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23919. this._renderForCamera(camera);
  23920. return;
  23921. }
  23922. // Update camera
  23923. if (this.activeCamera) {
  23924. this.activeCamera.update();
  23925. }
  23926. // rig cameras
  23927. for (var index = 0; index < camera._rigCameras.length; index++) {
  23928. this._renderForCamera(camera._rigCameras[index], camera);
  23929. }
  23930. this.activeCamera = camera;
  23931. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23932. };
  23933. Scene.prototype._checkIntersections = function () {
  23934. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23935. var sourceMesh = this._meshesForIntersections.data[index];
  23936. if (!sourceMesh.actionManager) {
  23937. continue;
  23938. }
  23939. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23940. var action = sourceMesh.actionManager.actions[actionIndex];
  23941. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23942. var parameters = action.getTriggerParameter();
  23943. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23944. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23945. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23946. if (areIntersecting && currentIntersectionInProgress === -1) {
  23947. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23948. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23949. sourceMesh._intersectionsInProgress.push(otherMesh);
  23950. }
  23951. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23952. sourceMesh._intersectionsInProgress.push(otherMesh);
  23953. }
  23954. }
  23955. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23956. //They intersected, and now they don't.
  23957. //is this trigger an exit trigger? execute an event.
  23958. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23959. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23960. }
  23961. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23962. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23963. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23964. }
  23965. }
  23966. }
  23967. }
  23968. }
  23969. };
  23970. Scene.prototype.render = function () {
  23971. if (this.isDisposed) {
  23972. return;
  23973. }
  23974. this._activeParticles.fetchNewFrame();
  23975. this._totalVertices.fetchNewFrame();
  23976. this._activeIndices.fetchNewFrame();
  23977. this._activeBones.fetchNewFrame();
  23978. this._meshesForIntersections.reset();
  23979. this.resetCachedMaterial();
  23980. this.onBeforeAnimationsObservable.notifyObservers(this);
  23981. // Actions
  23982. if (this.actionManager) {
  23983. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23984. }
  23985. //Simplification Queue
  23986. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23987. this.simplificationQueue.executeNext();
  23988. }
  23989. if (this._engine.isDeterministicLockStep()) {
  23990. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23991. var defaultFPS = (60.0 / 1000.0);
  23992. var defaultFrameTime = 1000 / 60; // frame time in MS
  23993. if (this._physicsEngine) {
  23994. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23995. }
  23996. var stepsTaken = 0;
  23997. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23998. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23999. internalSteps = Math.min(internalSteps, maxSubSteps);
  24000. do {
  24001. this.onBeforeStepObservable.notifyObservers(this);
  24002. // Animations
  24003. this._animationRatio = defaultFrameTime * defaultFPS;
  24004. this._animate();
  24005. this.onAfterAnimationsObservable.notifyObservers(this);
  24006. // Physics
  24007. if (this._physicsEngine) {
  24008. this.onBeforePhysicsObservable.notifyObservers(this);
  24009. this._physicsEngine._step(defaultFrameTime / 1000);
  24010. this.onAfterPhysicsObservable.notifyObservers(this);
  24011. }
  24012. this.onAfterStepObservable.notifyObservers(this);
  24013. this._currentStepId++;
  24014. stepsTaken++;
  24015. deltaTime -= defaultFrameTime;
  24016. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24017. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24018. }
  24019. else {
  24020. // Animations
  24021. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24022. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24023. this._animate();
  24024. this.onAfterAnimationsObservable.notifyObservers(this);
  24025. // Physics
  24026. if (this._physicsEngine) {
  24027. this.onBeforePhysicsObservable.notifyObservers(this);
  24028. this._physicsEngine._step(deltaTime / 1000.0);
  24029. this.onAfterPhysicsObservable.notifyObservers(this);
  24030. }
  24031. }
  24032. // update gamepad manager
  24033. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24034. this._gamepadManager._checkGamepadsStatus();
  24035. }
  24036. // Before render
  24037. this.onBeforeRenderObservable.notifyObservers(this);
  24038. // Customs render targets
  24039. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24040. var engine = this.getEngine();
  24041. var currentActiveCamera = this.activeCamera;
  24042. if (this.renderTargetsEnabled) {
  24043. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24044. this._intermediateRendering = true;
  24045. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24046. var renderTarget = this.customRenderTargets[customIndex];
  24047. if (renderTarget._shouldRender()) {
  24048. this._renderId++;
  24049. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24050. if (!this.activeCamera)
  24051. throw new Error("Active camera not set");
  24052. // Viewport
  24053. engine.setViewport(this.activeCamera.viewport);
  24054. // Camera
  24055. this.updateTransformMatrix();
  24056. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24057. }
  24058. }
  24059. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24060. this._intermediateRendering = false;
  24061. this._renderId++;
  24062. }
  24063. // Restore back buffer
  24064. if (this.customRenderTargets.length > 0) {
  24065. engine.restoreDefaultFramebuffer();
  24066. }
  24067. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24068. this.activeCamera = currentActiveCamera;
  24069. // Procedural textures
  24070. if (this.proceduralTexturesEnabled) {
  24071. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24072. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24073. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24074. if (proceduralTexture._shouldRender()) {
  24075. proceduralTexture.render();
  24076. }
  24077. }
  24078. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24079. }
  24080. // Clear
  24081. if (this.autoClearDepthAndStencil || this.autoClear) {
  24082. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24083. }
  24084. // Shadows
  24085. if (this.shadowsEnabled) {
  24086. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24087. var light = this.lights[lightIndex];
  24088. var shadowGenerator = light.getShadowGenerator();
  24089. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24090. var shadowMap = (shadowGenerator.getShadowMap());
  24091. if (this.textures.indexOf(shadowMap) !== -1) {
  24092. this._renderTargets.push(shadowMap);
  24093. }
  24094. }
  24095. }
  24096. }
  24097. // Depth renderer
  24098. if (this._depthRenderer) {
  24099. this._renderTargets.push(this._depthRenderer.getDepthMap());
  24100. }
  24101. // Geometry renderer
  24102. if (this._geometryBufferRenderer) {
  24103. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24104. }
  24105. // RenderPipeline
  24106. if (this._postProcessRenderPipelineManager) {
  24107. this._postProcessRenderPipelineManager.update();
  24108. }
  24109. // Multi-cameras?
  24110. if (this.activeCameras.length > 0) {
  24111. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24112. if (cameraIndex > 0) {
  24113. this._engine.clear(null, false, true, true);
  24114. }
  24115. this._processSubCameras(this.activeCameras[cameraIndex]);
  24116. }
  24117. }
  24118. else {
  24119. if (!this.activeCamera) {
  24120. throw new Error("No camera defined");
  24121. }
  24122. this._processSubCameras(this.activeCamera);
  24123. }
  24124. // Intersection checks
  24125. this._checkIntersections();
  24126. // Update the audio listener attached to the camera
  24127. if (BABYLON.AudioEngine) {
  24128. this._updateAudioParameters();
  24129. }
  24130. // After render
  24131. if (this.afterRender) {
  24132. this.afterRender();
  24133. }
  24134. this.onAfterRenderObservable.notifyObservers(this);
  24135. // Cleaning
  24136. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24137. var data = this._toBeDisposed.data[index];
  24138. if (data) {
  24139. data.dispose();
  24140. }
  24141. this._toBeDisposed[index] = null;
  24142. }
  24143. this._toBeDisposed.reset();
  24144. if (this.dumpNextRenderTargets) {
  24145. this.dumpNextRenderTargets = false;
  24146. }
  24147. this._activeBones.addCount(0, true);
  24148. this._activeIndices.addCount(0, true);
  24149. this._activeParticles.addCount(0, true);
  24150. };
  24151. Scene.prototype._updateAudioParameters = function () {
  24152. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24153. return;
  24154. }
  24155. var listeningCamera;
  24156. var audioEngine = BABYLON.Engine.audioEngine;
  24157. if (this.activeCameras.length > 0) {
  24158. listeningCamera = this.activeCameras[0];
  24159. }
  24160. else {
  24161. listeningCamera = this.activeCamera;
  24162. }
  24163. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24164. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24165. // for VR cameras
  24166. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24167. listeningCamera = listeningCamera.rigCameras[0];
  24168. }
  24169. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24170. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24171. cameraDirection.normalize();
  24172. // To avoid some errors on GearVR
  24173. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24174. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24175. }
  24176. var i;
  24177. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24178. var sound = this.mainSoundTrack.soundCollection[i];
  24179. if (sound.useCustomAttenuation) {
  24180. sound.updateDistanceFromListener();
  24181. }
  24182. }
  24183. for (i = 0; i < this.soundTracks.length; i++) {
  24184. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24185. sound = this.soundTracks[i].soundCollection[j];
  24186. if (sound.useCustomAttenuation) {
  24187. sound.updateDistanceFromListener();
  24188. }
  24189. }
  24190. }
  24191. }
  24192. };
  24193. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24194. // Audio
  24195. get: function () {
  24196. return this._audioEnabled;
  24197. },
  24198. set: function (value) {
  24199. this._audioEnabled = value;
  24200. if (BABYLON.AudioEngine) {
  24201. if (this._audioEnabled) {
  24202. this._enableAudio();
  24203. }
  24204. else {
  24205. this._disableAudio();
  24206. }
  24207. }
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Scene.prototype._disableAudio = function () {
  24213. var i;
  24214. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24215. this.mainSoundTrack.soundCollection[i].pause();
  24216. }
  24217. for (i = 0; i < this.soundTracks.length; i++) {
  24218. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24219. this.soundTracks[i].soundCollection[j].pause();
  24220. }
  24221. }
  24222. };
  24223. Scene.prototype._enableAudio = function () {
  24224. var i;
  24225. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24226. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24227. this.mainSoundTrack.soundCollection[i].play();
  24228. }
  24229. }
  24230. for (i = 0; i < this.soundTracks.length; i++) {
  24231. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24232. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24233. this.soundTracks[i].soundCollection[j].play();
  24234. }
  24235. }
  24236. }
  24237. };
  24238. Object.defineProperty(Scene.prototype, "headphone", {
  24239. get: function () {
  24240. return this._headphone;
  24241. },
  24242. set: function (value) {
  24243. this._headphone = value;
  24244. if (BABYLON.AudioEngine) {
  24245. if (this._headphone) {
  24246. this._switchAudioModeForHeadphones();
  24247. }
  24248. else {
  24249. this._switchAudioModeForNormalSpeakers();
  24250. }
  24251. }
  24252. },
  24253. enumerable: true,
  24254. configurable: true
  24255. });
  24256. Scene.prototype._switchAudioModeForHeadphones = function () {
  24257. this.mainSoundTrack.switchPanningModelToHRTF();
  24258. for (var i = 0; i < this.soundTracks.length; i++) {
  24259. this.soundTracks[i].switchPanningModelToHRTF();
  24260. }
  24261. };
  24262. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24263. this.mainSoundTrack.switchPanningModelToEqualPower();
  24264. for (var i = 0; i < this.soundTracks.length; i++) {
  24265. this.soundTracks[i].switchPanningModelToEqualPower();
  24266. }
  24267. };
  24268. Scene.prototype.enableDepthRenderer = function () {
  24269. if (this._depthRenderer) {
  24270. return this._depthRenderer;
  24271. }
  24272. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24273. return this._depthRenderer;
  24274. };
  24275. Scene.prototype.disableDepthRenderer = function () {
  24276. if (!this._depthRenderer) {
  24277. return;
  24278. }
  24279. this._depthRenderer.dispose();
  24280. this._depthRenderer = null;
  24281. };
  24282. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24283. if (ratio === void 0) { ratio = 1; }
  24284. if (this._geometryBufferRenderer) {
  24285. return this._geometryBufferRenderer;
  24286. }
  24287. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24288. if (!this._geometryBufferRenderer.isSupported) {
  24289. this._geometryBufferRenderer = null;
  24290. }
  24291. return this._geometryBufferRenderer;
  24292. };
  24293. Scene.prototype.disableGeometryBufferRenderer = function () {
  24294. if (!this._geometryBufferRenderer) {
  24295. return;
  24296. }
  24297. this._geometryBufferRenderer.dispose();
  24298. this._geometryBufferRenderer = null;
  24299. };
  24300. Scene.prototype.freezeMaterials = function () {
  24301. for (var i = 0; i < this.materials.length; i++) {
  24302. this.materials[i].freeze();
  24303. }
  24304. };
  24305. Scene.prototype.unfreezeMaterials = function () {
  24306. for (var i = 0; i < this.materials.length; i++) {
  24307. this.materials[i].unfreeze();
  24308. }
  24309. };
  24310. Scene.prototype.dispose = function () {
  24311. this.beforeRender = null;
  24312. this.afterRender = null;
  24313. this.skeletons = [];
  24314. this.morphTargetManagers = [];
  24315. this.importedMeshesFiles = new Array();
  24316. this.stopAllAnimations();
  24317. this.resetCachedMaterial();
  24318. if (this._depthRenderer) {
  24319. this._depthRenderer.dispose();
  24320. }
  24321. if (this._gamepadManager) {
  24322. this._gamepadManager.dispose();
  24323. this._gamepadManager = null;
  24324. }
  24325. // Smart arrays
  24326. if (this.activeCamera) {
  24327. this.activeCamera._activeMeshes.dispose();
  24328. this.activeCamera = null;
  24329. }
  24330. this._activeMeshes.dispose();
  24331. this._renderingManager.dispose();
  24332. this._processedMaterials.dispose();
  24333. this._activeParticleSystems.dispose();
  24334. this._activeSkeletons.dispose();
  24335. this._softwareSkinnedMeshes.dispose();
  24336. this._renderTargets.dispose();
  24337. if (this._boundingBoxRenderer) {
  24338. this._boundingBoxRenderer.dispose();
  24339. }
  24340. this._meshesForIntersections.dispose();
  24341. this._toBeDisposed.dispose();
  24342. // Abort active requests
  24343. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24344. var request = _a[_i];
  24345. request.abort();
  24346. }
  24347. // Debug layer
  24348. if (this._debugLayer) {
  24349. this._debugLayer.hide();
  24350. }
  24351. // Events
  24352. this.onDisposeObservable.notifyObservers(this);
  24353. this.onDisposeObservable.clear();
  24354. this.onBeforeRenderObservable.clear();
  24355. this.onAfterRenderObservable.clear();
  24356. this.OnBeforeRenderTargetsRenderObservable.clear();
  24357. this.OnAfterRenderTargetsRenderObservable.clear();
  24358. this.onAfterStepObservable.clear();
  24359. this.onBeforeStepObservable.clear();
  24360. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24361. this.onAfterActiveMeshesEvaluationObservable.clear();
  24362. this.onBeforeParticlesRenderingObservable.clear();
  24363. this.onAfterParticlesRenderingObservable.clear();
  24364. this.onBeforeSpritesRenderingObservable.clear();
  24365. this.onAfterSpritesRenderingObservable.clear();
  24366. this.onBeforeDrawPhaseObservable.clear();
  24367. this.onAfterDrawPhaseObservable.clear();
  24368. this.onBeforePhysicsObservable.clear();
  24369. this.onAfterPhysicsObservable.clear();
  24370. this.onBeforeAnimationsObservable.clear();
  24371. this.onAfterAnimationsObservable.clear();
  24372. this.onDataLoadedObservable.clear();
  24373. this.detachControl();
  24374. // Release sounds & sounds tracks
  24375. if (BABYLON.AudioEngine) {
  24376. this.disposeSounds();
  24377. }
  24378. // VR Helper
  24379. if (this.VRHelper) {
  24380. this.VRHelper.dispose();
  24381. }
  24382. // Detach cameras
  24383. var canvas = this._engine.getRenderingCanvas();
  24384. if (canvas) {
  24385. var index;
  24386. for (index = 0; index < this.cameras.length; index++) {
  24387. this.cameras[index].detachControl(canvas);
  24388. }
  24389. }
  24390. // Release animation groups
  24391. while (this.animationGroups.length) {
  24392. this.animationGroups[0].dispose();
  24393. }
  24394. // Release lights
  24395. while (this.lights.length) {
  24396. this.lights[0].dispose();
  24397. }
  24398. // Release meshes
  24399. while (this.meshes.length) {
  24400. this.meshes[0].dispose(true);
  24401. }
  24402. while (this.transformNodes.length) {
  24403. this.removeTransformNode(this.transformNodes[0]);
  24404. }
  24405. // Release cameras
  24406. while (this.cameras.length) {
  24407. this.cameras[0].dispose();
  24408. }
  24409. // Release materials
  24410. if (this.defaultMaterial) {
  24411. this.defaultMaterial.dispose();
  24412. }
  24413. while (this.multiMaterials.length) {
  24414. this.multiMaterials[0].dispose();
  24415. }
  24416. while (this.materials.length) {
  24417. this.materials[0].dispose();
  24418. }
  24419. // Release particles
  24420. while (this.particleSystems.length) {
  24421. this.particleSystems[0].dispose();
  24422. }
  24423. // Release sprites
  24424. while (this.spriteManagers.length) {
  24425. this.spriteManagers[0].dispose();
  24426. }
  24427. // Release postProcesses
  24428. while (this.postProcesses.length) {
  24429. this.postProcesses[0].dispose();
  24430. }
  24431. // Release layers
  24432. while (this.layers.length) {
  24433. this.layers[0].dispose();
  24434. }
  24435. while (this.effectLayers.length) {
  24436. this.effectLayers[0].dispose();
  24437. }
  24438. // Release textures
  24439. while (this.textures.length) {
  24440. this.textures[0].dispose();
  24441. }
  24442. // Release UBO
  24443. this._sceneUbo.dispose();
  24444. if (this._alternateSceneUbo) {
  24445. this._alternateSceneUbo.dispose();
  24446. }
  24447. // Post-processes
  24448. this.postProcessManager.dispose();
  24449. if (this._postProcessRenderPipelineManager) {
  24450. this._postProcessRenderPipelineManager.dispose();
  24451. }
  24452. // Physics
  24453. if (this._physicsEngine) {
  24454. this.disablePhysicsEngine();
  24455. }
  24456. // Remove from engine
  24457. index = this._engine.scenes.indexOf(this);
  24458. if (index > -1) {
  24459. this._engine.scenes.splice(index, 1);
  24460. }
  24461. this._engine.wipeCaches(true);
  24462. this._isDisposed = true;
  24463. };
  24464. Object.defineProperty(Scene.prototype, "isDisposed", {
  24465. get: function () {
  24466. return this._isDisposed;
  24467. },
  24468. enumerable: true,
  24469. configurable: true
  24470. });
  24471. // Release sounds & sounds tracks
  24472. Scene.prototype.disposeSounds = function () {
  24473. if (!this._mainSoundTrack) {
  24474. return;
  24475. }
  24476. this.mainSoundTrack.dispose();
  24477. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24478. this.soundTracks[scIndex].dispose();
  24479. }
  24480. };
  24481. // Octrees
  24482. Scene.prototype.getWorldExtends = function () {
  24483. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24484. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24485. for (var index = 0; index < this.meshes.length; index++) {
  24486. var mesh = this.meshes[index];
  24487. mesh.computeWorldMatrix(true);
  24488. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24489. continue;
  24490. }
  24491. var boundingInfo = mesh.getBoundingInfo();
  24492. var minBox = boundingInfo.boundingBox.minimumWorld;
  24493. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24494. BABYLON.Tools.CheckExtends(minBox, min, max);
  24495. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24496. }
  24497. return {
  24498. min: min,
  24499. max: max
  24500. };
  24501. };
  24502. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24503. if (maxCapacity === void 0) { maxCapacity = 64; }
  24504. if (maxDepth === void 0) { maxDepth = 2; }
  24505. if (!this._selectionOctree) {
  24506. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24507. }
  24508. var worldExtends = this.getWorldExtends();
  24509. // Update octree
  24510. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24511. return this._selectionOctree;
  24512. };
  24513. // Picking
  24514. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24515. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24516. var result = BABYLON.Ray.Zero();
  24517. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24518. return result;
  24519. };
  24520. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24521. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24522. var engine = this._engine;
  24523. if (!camera) {
  24524. if (!this.activeCamera)
  24525. throw new Error("Active camera not set");
  24526. camera = this.activeCamera;
  24527. }
  24528. var cameraViewport = camera.viewport;
  24529. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24530. // Moving coordinates to local viewport world
  24531. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24532. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24533. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24534. return this;
  24535. };
  24536. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24537. var result = BABYLON.Ray.Zero();
  24538. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24539. return result;
  24540. };
  24541. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24542. if (!BABYLON.PickingInfo) {
  24543. return this;
  24544. }
  24545. var engine = this._engine;
  24546. if (!camera) {
  24547. if (!this.activeCamera)
  24548. throw new Error("Active camera not set");
  24549. camera = this.activeCamera;
  24550. }
  24551. var cameraViewport = camera.viewport;
  24552. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24553. var identity = BABYLON.Matrix.Identity();
  24554. // Moving coordinates to local viewport world
  24555. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24556. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24557. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24558. return this;
  24559. };
  24560. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24561. if (!BABYLON.PickingInfo) {
  24562. return null;
  24563. }
  24564. var pickingInfo = null;
  24565. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24566. var mesh = this.meshes[meshIndex];
  24567. if (predicate) {
  24568. if (!predicate(mesh)) {
  24569. continue;
  24570. }
  24571. }
  24572. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24573. continue;
  24574. }
  24575. var world = mesh.getWorldMatrix();
  24576. var ray = rayFunction(world);
  24577. var result = mesh.intersects(ray, fastCheck);
  24578. if (!result || !result.hit)
  24579. continue;
  24580. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24581. continue;
  24582. pickingInfo = result;
  24583. if (fastCheck) {
  24584. break;
  24585. }
  24586. }
  24587. return pickingInfo || new BABYLON.PickingInfo();
  24588. };
  24589. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24590. if (!BABYLON.PickingInfo) {
  24591. return null;
  24592. }
  24593. var pickingInfos = new Array();
  24594. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24595. var mesh = this.meshes[meshIndex];
  24596. if (predicate) {
  24597. if (!predicate(mesh)) {
  24598. continue;
  24599. }
  24600. }
  24601. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24602. continue;
  24603. }
  24604. var world = mesh.getWorldMatrix();
  24605. var ray = rayFunction(world);
  24606. var result = mesh.intersects(ray, false);
  24607. if (!result || !result.hit)
  24608. continue;
  24609. pickingInfos.push(result);
  24610. }
  24611. return pickingInfos;
  24612. };
  24613. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24614. if (!BABYLON.PickingInfo) {
  24615. return null;
  24616. }
  24617. var pickingInfo = null;
  24618. if (!camera) {
  24619. if (!this.activeCamera) {
  24620. return null;
  24621. }
  24622. camera = this.activeCamera;
  24623. }
  24624. if (this.spriteManagers.length > 0) {
  24625. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24626. var spriteManager = this.spriteManagers[spriteIndex];
  24627. if (!spriteManager.isPickable) {
  24628. continue;
  24629. }
  24630. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24631. if (!result || !result.hit)
  24632. continue;
  24633. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24634. continue;
  24635. pickingInfo = result;
  24636. if (fastCheck) {
  24637. break;
  24638. }
  24639. }
  24640. }
  24641. return pickingInfo || new BABYLON.PickingInfo();
  24642. };
  24643. /** Launch a ray to try to pick a mesh in the scene
  24644. * @param x position on screen
  24645. * @param y position on screen
  24646. * @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
  24647. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24648. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24649. */
  24650. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24651. var _this = this;
  24652. if (!BABYLON.PickingInfo) {
  24653. return null;
  24654. }
  24655. return this._internalPick(function (world) {
  24656. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24657. return _this._tempPickingRay;
  24658. }, predicate, fastCheck);
  24659. };
  24660. /** Launch a ray to try to pick a sprite in the scene
  24661. * @param x position on screen
  24662. * @param y position on screen
  24663. * @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
  24664. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24665. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24666. */
  24667. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24668. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24669. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24670. };
  24671. /** Use the given ray to pick a mesh in the scene
  24672. * @param ray The ray to use to pick meshes
  24673. * @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
  24674. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24675. */
  24676. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24677. var _this = this;
  24678. return this._internalPick(function (world) {
  24679. if (!_this._pickWithRayInverseMatrix) {
  24680. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24681. }
  24682. world.invertToRef(_this._pickWithRayInverseMatrix);
  24683. if (!_this._cachedRayForTransform) {
  24684. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24685. }
  24686. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24687. return _this._cachedRayForTransform;
  24688. }, predicate, fastCheck);
  24689. };
  24690. /**
  24691. * Launch a ray to try to pick a mesh in the scene
  24692. * @param x X position on screen
  24693. * @param y Y position on screen
  24694. * @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
  24695. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24696. */
  24697. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24698. var _this = this;
  24699. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24700. };
  24701. /**
  24702. * Launch a ray to try to pick a mesh in the scene
  24703. * @param ray Ray to use
  24704. * @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
  24705. */
  24706. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24707. var _this = this;
  24708. return this._internalMultiPick(function (world) {
  24709. if (!_this._pickWithRayInverseMatrix) {
  24710. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24711. }
  24712. world.invertToRef(_this._pickWithRayInverseMatrix);
  24713. if (!_this._cachedRayForTransform) {
  24714. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24715. }
  24716. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24717. return _this._cachedRayForTransform;
  24718. }, predicate);
  24719. };
  24720. Scene.prototype.setPointerOverMesh = function (mesh) {
  24721. if (this._pointerOverMesh === mesh) {
  24722. return;
  24723. }
  24724. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24725. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24726. }
  24727. this._pointerOverMesh = mesh;
  24728. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24729. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24730. }
  24731. };
  24732. Scene.prototype.getPointerOverMesh = function () {
  24733. return this._pointerOverMesh;
  24734. };
  24735. Scene.prototype.setPointerOverSprite = function (sprite) {
  24736. if (this._pointerOverSprite === sprite) {
  24737. return;
  24738. }
  24739. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24740. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24741. }
  24742. this._pointerOverSprite = sprite;
  24743. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24744. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24745. }
  24746. };
  24747. Scene.prototype.getPointerOverSprite = function () {
  24748. return this._pointerOverSprite;
  24749. };
  24750. // Physics
  24751. Scene.prototype.getPhysicsEngine = function () {
  24752. return this._physicsEngine;
  24753. };
  24754. /**
  24755. * Enables physics to the current scene
  24756. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24757. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24758. * @return {boolean} was the physics engine initialized
  24759. */
  24760. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24761. if (gravity === void 0) { gravity = null; }
  24762. if (this._physicsEngine) {
  24763. return true;
  24764. }
  24765. try {
  24766. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24767. return true;
  24768. }
  24769. catch (e) {
  24770. BABYLON.Tools.Error(e.message);
  24771. return false;
  24772. }
  24773. };
  24774. Scene.prototype.disablePhysicsEngine = function () {
  24775. if (!this._physicsEngine) {
  24776. return;
  24777. }
  24778. this._physicsEngine.dispose();
  24779. this._physicsEngine = null;
  24780. };
  24781. Scene.prototype.isPhysicsEnabled = function () {
  24782. return this._physicsEngine !== undefined;
  24783. };
  24784. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24785. var mesh = compound.parts[0].mesh;
  24786. if (mesh.physicsImpostor) {
  24787. mesh.physicsImpostor.dispose();
  24788. mesh.physicsImpostor = null;
  24789. }
  24790. };
  24791. // Misc.
  24792. Scene.prototype._rebuildGeometries = function () {
  24793. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24794. var geometry = _a[_i];
  24795. geometry._rebuild();
  24796. }
  24797. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24798. var mesh = _c[_b];
  24799. mesh._rebuild();
  24800. }
  24801. if (this.postProcessManager) {
  24802. this.postProcessManager._rebuild();
  24803. }
  24804. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24805. var layer = _e[_d];
  24806. layer._rebuild();
  24807. }
  24808. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24809. var effectLayer = _g[_f];
  24810. effectLayer._rebuild();
  24811. }
  24812. if (this._boundingBoxRenderer) {
  24813. this._boundingBoxRenderer._rebuild();
  24814. }
  24815. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24816. var system = _j[_h];
  24817. system.rebuild();
  24818. }
  24819. if (this._postProcessRenderPipelineManager) {
  24820. this._postProcessRenderPipelineManager._rebuild();
  24821. }
  24822. };
  24823. Scene.prototype._rebuildTextures = function () {
  24824. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24825. var texture = _a[_i];
  24826. texture._rebuild();
  24827. }
  24828. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24829. };
  24830. /**
  24831. * Creates a default light for the scene.
  24832. * @param replace Whether to replace the existing lights in the scene.
  24833. */
  24834. Scene.prototype.createDefaultLight = function (replace) {
  24835. if (replace === void 0) { replace = false; }
  24836. // Dispose existing light in replace mode.
  24837. if (replace) {
  24838. if (this.lights) {
  24839. for (var i = 0; i < this.lights.length; i++) {
  24840. this.lights[i].dispose();
  24841. }
  24842. }
  24843. }
  24844. // Light
  24845. if (this.lights.length === 0) {
  24846. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24847. }
  24848. };
  24849. /**
  24850. * Creates a default camera for the scene.
  24851. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24852. * @param replace Whether to replace the existing active camera in the scene.
  24853. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24854. */
  24855. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24856. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24857. if (replace === void 0) { replace = false; }
  24858. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24859. // Dispose existing camera in replace mode.
  24860. if (replace) {
  24861. if (this.activeCamera) {
  24862. this.activeCamera.dispose();
  24863. this.activeCamera = null;
  24864. }
  24865. }
  24866. // Camera
  24867. if (!this.activeCamera) {
  24868. var worldExtends = this.getWorldExtends();
  24869. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24870. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24871. var camera;
  24872. var radius = worldSize.length() * 1.5;
  24873. // empty scene scenario!
  24874. if (!isFinite(radius)) {
  24875. radius = 1;
  24876. worldCenter.copyFromFloats(0, 0, 0);
  24877. }
  24878. if (createArcRotateCamera) {
  24879. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24880. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24881. arcRotateCamera.wheelPrecision = 100 / radius;
  24882. camera = arcRotateCamera;
  24883. }
  24884. else {
  24885. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24886. freeCamera.setTarget(worldCenter);
  24887. camera = freeCamera;
  24888. }
  24889. camera.minZ = radius * 0.01;
  24890. camera.maxZ = radius * 1000;
  24891. camera.speed = radius * 0.2;
  24892. this.activeCamera = camera;
  24893. var canvas = this.getEngine().getRenderingCanvas();
  24894. if (attachCameraControls && canvas) {
  24895. camera.attachControl(canvas);
  24896. }
  24897. }
  24898. };
  24899. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24900. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24901. if (replace === void 0) { replace = false; }
  24902. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24903. this.createDefaultLight(replace);
  24904. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24905. };
  24906. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24907. if (pbr === void 0) { pbr = false; }
  24908. if (scale === void 0) { scale = 1000; }
  24909. if (blur === void 0) { blur = 0; }
  24910. if (environmentTexture) {
  24911. this.environmentTexture = environmentTexture;
  24912. }
  24913. if (!this.environmentTexture) {
  24914. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24915. return null;
  24916. }
  24917. // Skybox
  24918. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24919. if (pbr) {
  24920. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24921. hdrSkyboxMaterial.backFaceCulling = false;
  24922. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24923. if (hdrSkyboxMaterial.reflectionTexture) {
  24924. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24925. }
  24926. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24927. hdrSkyboxMaterial.disableLighting = true;
  24928. hdrSkyboxMaterial.twoSidedLighting = true;
  24929. hdrSkybox.infiniteDistance = true;
  24930. hdrSkybox.material = hdrSkyboxMaterial;
  24931. }
  24932. else {
  24933. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24934. skyboxMaterial.backFaceCulling = false;
  24935. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24936. if (skyboxMaterial.reflectionTexture) {
  24937. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24938. }
  24939. skyboxMaterial.disableLighting = true;
  24940. hdrSkybox.infiniteDistance = true;
  24941. hdrSkybox.material = skyboxMaterial;
  24942. }
  24943. return hdrSkybox;
  24944. };
  24945. Scene.prototype.createDefaultEnvironment = function (options) {
  24946. if (BABYLON.EnvironmentHelper) {
  24947. return new BABYLON.EnvironmentHelper(options, this);
  24948. }
  24949. return null;
  24950. };
  24951. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24952. if (webVROptions === void 0) { webVROptions = {}; }
  24953. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24954. };
  24955. // Tags
  24956. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24957. if (tagsQuery === undefined) {
  24958. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24959. return list;
  24960. }
  24961. var listByTags = [];
  24962. forEach = forEach || (function (item) { return; });
  24963. for (var i in list) {
  24964. var item = list[i];
  24965. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24966. listByTags.push(item);
  24967. forEach(item);
  24968. }
  24969. }
  24970. return listByTags;
  24971. };
  24972. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24973. return this._getByTags(this.meshes, tagsQuery, forEach);
  24974. };
  24975. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24976. return this._getByTags(this.cameras, tagsQuery, forEach);
  24977. };
  24978. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24979. return this._getByTags(this.lights, tagsQuery, forEach);
  24980. };
  24981. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24982. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24983. };
  24984. /**
  24985. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24986. * This allowed control for front to back rendering or reversly depending of the special needs.
  24987. *
  24988. * @param renderingGroupId The rendering group id corresponding to its index
  24989. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24990. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24991. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24992. */
  24993. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24994. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24995. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24996. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24997. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24998. };
  24999. /**
  25000. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25001. *
  25002. * @param renderingGroupId The rendering group id corresponding to its index
  25003. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25004. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25005. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25006. */
  25007. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25008. if (depth === void 0) { depth = true; }
  25009. if (stencil === void 0) { stencil = true; }
  25010. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25011. };
  25012. /**
  25013. * Will flag all materials as dirty to trigger new shader compilation
  25014. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25015. */
  25016. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25017. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25018. var material = _a[_i];
  25019. if (predicate && !predicate(material)) {
  25020. continue;
  25021. }
  25022. material.markAsDirty(flag);
  25023. }
  25024. };
  25025. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25026. var _this = this;
  25027. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25028. this._activeRequests.push(request);
  25029. request.onCompleteObservable.add(function (request) {
  25030. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25031. });
  25032. return request;
  25033. };
  25034. /** @ignore */
  25035. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25036. var _this = this;
  25037. return new Promise(function (resolve, reject) {
  25038. _this._loadFile(url, function (data) {
  25039. resolve(data);
  25040. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25041. reject(exception);
  25042. });
  25043. });
  25044. };
  25045. // Statics
  25046. Scene._FOGMODE_NONE = 0;
  25047. Scene._FOGMODE_EXP = 1;
  25048. Scene._FOGMODE_EXP2 = 2;
  25049. Scene._FOGMODE_LINEAR = 3;
  25050. Scene._uniqueIdCounter = 0;
  25051. Scene.MinDeltaTime = 1.0;
  25052. Scene.MaxDeltaTime = 1000.0;
  25053. /** The distance in pixel that you have to move to prevent some events */
  25054. Scene.DragMovementThreshold = 10; // in pixels
  25055. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25056. Scene.LongPressDelay = 500; // in milliseconds
  25057. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25058. Scene.DoubleClickDelay = 300; // in milliseconds
  25059. /** If you need to check double click without raising a single click at first click, enable this flag */
  25060. Scene.ExclusiveDoubleClickMode = false;
  25061. return Scene;
  25062. }());
  25063. BABYLON.Scene = Scene;
  25064. })(BABYLON || (BABYLON = {}));
  25065. //# sourceMappingURL=babylon.scene.js.map
  25066. var BABYLON;
  25067. (function (BABYLON) {
  25068. /**
  25069. * Set of assets to keep when moving a scene into an asset container.
  25070. */
  25071. var KeepAssets = /** @class */ (function () {
  25072. function KeepAssets() {
  25073. /**
  25074. * Cameras to keep.
  25075. */
  25076. this.cameras = new Array();
  25077. /**
  25078. * Lights to keep.
  25079. */
  25080. this.lights = new Array();
  25081. /**
  25082. * Meshes to keep.
  25083. */
  25084. this.meshes = new Array();
  25085. /**
  25086. * Skeletons to keep.
  25087. */
  25088. this.skeletons = new Array();
  25089. /**
  25090. * ParticleSystems to keep.
  25091. */
  25092. this.particleSystems = new Array();
  25093. /**
  25094. * Animations to keep.
  25095. */
  25096. this.animations = new Array();
  25097. /**
  25098. * MultiMaterials to keep.
  25099. */
  25100. this.multiMaterials = new Array();
  25101. /**
  25102. * Materials to keep.
  25103. */
  25104. this.materials = new Array();
  25105. /**
  25106. * MorphTargetManagers to keep.
  25107. */
  25108. this.morphTargetManagers = new Array();
  25109. /**
  25110. * Geometries to keep.
  25111. */
  25112. this.geometries = new Array();
  25113. /**
  25114. * TransformNodes to keep.
  25115. */
  25116. this.transformNodes = new Array();
  25117. /**
  25118. * LensFlareSystems to keep.
  25119. */
  25120. this.lensFlareSystems = new Array();
  25121. /**
  25122. * ShadowGenerators to keep.
  25123. */
  25124. this.shadowGenerators = new Array();
  25125. /**
  25126. * ActionManagers to keep.
  25127. */
  25128. this.actionManagers = new Array();
  25129. /**
  25130. * Sounds to keep.
  25131. */
  25132. this.sounds = new Array();
  25133. }
  25134. return KeepAssets;
  25135. }());
  25136. BABYLON.KeepAssets = KeepAssets;
  25137. /**
  25138. * Container with a set of assets that can be added or removed from a scene.
  25139. */
  25140. var AssetContainer = /** @class */ (function () {
  25141. /**
  25142. * Instantiates an AssetContainer.
  25143. * @param scene The scene the AssetContainer belongs to.
  25144. */
  25145. function AssetContainer(scene) {
  25146. // Objects
  25147. /**
  25148. * Cameras populated in the container.
  25149. */
  25150. this.cameras = new Array();
  25151. /**
  25152. * Lights populated in the container.
  25153. */
  25154. this.lights = new Array();
  25155. /**
  25156. * Meshes populated in the container.
  25157. */
  25158. this.meshes = new Array();
  25159. /**
  25160. * Skeletons populated in the container.
  25161. */
  25162. this.skeletons = new Array();
  25163. /**
  25164. * ParticleSystems populated in the container.
  25165. */
  25166. this.particleSystems = new Array();
  25167. /**
  25168. * Animations populated in the container.
  25169. */
  25170. this.animations = new Array();
  25171. /**
  25172. * MultiMaterials populated in the container.
  25173. */
  25174. this.multiMaterials = new Array();
  25175. /**
  25176. * Materials populated in the container.
  25177. */
  25178. this.materials = new Array();
  25179. /**
  25180. * MorphTargetManagers populated in the container.
  25181. */
  25182. this.morphTargetManagers = new Array();
  25183. /**
  25184. * Geometries populated in the container.
  25185. */
  25186. this.geometries = new Array();
  25187. /**
  25188. * TransformNodes populated in the container.
  25189. */
  25190. this.transformNodes = new Array();
  25191. /**
  25192. * LensFlareSystems populated in the container.
  25193. */
  25194. this.lensFlareSystems = new Array();
  25195. /**
  25196. * ShadowGenerators populated in the container.
  25197. */
  25198. this.shadowGenerators = new Array();
  25199. /**
  25200. * ActionManagers populated in the container.
  25201. */
  25202. this.actionManagers = new Array();
  25203. /**
  25204. * Sounds populated in the container.
  25205. */
  25206. this.sounds = new Array();
  25207. this.scene = scene;
  25208. }
  25209. /**
  25210. * Adds all the assets from the container to the scene.
  25211. */
  25212. AssetContainer.prototype.addAllToScene = function () {
  25213. var _this = this;
  25214. this.cameras.forEach(function (o) {
  25215. _this.scene.addCamera(o);
  25216. });
  25217. this.lights.forEach(function (o) {
  25218. _this.scene.addLight(o);
  25219. });
  25220. this.meshes.forEach(function (o) {
  25221. _this.scene.addMesh(o);
  25222. });
  25223. this.skeletons.forEach(function (o) {
  25224. _this.scene.addSkeleton(o);
  25225. });
  25226. this.particleSystems.forEach(function (o) {
  25227. _this.scene.addParticleSystem(o);
  25228. });
  25229. this.animations.forEach(function (o) {
  25230. _this.scene.addAnimation(o);
  25231. });
  25232. this.multiMaterials.forEach(function (o) {
  25233. _this.scene.addMultiMaterial(o);
  25234. });
  25235. this.materials.forEach(function (o) {
  25236. _this.scene.addMaterial(o);
  25237. });
  25238. this.morphTargetManagers.forEach(function (o) {
  25239. _this.scene.addMorphTargetManager(o);
  25240. });
  25241. this.geometries.forEach(function (o) {
  25242. _this.scene.addGeometry(o);
  25243. });
  25244. this.transformNodes.forEach(function (o) {
  25245. _this.scene.addTransformNode(o);
  25246. });
  25247. this.lensFlareSystems.forEach(function (o) {
  25248. _this.scene.addLensFlareSystem(o);
  25249. });
  25250. this.actionManagers.forEach(function (o) {
  25251. _this.scene.addActionManager(o);
  25252. });
  25253. this.sounds.forEach(function (o) {
  25254. o.play();
  25255. o.autoplay = true;
  25256. _this.scene.mainSoundTrack.AddSound(o);
  25257. });
  25258. };
  25259. /**
  25260. * Removes all the assets in the container from the scene
  25261. */
  25262. AssetContainer.prototype.removeAllFromScene = function () {
  25263. var _this = this;
  25264. this.cameras.forEach(function (o) {
  25265. _this.scene.removeCamera(o);
  25266. });
  25267. this.lights.forEach(function (o) {
  25268. _this.scene.removeLight(o);
  25269. });
  25270. this.meshes.forEach(function (o) {
  25271. _this.scene.removeMesh(o);
  25272. });
  25273. this.skeletons.forEach(function (o) {
  25274. _this.scene.removeSkeleton(o);
  25275. });
  25276. this.particleSystems.forEach(function (o) {
  25277. _this.scene.removeParticleSystem(o);
  25278. });
  25279. this.animations.forEach(function (o) {
  25280. _this.scene.removeAnimation(o);
  25281. });
  25282. this.multiMaterials.forEach(function (o) {
  25283. _this.scene.removeMultiMaterial(o);
  25284. });
  25285. this.materials.forEach(function (o) {
  25286. _this.scene.removeMaterial(o);
  25287. });
  25288. this.morphTargetManagers.forEach(function (o) {
  25289. _this.scene.removeMorphTargetManager(o);
  25290. });
  25291. this.geometries.forEach(function (o) {
  25292. _this.scene.removeGeometry(o);
  25293. });
  25294. this.transformNodes.forEach(function (o) {
  25295. _this.scene.removeTransformNode(o);
  25296. });
  25297. this.lensFlareSystems.forEach(function (o) {
  25298. _this.scene.removeLensFlareSystem(o);
  25299. });
  25300. this.actionManagers.forEach(function (o) {
  25301. _this.scene.removeActionManager(o);
  25302. });
  25303. this.sounds.forEach(function (o) {
  25304. o.stop();
  25305. o.autoplay = false;
  25306. _this.scene.mainSoundTrack.RemoveSound(o);
  25307. });
  25308. };
  25309. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25310. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25311. var asset = sourceAssets_1[_i];
  25312. var move = true;
  25313. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25314. var keepAsset = keepAssets_1[_a];
  25315. if (asset === keepAsset) {
  25316. move = false;
  25317. break;
  25318. }
  25319. }
  25320. if (move) {
  25321. targetAssets.push(asset);
  25322. }
  25323. }
  25324. };
  25325. /**
  25326. * Removes all the assets contained in the scene and adds them to the container.
  25327. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25328. */
  25329. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25330. if (keepAssets === undefined) {
  25331. keepAssets = new KeepAssets();
  25332. }
  25333. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25334. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25335. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25336. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25337. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25338. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25339. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25340. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25341. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25342. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25343. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25344. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25345. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25346. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25347. this.removeAllFromScene();
  25348. };
  25349. return AssetContainer;
  25350. }());
  25351. BABYLON.AssetContainer = AssetContainer;
  25352. })(BABYLON || (BABYLON = {}));
  25353. //# sourceMappingURL=babylon.assetContainer.js.map
  25354. var BABYLON;
  25355. (function (BABYLON) {
  25356. var Buffer = /** @class */ (function () {
  25357. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25358. if (instanced === void 0) { instanced = false; }
  25359. if (engine instanceof BABYLON.Mesh) {
  25360. this._engine = engine.getScene().getEngine();
  25361. }
  25362. else {
  25363. this._engine = engine;
  25364. }
  25365. this._updatable = updatable;
  25366. this._instanced = instanced;
  25367. this._data = data;
  25368. this._strideSize = stride;
  25369. if (!postponeInternalCreation) {
  25370. this.create();
  25371. }
  25372. }
  25373. /**
  25374. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25375. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25376. * @param offset defines offset in the buffer (0 by default)
  25377. * @param size defines the size in floats of attributes (position is 3 for instance)
  25378. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25379. * @param instanced defines if the vertex buffer contains indexed data
  25380. * @returns the new vertex buffer
  25381. */
  25382. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25383. // a lot of these parameters are ignored as they are overriden by the buffer
  25384. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25385. };
  25386. // Properties
  25387. Buffer.prototype.isUpdatable = function () {
  25388. return this._updatable;
  25389. };
  25390. Buffer.prototype.getData = function () {
  25391. return this._data;
  25392. };
  25393. Buffer.prototype.getBuffer = function () {
  25394. return this._buffer;
  25395. };
  25396. Buffer.prototype.getStrideSize = function () {
  25397. return this._strideSize;
  25398. };
  25399. // public getIsInstanced(): boolean {
  25400. // return this._instanced;
  25401. // }
  25402. // public get instanceDivisor(): number {
  25403. // return this._instanceDivisor;
  25404. // }
  25405. // public set instanceDivisor(value: number) {
  25406. // this._instanceDivisor = value;
  25407. // if (value == 0) {
  25408. // this._instanced = false;
  25409. // } else {
  25410. // this._instanced = true;
  25411. // }
  25412. // }
  25413. // Methods
  25414. Buffer.prototype.create = function (data) {
  25415. if (data === void 0) { data = null; }
  25416. if (!data && this._buffer) {
  25417. return; // nothing to do
  25418. }
  25419. data = data || this._data;
  25420. if (!data) {
  25421. return;
  25422. }
  25423. if (!this._buffer) {
  25424. if (this._updatable) {
  25425. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25426. this._data = data;
  25427. }
  25428. else {
  25429. this._buffer = this._engine.createVertexBuffer(data);
  25430. }
  25431. }
  25432. else if (this._updatable) {
  25433. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25434. this._data = data;
  25435. }
  25436. };
  25437. Buffer.prototype._rebuild = function () {
  25438. this._buffer = null;
  25439. this.create(this._data);
  25440. };
  25441. Buffer.prototype.update = function (data) {
  25442. this.create(data);
  25443. };
  25444. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25445. if (!this._buffer) {
  25446. return;
  25447. }
  25448. if (this._updatable) {
  25449. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25450. this._data = null;
  25451. }
  25452. };
  25453. Buffer.prototype.dispose = function () {
  25454. if (!this._buffer) {
  25455. return;
  25456. }
  25457. if (this._engine._releaseBuffer(this._buffer)) {
  25458. this._buffer = null;
  25459. }
  25460. };
  25461. return Buffer;
  25462. }());
  25463. BABYLON.Buffer = Buffer;
  25464. })(BABYLON || (BABYLON = {}));
  25465. //# sourceMappingURL=babylon.buffer.js.map
  25466. var BABYLON;
  25467. (function (BABYLON) {
  25468. var VertexBuffer = /** @class */ (function () {
  25469. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25470. if (data instanceof BABYLON.Buffer) {
  25471. if (!stride) {
  25472. stride = data.getStrideSize();
  25473. }
  25474. this._buffer = data;
  25475. this._ownsBuffer = false;
  25476. }
  25477. else {
  25478. if (!stride) {
  25479. stride = VertexBuffer.DeduceStride(kind);
  25480. }
  25481. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25482. this._ownsBuffer = true;
  25483. }
  25484. this._stride = stride;
  25485. this._instanced = instanced !== undefined ? instanced : false;
  25486. this._instanceDivisor = instanced ? 1 : 0;
  25487. this._offset = offset ? offset : 0;
  25488. this._size = size ? size : stride;
  25489. this._kind = kind;
  25490. }
  25491. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25492. /**
  25493. * Gets or sets the instance divisor when in instanced mode
  25494. */
  25495. get: function () {
  25496. return this._instanceDivisor;
  25497. },
  25498. set: function (value) {
  25499. this._instanceDivisor = value;
  25500. if (value == 0) {
  25501. this._instanced = false;
  25502. }
  25503. else {
  25504. this._instanced = true;
  25505. }
  25506. },
  25507. enumerable: true,
  25508. configurable: true
  25509. });
  25510. VertexBuffer.prototype._rebuild = function () {
  25511. if (!this._buffer) {
  25512. return;
  25513. }
  25514. this._buffer._rebuild();
  25515. };
  25516. /**
  25517. * Returns the kind of the VertexBuffer (string).
  25518. */
  25519. VertexBuffer.prototype.getKind = function () {
  25520. return this._kind;
  25521. };
  25522. // Properties
  25523. /**
  25524. * Boolean : is the VertexBuffer updatable ?
  25525. */
  25526. VertexBuffer.prototype.isUpdatable = function () {
  25527. return this._buffer.isUpdatable();
  25528. };
  25529. /**
  25530. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25531. */
  25532. VertexBuffer.prototype.getData = function () {
  25533. return this._buffer.getData();
  25534. };
  25535. /**
  25536. * Returns the WebGLBuffer associated to the VertexBuffer.
  25537. */
  25538. VertexBuffer.prototype.getBuffer = function () {
  25539. return this._buffer.getBuffer();
  25540. };
  25541. /**
  25542. * Returns the stride of the VertexBuffer (integer).
  25543. */
  25544. VertexBuffer.prototype.getStrideSize = function () {
  25545. return this._stride;
  25546. };
  25547. /**
  25548. * Returns the offset (integer).
  25549. */
  25550. VertexBuffer.prototype.getOffset = function () {
  25551. return this._offset;
  25552. };
  25553. /**
  25554. * Returns the VertexBuffer total size (integer).
  25555. */
  25556. VertexBuffer.prototype.getSize = function () {
  25557. return this._size;
  25558. };
  25559. /**
  25560. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25561. */
  25562. VertexBuffer.prototype.getIsInstanced = function () {
  25563. return this._instanced;
  25564. };
  25565. /**
  25566. * Returns the instancing divisor, zero for non-instanced (integer).
  25567. */
  25568. VertexBuffer.prototype.getInstanceDivisor = function () {
  25569. return this._instanceDivisor;
  25570. };
  25571. // Methods
  25572. /**
  25573. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25574. * Returns the created WebGLBuffer.
  25575. */
  25576. VertexBuffer.prototype.create = function (data) {
  25577. return this._buffer.create(data);
  25578. };
  25579. /**
  25580. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25581. * This function will create a new buffer if the current one is not updatable
  25582. * Returns the updated WebGLBuffer.
  25583. */
  25584. VertexBuffer.prototype.update = function (data) {
  25585. return this._buffer.update(data);
  25586. };
  25587. /**
  25588. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25589. * Returns the directly updated WebGLBuffer.
  25590. */
  25591. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25592. return this._buffer.updateDirectly(data, offset);
  25593. };
  25594. /**
  25595. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25596. */
  25597. VertexBuffer.prototype.dispose = function () {
  25598. if (this._ownsBuffer) {
  25599. this._buffer.dispose();
  25600. }
  25601. };
  25602. Object.defineProperty(VertexBuffer, "PositionKind", {
  25603. get: function () {
  25604. return VertexBuffer._PositionKind;
  25605. },
  25606. enumerable: true,
  25607. configurable: true
  25608. });
  25609. Object.defineProperty(VertexBuffer, "NormalKind", {
  25610. get: function () {
  25611. return VertexBuffer._NormalKind;
  25612. },
  25613. enumerable: true,
  25614. configurable: true
  25615. });
  25616. Object.defineProperty(VertexBuffer, "TangentKind", {
  25617. get: function () {
  25618. return VertexBuffer._TangentKind;
  25619. },
  25620. enumerable: true,
  25621. configurable: true
  25622. });
  25623. Object.defineProperty(VertexBuffer, "UVKind", {
  25624. get: function () {
  25625. return VertexBuffer._UVKind;
  25626. },
  25627. enumerable: true,
  25628. configurable: true
  25629. });
  25630. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25631. get: function () {
  25632. return VertexBuffer._UV2Kind;
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25638. get: function () {
  25639. return VertexBuffer._UV3Kind;
  25640. },
  25641. enumerable: true,
  25642. configurable: true
  25643. });
  25644. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25645. get: function () {
  25646. return VertexBuffer._UV4Kind;
  25647. },
  25648. enumerable: true,
  25649. configurable: true
  25650. });
  25651. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25652. get: function () {
  25653. return VertexBuffer._UV5Kind;
  25654. },
  25655. enumerable: true,
  25656. configurable: true
  25657. });
  25658. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25659. get: function () {
  25660. return VertexBuffer._UV6Kind;
  25661. },
  25662. enumerable: true,
  25663. configurable: true
  25664. });
  25665. Object.defineProperty(VertexBuffer, "ColorKind", {
  25666. get: function () {
  25667. return VertexBuffer._ColorKind;
  25668. },
  25669. enumerable: true,
  25670. configurable: true
  25671. });
  25672. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25673. get: function () {
  25674. return VertexBuffer._MatricesIndicesKind;
  25675. },
  25676. enumerable: true,
  25677. configurable: true
  25678. });
  25679. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25680. get: function () {
  25681. return VertexBuffer._MatricesWeightsKind;
  25682. },
  25683. enumerable: true,
  25684. configurable: true
  25685. });
  25686. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25687. get: function () {
  25688. return VertexBuffer._MatricesIndicesExtraKind;
  25689. },
  25690. enumerable: true,
  25691. configurable: true
  25692. });
  25693. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25694. get: function () {
  25695. return VertexBuffer._MatricesWeightsExtraKind;
  25696. },
  25697. enumerable: true,
  25698. configurable: true
  25699. });
  25700. /**
  25701. * Deduces the stride given a kind.
  25702. * @param kind The kind string to deduce
  25703. * @returns The deduced stride
  25704. */
  25705. VertexBuffer.DeduceStride = function (kind) {
  25706. switch (kind) {
  25707. case VertexBuffer.PositionKind:
  25708. return 3;
  25709. case VertexBuffer.NormalKind:
  25710. return 3;
  25711. case VertexBuffer.UVKind:
  25712. case VertexBuffer.UV2Kind:
  25713. case VertexBuffer.UV3Kind:
  25714. case VertexBuffer.UV4Kind:
  25715. case VertexBuffer.UV5Kind:
  25716. case VertexBuffer.UV6Kind:
  25717. return 2;
  25718. case VertexBuffer.TangentKind:
  25719. case VertexBuffer.ColorKind:
  25720. return 4;
  25721. case VertexBuffer.MatricesIndicesKind:
  25722. case VertexBuffer.MatricesIndicesExtraKind:
  25723. return 4;
  25724. case VertexBuffer.MatricesWeightsKind:
  25725. case VertexBuffer.MatricesWeightsExtraKind:
  25726. return 4;
  25727. default:
  25728. throw new Error("Invalid kind '" + kind + "'");
  25729. }
  25730. };
  25731. // Enums
  25732. VertexBuffer._PositionKind = "position";
  25733. VertexBuffer._NormalKind = "normal";
  25734. VertexBuffer._TangentKind = "tangent";
  25735. VertexBuffer._UVKind = "uv";
  25736. VertexBuffer._UV2Kind = "uv2";
  25737. VertexBuffer._UV3Kind = "uv3";
  25738. VertexBuffer._UV4Kind = "uv4";
  25739. VertexBuffer._UV5Kind = "uv5";
  25740. VertexBuffer._UV6Kind = "uv6";
  25741. VertexBuffer._ColorKind = "color";
  25742. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25743. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25744. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25745. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25746. return VertexBuffer;
  25747. }());
  25748. BABYLON.VertexBuffer = VertexBuffer;
  25749. })(BABYLON || (BABYLON = {}));
  25750. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25751. var BABYLON;
  25752. (function (BABYLON) {
  25753. /**
  25754. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25755. */
  25756. var DummyInternalTextureTracker = /** @class */ (function () {
  25757. function DummyInternalTextureTracker() {
  25758. /**
  25759. * Gets or set the previous tracker in the list
  25760. */
  25761. this.previous = null;
  25762. /**
  25763. * Gets or set the next tracker in the list
  25764. */
  25765. this.next = null;
  25766. }
  25767. return DummyInternalTextureTracker;
  25768. }());
  25769. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25770. })(BABYLON || (BABYLON = {}));
  25771. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25772. var BABYLON;
  25773. (function (BABYLON) {
  25774. /**
  25775. * Class used to store data associated with WebGL texture data for the engine
  25776. * This class should not be used directly
  25777. */
  25778. var InternalTexture = /** @class */ (function () {
  25779. /**
  25780. * Creates a new InternalTexture
  25781. * @param engine defines the engine to use
  25782. * @param dataSource defines the type of data that will be used
  25783. */
  25784. function InternalTexture(engine, dataSource) {
  25785. /**
  25786. * Observable called when the texture is loaded
  25787. */
  25788. this.onLoadedObservable = new BABYLON.Observable();
  25789. /**
  25790. * Gets or set the previous tracker in the list
  25791. */
  25792. this.previous = null;
  25793. /**
  25794. * Gets or set the next tracker in the list
  25795. */
  25796. this.next = null;
  25797. // Private
  25798. /** @ignore */
  25799. this._initialSlot = -1;
  25800. /** @ignore */
  25801. this._designatedSlot = -1;
  25802. /** @ignore */
  25803. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25804. /** @ignore */
  25805. this._references = 1;
  25806. this._engine = engine;
  25807. this._dataSource = dataSource;
  25808. this._webGLTexture = engine._createTexture();
  25809. }
  25810. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25811. /**
  25812. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25813. */
  25814. get: function () {
  25815. return this._dataSource;
  25816. },
  25817. enumerable: true,
  25818. configurable: true
  25819. });
  25820. /**
  25821. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25822. */
  25823. InternalTexture.prototype.incrementReferences = function () {
  25824. this._references++;
  25825. };
  25826. /**
  25827. * Change the size of the texture (not the size of the content)
  25828. * @param width defines the new width
  25829. * @param height defines the new height
  25830. * @param depth defines the new depth (1 by default)
  25831. */
  25832. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25833. if (depth === void 0) { depth = 1; }
  25834. this.width = width;
  25835. this.height = height;
  25836. this.depth = depth;
  25837. this.baseWidth = width;
  25838. this.baseHeight = height;
  25839. this.baseDepth = depth;
  25840. this._size = width * height * depth;
  25841. };
  25842. /** @ignore */
  25843. InternalTexture.prototype._rebuild = function () {
  25844. var _this = this;
  25845. var proxy;
  25846. this.isReady = false;
  25847. this._cachedCoordinatesMode = null;
  25848. this._cachedWrapU = null;
  25849. this._cachedWrapV = null;
  25850. this._cachedAnisotropicFilteringLevel = null;
  25851. switch (this._dataSource) {
  25852. case InternalTexture.DATASOURCE_TEMP:
  25853. return;
  25854. case InternalTexture.DATASOURCE_URL:
  25855. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25856. _this.isReady = true;
  25857. }, null, this._buffer, undefined, this.format);
  25858. proxy._swapAndDie(this);
  25859. return;
  25860. case InternalTexture.DATASOURCE_RAW:
  25861. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25862. proxy._swapAndDie(this);
  25863. this.isReady = true;
  25864. return;
  25865. case InternalTexture.DATASOURCE_RAW3D:
  25866. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25867. proxy._swapAndDie(this);
  25868. this.isReady = true;
  25869. return;
  25870. case InternalTexture.DATASOURCE_DYNAMIC:
  25871. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25872. proxy._swapAndDie(this);
  25873. // The engine will make sure to update content so no need to flag it as isReady = true
  25874. return;
  25875. case InternalTexture.DATASOURCE_RENDERTARGET:
  25876. var options = new BABYLON.RenderTargetCreationOptions();
  25877. options.generateDepthBuffer = this._generateDepthBuffer;
  25878. options.generateMipMaps = this.generateMipMaps;
  25879. options.generateStencilBuffer = this._generateStencilBuffer;
  25880. options.samplingMode = this.samplingMode;
  25881. options.type = this.type;
  25882. if (this.isCube) {
  25883. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25884. }
  25885. else {
  25886. var size = {
  25887. width: this.width,
  25888. height: this.height
  25889. };
  25890. proxy = this._engine.createRenderTargetTexture(size, options);
  25891. }
  25892. proxy._swapAndDie(this);
  25893. this.isReady = true;
  25894. return;
  25895. case InternalTexture.DATASOURCE_CUBE:
  25896. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25897. _this.isReady = true;
  25898. }, null, this.format, this._extension);
  25899. proxy._swapAndDie(this);
  25900. return;
  25901. case InternalTexture.DATASOURCE_CUBERAW:
  25902. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25903. proxy._swapAndDie(this);
  25904. this.isReady = true;
  25905. return;
  25906. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25907. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25908. if (proxy) {
  25909. proxy._swapAndDie(_this);
  25910. }
  25911. _this.isReady = true;
  25912. }, null, this.format, this._extension);
  25913. return;
  25914. }
  25915. };
  25916. InternalTexture.prototype._swapAndDie = function (target) {
  25917. target._webGLTexture = this._webGLTexture;
  25918. if (this._framebuffer) {
  25919. target._framebuffer = this._framebuffer;
  25920. }
  25921. if (this._depthStencilBuffer) {
  25922. target._depthStencilBuffer = this._depthStencilBuffer;
  25923. }
  25924. if (this._lodTextureHigh) {
  25925. if (target._lodTextureHigh) {
  25926. target._lodTextureHigh.dispose();
  25927. }
  25928. target._lodTextureHigh = this._lodTextureHigh;
  25929. }
  25930. if (this._lodTextureMid) {
  25931. if (target._lodTextureMid) {
  25932. target._lodTextureMid.dispose();
  25933. }
  25934. target._lodTextureMid = this._lodTextureMid;
  25935. }
  25936. if (this._lodTextureLow) {
  25937. if (target._lodTextureLow) {
  25938. target._lodTextureLow.dispose();
  25939. }
  25940. target._lodTextureLow = this._lodTextureLow;
  25941. }
  25942. var cache = this._engine.getLoadedTexturesCache();
  25943. var index = cache.indexOf(this);
  25944. if (index !== -1) {
  25945. cache.splice(index, 1);
  25946. }
  25947. };
  25948. /**
  25949. * Dispose the current allocated resources
  25950. */
  25951. InternalTexture.prototype.dispose = function () {
  25952. if (!this._webGLTexture) {
  25953. return;
  25954. }
  25955. this._references--;
  25956. if (this._references === 0) {
  25957. this._engine._releaseTexture(this);
  25958. this._webGLTexture = null;
  25959. this.previous = null;
  25960. this.next = null;
  25961. }
  25962. };
  25963. /**
  25964. * The source of the texture data is unknown
  25965. */
  25966. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25967. /**
  25968. * Texture data comes from an URL
  25969. */
  25970. InternalTexture.DATASOURCE_URL = 1;
  25971. /**
  25972. * Texture data is only used for temporary storage
  25973. */
  25974. InternalTexture.DATASOURCE_TEMP = 2;
  25975. /**
  25976. * Texture data comes from raw data (ArrayBuffer)
  25977. */
  25978. InternalTexture.DATASOURCE_RAW = 3;
  25979. /**
  25980. * Texture content is dynamic (video or dynamic texture)
  25981. */
  25982. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25983. /**
  25984. * Texture content is generated by rendering to it
  25985. */
  25986. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25987. /**
  25988. * Texture content is part of a multi render target process
  25989. */
  25990. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25991. /**
  25992. * Texture data comes from a cube data file
  25993. */
  25994. InternalTexture.DATASOURCE_CUBE = 7;
  25995. /**
  25996. * Texture data comes from a raw cube data
  25997. */
  25998. InternalTexture.DATASOURCE_CUBERAW = 8;
  25999. /**
  26000. * Texture data come from a prefiltered cube data file
  26001. */
  26002. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26003. /**
  26004. * Texture content is raw 3D data
  26005. */
  26006. InternalTexture.DATASOURCE_RAW3D = 10;
  26007. return InternalTexture;
  26008. }());
  26009. BABYLON.InternalTexture = InternalTexture;
  26010. })(BABYLON || (BABYLON = {}));
  26011. //# sourceMappingURL=babylon.internalTexture.js.map
  26012. var BABYLON;
  26013. (function (BABYLON) {
  26014. var BaseTexture = /** @class */ (function () {
  26015. function BaseTexture(scene) {
  26016. this._hasAlpha = false;
  26017. this.getAlphaFromRGB = false;
  26018. this.level = 1;
  26019. this.coordinatesIndex = 0;
  26020. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26021. /**
  26022. * | Value | Type | Description |
  26023. * | ----- | ------------------ | ----------- |
  26024. * | 0 | CLAMP_ADDRESSMODE | |
  26025. * | 1 | WRAP_ADDRESSMODE | |
  26026. * | 2 | MIRROR_ADDRESSMODE | |
  26027. */
  26028. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26029. /**
  26030. * | Value | Type | Description |
  26031. * | ----- | ------------------ | ----------- |
  26032. * | 0 | CLAMP_ADDRESSMODE | |
  26033. * | 1 | WRAP_ADDRESSMODE | |
  26034. * | 2 | MIRROR_ADDRESSMODE | |
  26035. */
  26036. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26037. /**
  26038. * | Value | Type | Description |
  26039. * | ----- | ------------------ | ----------- |
  26040. * | 0 | CLAMP_ADDRESSMODE | |
  26041. * | 1 | WRAP_ADDRESSMODE | |
  26042. * | 2 | MIRROR_ADDRESSMODE | |
  26043. */
  26044. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26045. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26046. this.isCube = false;
  26047. this.is3D = false;
  26048. this.gammaSpace = true;
  26049. this.invertZ = false;
  26050. this.lodLevelInAlpha = false;
  26051. this.lodGenerationOffset = 0.0;
  26052. this.lodGenerationScale = 0.8;
  26053. this.isRenderTarget = false;
  26054. this.animations = new Array();
  26055. /**
  26056. * An event triggered when the texture is disposed.
  26057. * @type {BABYLON.Observable}
  26058. */
  26059. this.onDisposeObservable = new BABYLON.Observable();
  26060. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26061. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26062. if (this._scene) {
  26063. this._scene.textures.push(this);
  26064. }
  26065. this._uid = null;
  26066. }
  26067. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26068. get: function () {
  26069. return this._hasAlpha;
  26070. },
  26071. set: function (value) {
  26072. if (this._hasAlpha === value) {
  26073. return;
  26074. }
  26075. this._hasAlpha = value;
  26076. if (this._scene) {
  26077. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26078. }
  26079. },
  26080. enumerable: true,
  26081. configurable: true
  26082. });
  26083. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26084. get: function () {
  26085. return this._coordinatesMode;
  26086. },
  26087. /**
  26088. * How a texture is mapped.
  26089. *
  26090. * | Value | Type | Description |
  26091. * | ----- | ----------------------------------- | ----------- |
  26092. * | 0 | EXPLICIT_MODE | |
  26093. * | 1 | SPHERICAL_MODE | |
  26094. * | 2 | PLANAR_MODE | |
  26095. * | 3 | CUBIC_MODE | |
  26096. * | 4 | PROJECTION_MODE | |
  26097. * | 5 | SKYBOX_MODE | |
  26098. * | 6 | INVCUBIC_MODE | |
  26099. * | 7 | EQUIRECTANGULAR_MODE | |
  26100. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26101. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26102. */
  26103. set: function (value) {
  26104. if (this._coordinatesMode === value) {
  26105. return;
  26106. }
  26107. this._coordinatesMode = value;
  26108. if (this._scene) {
  26109. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26110. }
  26111. },
  26112. enumerable: true,
  26113. configurable: true
  26114. });
  26115. Object.defineProperty(BaseTexture.prototype, "uid", {
  26116. get: function () {
  26117. if (!this._uid) {
  26118. this._uid = BABYLON.Tools.RandomId();
  26119. }
  26120. return this._uid;
  26121. },
  26122. enumerable: true,
  26123. configurable: true
  26124. });
  26125. BaseTexture.prototype.toString = function () {
  26126. return this.name;
  26127. };
  26128. BaseTexture.prototype.getClassName = function () {
  26129. return "BaseTexture";
  26130. };
  26131. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26132. set: function (callback) {
  26133. if (this._onDisposeObserver) {
  26134. this.onDisposeObservable.remove(this._onDisposeObserver);
  26135. }
  26136. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26137. },
  26138. enumerable: true,
  26139. configurable: true
  26140. });
  26141. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26142. get: function () {
  26143. return true;
  26144. },
  26145. enumerable: true,
  26146. configurable: true
  26147. });
  26148. BaseTexture.prototype.getScene = function () {
  26149. return this._scene;
  26150. };
  26151. BaseTexture.prototype.getTextureMatrix = function () {
  26152. return BABYLON.Matrix.IdentityReadOnly;
  26153. };
  26154. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26155. return BABYLON.Matrix.IdentityReadOnly;
  26156. };
  26157. BaseTexture.prototype.getInternalTexture = function () {
  26158. return this._texture;
  26159. };
  26160. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26161. return !this.isBlocking || this.isReady();
  26162. };
  26163. BaseTexture.prototype.isReady = function () {
  26164. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26165. this.delayLoad();
  26166. return false;
  26167. }
  26168. if (this._texture) {
  26169. return this._texture.isReady;
  26170. }
  26171. return false;
  26172. };
  26173. BaseTexture.prototype.getSize = function () {
  26174. if (this._texture && this._texture.width) {
  26175. return new BABYLON.Size(this._texture.width, this._texture.height);
  26176. }
  26177. if (this._texture && this._texture._size) {
  26178. return new BABYLON.Size(this._texture._size, this._texture._size);
  26179. }
  26180. return BABYLON.Size.Zero();
  26181. };
  26182. BaseTexture.prototype.getBaseSize = function () {
  26183. if (!this.isReady() || !this._texture)
  26184. return BABYLON.Size.Zero();
  26185. if (this._texture._size) {
  26186. return new BABYLON.Size(this._texture._size, this._texture._size);
  26187. }
  26188. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26189. };
  26190. BaseTexture.prototype.scale = function (ratio) {
  26191. };
  26192. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26193. get: function () {
  26194. return false;
  26195. },
  26196. enumerable: true,
  26197. configurable: true
  26198. });
  26199. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26200. if (!this._scene) {
  26201. return null;
  26202. }
  26203. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26204. for (var index = 0; index < texturesCache.length; index++) {
  26205. var texturesCacheEntry = texturesCache[index];
  26206. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26207. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26208. texturesCacheEntry.incrementReferences();
  26209. return texturesCacheEntry;
  26210. }
  26211. }
  26212. }
  26213. return null;
  26214. };
  26215. BaseTexture.prototype._rebuild = function () {
  26216. };
  26217. BaseTexture.prototype.delayLoad = function () {
  26218. };
  26219. BaseTexture.prototype.clone = function () {
  26220. return null;
  26221. };
  26222. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26223. get: function () {
  26224. if (!this._texture) {
  26225. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26226. }
  26227. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26228. },
  26229. enumerable: true,
  26230. configurable: true
  26231. });
  26232. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26233. get: function () {
  26234. if (!this._texture) {
  26235. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26236. }
  26237. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26238. },
  26239. enumerable: true,
  26240. configurable: true
  26241. });
  26242. BaseTexture.prototype.readPixels = function (faceIndex) {
  26243. if (faceIndex === void 0) { faceIndex = 0; }
  26244. if (!this._texture) {
  26245. return null;
  26246. }
  26247. var size = this.getSize();
  26248. var scene = this.getScene();
  26249. if (!scene) {
  26250. return null;
  26251. }
  26252. var engine = scene.getEngine();
  26253. if (this._texture.isCube) {
  26254. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26255. }
  26256. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26257. };
  26258. BaseTexture.prototype.releaseInternalTexture = function () {
  26259. if (this._texture) {
  26260. this._texture.dispose();
  26261. this._texture = null;
  26262. }
  26263. };
  26264. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26265. get: function () {
  26266. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26267. return null;
  26268. }
  26269. if (!this._texture._sphericalPolynomial) {
  26270. this._texture._sphericalPolynomial =
  26271. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26272. }
  26273. return this._texture._sphericalPolynomial;
  26274. },
  26275. set: function (value) {
  26276. if (this._texture) {
  26277. this._texture._sphericalPolynomial = value;
  26278. }
  26279. },
  26280. enumerable: true,
  26281. configurable: true
  26282. });
  26283. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26284. get: function () {
  26285. if (this._texture) {
  26286. return this._texture._lodTextureHigh;
  26287. }
  26288. return null;
  26289. },
  26290. enumerable: true,
  26291. configurable: true
  26292. });
  26293. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26294. get: function () {
  26295. if (this._texture) {
  26296. return this._texture._lodTextureMid;
  26297. }
  26298. return null;
  26299. },
  26300. enumerable: true,
  26301. configurable: true
  26302. });
  26303. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26304. get: function () {
  26305. if (this._texture) {
  26306. return this._texture._lodTextureLow;
  26307. }
  26308. return null;
  26309. },
  26310. enumerable: true,
  26311. configurable: true
  26312. });
  26313. BaseTexture.prototype.dispose = function () {
  26314. if (!this._scene) {
  26315. return;
  26316. }
  26317. // Animations
  26318. this._scene.stopAnimation(this);
  26319. // Remove from scene
  26320. this._scene._removePendingData(this);
  26321. var index = this._scene.textures.indexOf(this);
  26322. if (index >= 0) {
  26323. this._scene.textures.splice(index, 1);
  26324. }
  26325. if (this._texture === undefined) {
  26326. return;
  26327. }
  26328. // Release
  26329. this.releaseInternalTexture();
  26330. // Callback
  26331. this.onDisposeObservable.notifyObservers(this);
  26332. this.onDisposeObservable.clear();
  26333. };
  26334. BaseTexture.prototype.serialize = function () {
  26335. if (!this.name) {
  26336. return null;
  26337. }
  26338. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26339. // Animations
  26340. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26341. return serializationObject;
  26342. };
  26343. BaseTexture.WhenAllReady = function (textures, callback) {
  26344. var numRemaining = textures.length;
  26345. if (numRemaining === 0) {
  26346. callback();
  26347. return;
  26348. }
  26349. var _loop_1 = function () {
  26350. texture = textures[i];
  26351. if (texture.isReady()) {
  26352. if (--numRemaining === 0) {
  26353. callback();
  26354. }
  26355. }
  26356. else {
  26357. onLoadObservable = texture.onLoadObservable;
  26358. var onLoadCallback_1 = function () {
  26359. onLoadObservable.removeCallback(onLoadCallback_1);
  26360. if (--numRemaining === 0) {
  26361. callback();
  26362. }
  26363. };
  26364. onLoadObservable.add(onLoadCallback_1);
  26365. }
  26366. };
  26367. var texture, onLoadObservable;
  26368. for (var i = 0; i < textures.length; i++) {
  26369. _loop_1();
  26370. }
  26371. };
  26372. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26373. __decorate([
  26374. BABYLON.serialize()
  26375. ], BaseTexture.prototype, "name", void 0);
  26376. __decorate([
  26377. BABYLON.serialize("hasAlpha")
  26378. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26379. __decorate([
  26380. BABYLON.serialize()
  26381. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26382. __decorate([
  26383. BABYLON.serialize()
  26384. ], BaseTexture.prototype, "level", void 0);
  26385. __decorate([
  26386. BABYLON.serialize()
  26387. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26388. __decorate([
  26389. BABYLON.serialize("coordinatesMode")
  26390. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26391. __decorate([
  26392. BABYLON.serialize()
  26393. ], BaseTexture.prototype, "wrapU", void 0);
  26394. __decorate([
  26395. BABYLON.serialize()
  26396. ], BaseTexture.prototype, "wrapV", void 0);
  26397. __decorate([
  26398. BABYLON.serialize()
  26399. ], BaseTexture.prototype, "wrapR", void 0);
  26400. __decorate([
  26401. BABYLON.serialize()
  26402. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26403. __decorate([
  26404. BABYLON.serialize()
  26405. ], BaseTexture.prototype, "isCube", void 0);
  26406. __decorate([
  26407. BABYLON.serialize()
  26408. ], BaseTexture.prototype, "is3D", void 0);
  26409. __decorate([
  26410. BABYLON.serialize()
  26411. ], BaseTexture.prototype, "gammaSpace", void 0);
  26412. __decorate([
  26413. BABYLON.serialize()
  26414. ], BaseTexture.prototype, "invertZ", void 0);
  26415. __decorate([
  26416. BABYLON.serialize()
  26417. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26418. __decorate([
  26419. BABYLON.serialize()
  26420. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26421. __decorate([
  26422. BABYLON.serialize()
  26423. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26424. __decorate([
  26425. BABYLON.serialize()
  26426. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26427. return BaseTexture;
  26428. }());
  26429. BABYLON.BaseTexture = BaseTexture;
  26430. })(BABYLON || (BABYLON = {}));
  26431. //# sourceMappingURL=babylon.baseTexture.js.map
  26432. var BABYLON;
  26433. (function (BABYLON) {
  26434. var Texture = /** @class */ (function (_super) {
  26435. __extends(Texture, _super);
  26436. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26437. if (noMipmap === void 0) { noMipmap = false; }
  26438. if (invertY === void 0) { invertY = true; }
  26439. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26440. if (onLoad === void 0) { onLoad = null; }
  26441. if (onError === void 0) { onError = null; }
  26442. if (buffer === void 0) { buffer = null; }
  26443. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26444. var _this = _super.call(this, scene) || this;
  26445. _this.uOffset = 0;
  26446. _this.vOffset = 0;
  26447. _this.uScale = 1.0;
  26448. _this.vScale = 1.0;
  26449. _this.uAng = 0;
  26450. _this.vAng = 0;
  26451. _this.wAng = 0;
  26452. _this._isBlocking = true;
  26453. _this.name = url || "";
  26454. _this.url = url;
  26455. _this._noMipmap = noMipmap;
  26456. _this._invertY = invertY;
  26457. _this._samplingMode = samplingMode;
  26458. _this._buffer = buffer;
  26459. _this._deleteBuffer = deleteBuffer;
  26460. if (format) {
  26461. _this._format = format;
  26462. }
  26463. scene = _this.getScene();
  26464. if (!scene) {
  26465. return _this;
  26466. }
  26467. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26468. var load = function () {
  26469. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26470. _this.onLoadObservable.notifyObservers(_this);
  26471. }
  26472. if (onLoad) {
  26473. onLoad();
  26474. }
  26475. if (!_this.isBlocking && scene) {
  26476. scene.resetCachedMaterial();
  26477. }
  26478. };
  26479. if (!_this.url) {
  26480. _this._delayedOnLoad = load;
  26481. _this._delayedOnError = onError;
  26482. return _this;
  26483. }
  26484. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26485. if (!_this._texture) {
  26486. if (!scene.useDelayedTextureLoading) {
  26487. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26488. if (deleteBuffer) {
  26489. delete _this._buffer;
  26490. }
  26491. }
  26492. else {
  26493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26494. _this._delayedOnLoad = load;
  26495. _this._delayedOnError = onError;
  26496. }
  26497. }
  26498. else {
  26499. if (_this._texture.isReady) {
  26500. BABYLON.Tools.SetImmediate(function () { return load(); });
  26501. }
  26502. else {
  26503. _this._texture.onLoadedObservable.add(load);
  26504. }
  26505. }
  26506. return _this;
  26507. }
  26508. Object.defineProperty(Texture.prototype, "noMipmap", {
  26509. get: function () {
  26510. return this._noMipmap;
  26511. },
  26512. enumerable: true,
  26513. configurable: true
  26514. });
  26515. Object.defineProperty(Texture.prototype, "isBlocking", {
  26516. get: function () {
  26517. return this._isBlocking;
  26518. },
  26519. set: function (value) {
  26520. this._isBlocking = value;
  26521. },
  26522. enumerable: true,
  26523. configurable: true
  26524. });
  26525. Object.defineProperty(Texture.prototype, "samplingMode", {
  26526. get: function () {
  26527. return this._samplingMode;
  26528. },
  26529. enumerable: true,
  26530. configurable: true
  26531. });
  26532. Texture.prototype.updateURL = function (url) {
  26533. this.url = url;
  26534. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26535. this.delayLoad();
  26536. };
  26537. Texture.prototype.delayLoad = function () {
  26538. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26539. return;
  26540. }
  26541. var scene = this.getScene();
  26542. if (!scene) {
  26543. return;
  26544. }
  26545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26546. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26547. if (!this._texture) {
  26548. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26549. if (this._deleteBuffer) {
  26550. delete this._buffer;
  26551. }
  26552. }
  26553. else {
  26554. if (this._delayedOnLoad) {
  26555. if (this._texture.isReady) {
  26556. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26557. }
  26558. else {
  26559. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26560. }
  26561. }
  26562. }
  26563. this._delayedOnLoad = null;
  26564. this._delayedOnError = null;
  26565. };
  26566. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26567. if (!this._texture) {
  26568. return;
  26569. }
  26570. var scene = this.getScene();
  26571. if (!scene) {
  26572. return;
  26573. }
  26574. this._samplingMode = samplingMode;
  26575. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26576. };
  26577. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26578. x *= this.uScale;
  26579. y *= this.vScale;
  26580. x -= 0.5 * this.uScale;
  26581. y -= 0.5 * this.vScale;
  26582. z -= 0.5;
  26583. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26584. t.x += 0.5 * this.uScale + this.uOffset;
  26585. t.y += 0.5 * this.vScale + this.vOffset;
  26586. t.z += 0.5;
  26587. };
  26588. Texture.prototype.getTextureMatrix = function () {
  26589. var _this = this;
  26590. if (this.uOffset === this._cachedUOffset &&
  26591. this.vOffset === this._cachedVOffset &&
  26592. this.uScale === this._cachedUScale &&
  26593. this.vScale === this._cachedVScale &&
  26594. this.uAng === this._cachedUAng &&
  26595. this.vAng === this._cachedVAng &&
  26596. this.wAng === this._cachedWAng) {
  26597. return this._cachedTextureMatrix;
  26598. }
  26599. this._cachedUOffset = this.uOffset;
  26600. this._cachedVOffset = this.vOffset;
  26601. this._cachedUScale = this.uScale;
  26602. this._cachedVScale = this.vScale;
  26603. this._cachedUAng = this.uAng;
  26604. this._cachedVAng = this.vAng;
  26605. this._cachedWAng = this.wAng;
  26606. if (!this._cachedTextureMatrix) {
  26607. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26608. this._rowGenerationMatrix = new BABYLON.Matrix();
  26609. this._t0 = BABYLON.Vector3.Zero();
  26610. this._t1 = BABYLON.Vector3.Zero();
  26611. this._t2 = BABYLON.Vector3.Zero();
  26612. }
  26613. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26614. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26615. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26616. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26617. this._t1.subtractInPlace(this._t0);
  26618. this._t2.subtractInPlace(this._t0);
  26619. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26620. this._cachedTextureMatrix.m[0] = this._t1.x;
  26621. this._cachedTextureMatrix.m[1] = this._t1.y;
  26622. this._cachedTextureMatrix.m[2] = this._t1.z;
  26623. this._cachedTextureMatrix.m[4] = this._t2.x;
  26624. this._cachedTextureMatrix.m[5] = this._t2.y;
  26625. this._cachedTextureMatrix.m[6] = this._t2.z;
  26626. this._cachedTextureMatrix.m[8] = this._t0.x;
  26627. this._cachedTextureMatrix.m[9] = this._t0.y;
  26628. this._cachedTextureMatrix.m[10] = this._t0.z;
  26629. var scene = this.getScene();
  26630. if (!scene) {
  26631. return this._cachedTextureMatrix;
  26632. }
  26633. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26634. return mat.hasTexture(_this);
  26635. });
  26636. return this._cachedTextureMatrix;
  26637. };
  26638. Texture.prototype.getReflectionTextureMatrix = function () {
  26639. var _this = this;
  26640. var scene = this.getScene();
  26641. if (!scene) {
  26642. return this._cachedTextureMatrix;
  26643. }
  26644. if (this.uOffset === this._cachedUOffset &&
  26645. this.vOffset === this._cachedVOffset &&
  26646. this.uScale === this._cachedUScale &&
  26647. this.vScale === this._cachedVScale &&
  26648. this.coordinatesMode === this._cachedCoordinatesMode) {
  26649. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26650. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26651. return this._cachedTextureMatrix;
  26652. }
  26653. }
  26654. else {
  26655. return this._cachedTextureMatrix;
  26656. }
  26657. }
  26658. if (!this._cachedTextureMatrix) {
  26659. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26660. }
  26661. if (!this._projectionModeMatrix) {
  26662. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26663. }
  26664. this._cachedUOffset = this.uOffset;
  26665. this._cachedVOffset = this.vOffset;
  26666. this._cachedUScale = this.uScale;
  26667. this._cachedVScale = this.vScale;
  26668. this._cachedCoordinatesMode = this.coordinatesMode;
  26669. switch (this.coordinatesMode) {
  26670. case Texture.PLANAR_MODE:
  26671. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26672. this._cachedTextureMatrix[0] = this.uScale;
  26673. this._cachedTextureMatrix[5] = this.vScale;
  26674. this._cachedTextureMatrix[12] = this.uOffset;
  26675. this._cachedTextureMatrix[13] = this.vOffset;
  26676. break;
  26677. case Texture.PROJECTION_MODE:
  26678. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26679. this._projectionModeMatrix.m[0] = 0.5;
  26680. this._projectionModeMatrix.m[5] = -0.5;
  26681. this._projectionModeMatrix.m[10] = 0.0;
  26682. this._projectionModeMatrix.m[12] = 0.5;
  26683. this._projectionModeMatrix.m[13] = 0.5;
  26684. this._projectionModeMatrix.m[14] = 1.0;
  26685. this._projectionModeMatrix.m[15] = 1.0;
  26686. var projectionMatrix = scene.getProjectionMatrix();
  26687. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26688. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26689. break;
  26690. default:
  26691. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26692. break;
  26693. }
  26694. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26695. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26696. });
  26697. return this._cachedTextureMatrix;
  26698. };
  26699. Texture.prototype.clone = function () {
  26700. var _this = this;
  26701. return BABYLON.SerializationHelper.Clone(function () {
  26702. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26703. }, this);
  26704. };
  26705. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26706. get: function () {
  26707. if (!this._onLoadObservable) {
  26708. this._onLoadObservable = new BABYLON.Observable();
  26709. }
  26710. return this._onLoadObservable;
  26711. },
  26712. enumerable: true,
  26713. configurable: true
  26714. });
  26715. Texture.prototype.serialize = function () {
  26716. var serializationObject = _super.prototype.serialize.call(this);
  26717. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26718. serializationObject.base64String = this._buffer;
  26719. serializationObject.name = serializationObject.name.replace("data:", "");
  26720. }
  26721. return serializationObject;
  26722. };
  26723. Texture.prototype.getClassName = function () {
  26724. return "Texture";
  26725. };
  26726. Texture.prototype.dispose = function () {
  26727. _super.prototype.dispose.call(this);
  26728. if (this.onLoadObservable) {
  26729. this.onLoadObservable.clear();
  26730. this._onLoadObservable = null;
  26731. }
  26732. this._delayedOnLoad = null;
  26733. this._delayedOnError = null;
  26734. };
  26735. // Statics
  26736. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26737. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26738. if (onLoad === void 0) { onLoad = null; }
  26739. if (onError === void 0) { onError = null; }
  26740. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26741. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26742. };
  26743. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26744. if (parsedTexture.customType) {
  26745. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26746. // Update Sampling Mode
  26747. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26748. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26749. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26750. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26751. }
  26752. }
  26753. return parsedCustomTexture;
  26754. }
  26755. if (parsedTexture.isCube) {
  26756. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26757. }
  26758. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26759. return null;
  26760. }
  26761. var texture = BABYLON.SerializationHelper.Parse(function () {
  26762. var generateMipMaps = true;
  26763. if (parsedTexture.noMipmap) {
  26764. generateMipMaps = false;
  26765. }
  26766. if (parsedTexture.mirrorPlane) {
  26767. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26768. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26769. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26770. return mirrorTexture;
  26771. }
  26772. else if (parsedTexture.isRenderTarget) {
  26773. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26774. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26775. return renderTargetTexture;
  26776. }
  26777. else {
  26778. var texture;
  26779. if (parsedTexture.base64String) {
  26780. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26781. }
  26782. else {
  26783. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26784. }
  26785. return texture;
  26786. }
  26787. }, parsedTexture, scene);
  26788. // Update Sampling Mode
  26789. if (parsedTexture.samplingMode) {
  26790. var sampling = parsedTexture.samplingMode;
  26791. if (texture._samplingMode !== sampling) {
  26792. texture.updateSamplingMode(sampling);
  26793. }
  26794. }
  26795. // Animations
  26796. if (parsedTexture.animations) {
  26797. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26798. var parsedAnimation = parsedTexture.animations[animationIndex];
  26799. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26800. }
  26801. }
  26802. return texture;
  26803. };
  26804. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26805. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26806. if (noMipmap === void 0) { noMipmap = false; }
  26807. if (invertY === void 0) { invertY = true; }
  26808. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26809. if (onLoad === void 0) { onLoad = null; }
  26810. if (onError === void 0) { onError = null; }
  26811. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26812. if (name.substr(0, 5) !== "data:") {
  26813. name = "data:" + name;
  26814. }
  26815. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26816. };
  26817. // Constants
  26818. Texture.NEAREST_SAMPLINGMODE = 1;
  26819. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26820. Texture.BILINEAR_SAMPLINGMODE = 2;
  26821. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26822. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26823. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26824. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26825. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26826. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26827. Texture.NEAREST_LINEAR = 7;
  26828. Texture.NEAREST_NEAREST = 8;
  26829. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26830. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26831. Texture.LINEAR_LINEAR = 11;
  26832. Texture.LINEAR_NEAREST = 12;
  26833. Texture.EXPLICIT_MODE = 0;
  26834. Texture.SPHERICAL_MODE = 1;
  26835. Texture.PLANAR_MODE = 2;
  26836. Texture.CUBIC_MODE = 3;
  26837. Texture.PROJECTION_MODE = 4;
  26838. Texture.SKYBOX_MODE = 5;
  26839. Texture.INVCUBIC_MODE = 6;
  26840. Texture.EQUIRECTANGULAR_MODE = 7;
  26841. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26842. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26843. Texture.CLAMP_ADDRESSMODE = 0;
  26844. Texture.WRAP_ADDRESSMODE = 1;
  26845. Texture.MIRROR_ADDRESSMODE = 2;
  26846. __decorate([
  26847. BABYLON.serialize()
  26848. ], Texture.prototype, "url", void 0);
  26849. __decorate([
  26850. BABYLON.serialize()
  26851. ], Texture.prototype, "uOffset", void 0);
  26852. __decorate([
  26853. BABYLON.serialize()
  26854. ], Texture.prototype, "vOffset", void 0);
  26855. __decorate([
  26856. BABYLON.serialize()
  26857. ], Texture.prototype, "uScale", void 0);
  26858. __decorate([
  26859. BABYLON.serialize()
  26860. ], Texture.prototype, "vScale", void 0);
  26861. __decorate([
  26862. BABYLON.serialize()
  26863. ], Texture.prototype, "uAng", void 0);
  26864. __decorate([
  26865. BABYLON.serialize()
  26866. ], Texture.prototype, "vAng", void 0);
  26867. __decorate([
  26868. BABYLON.serialize()
  26869. ], Texture.prototype, "wAng", void 0);
  26870. __decorate([
  26871. BABYLON.serialize()
  26872. ], Texture.prototype, "isBlocking", null);
  26873. return Texture;
  26874. }(BABYLON.BaseTexture));
  26875. BABYLON.Texture = Texture;
  26876. })(BABYLON || (BABYLON = {}));
  26877. //# sourceMappingURL=babylon.texture.js.map
  26878. var BABYLON;
  26879. (function (BABYLON) {
  26880. var _InstancesBatch = /** @class */ (function () {
  26881. function _InstancesBatch() {
  26882. this.mustReturn = false;
  26883. this.visibleInstances = new Array();
  26884. this.renderSelf = new Array();
  26885. }
  26886. return _InstancesBatch;
  26887. }());
  26888. BABYLON._InstancesBatch = _InstancesBatch;
  26889. var Mesh = /** @class */ (function (_super) {
  26890. __extends(Mesh, _super);
  26891. /**
  26892. * @constructor
  26893. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26894. * @param {Scene} scene The scene to add this mesh to.
  26895. * @param {Node} parent The parent of this mesh, if it has one
  26896. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26897. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26898. * When false, achieved by calling a clone(), also passing False.
  26899. * This will make creation of children, recursive.
  26900. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26901. */
  26902. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26903. if (scene === void 0) { scene = null; }
  26904. if (parent === void 0) { parent = null; }
  26905. if (source === void 0) { source = null; }
  26906. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26907. var _this = _super.call(this, name, scene) || this;
  26908. // Events
  26909. /**
  26910. * An event triggered before rendering the mesh
  26911. * @type {BABYLON.Observable}
  26912. */
  26913. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26914. /**
  26915. * An event triggered after rendering the mesh
  26916. * @type {BABYLON.Observable}
  26917. */
  26918. _this.onAfterRenderObservable = new BABYLON.Observable();
  26919. /**
  26920. * An event triggered before drawing the mesh
  26921. * @type {BABYLON.Observable}
  26922. */
  26923. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26924. // Members
  26925. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26926. _this.instances = new Array();
  26927. _this._LODLevels = new Array();
  26928. _this._visibleInstances = {};
  26929. _this._renderIdForInstances = new Array();
  26930. _this._batchCache = new _InstancesBatch();
  26931. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26932. // Use by builder only to know what orientation were the mesh build in.
  26933. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26934. _this.overrideMaterialSideOrientation = null;
  26935. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26936. // Will be used to save a source mesh reference, If any
  26937. _this._source = null;
  26938. scene = _this.getScene();
  26939. if (source) {
  26940. // Source mesh
  26941. _this._source = source;
  26942. // Geometry
  26943. if (source._geometry) {
  26944. source._geometry.applyToMesh(_this);
  26945. }
  26946. // Deep copy
  26947. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26948. // Metadata
  26949. if (source.metadata && source.metadata.clone) {
  26950. _this.metadata = source.metadata.clone();
  26951. }
  26952. else {
  26953. _this.metadata = source.metadata;
  26954. }
  26955. // Tags
  26956. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26957. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26958. }
  26959. // Parent
  26960. _this.parent = source.parent;
  26961. // Pivot
  26962. _this.setPivotMatrix(source.getPivotMatrix());
  26963. _this.id = name + "." + source.id;
  26964. // Material
  26965. _this.material = source.material;
  26966. var index;
  26967. if (!doNotCloneChildren) {
  26968. // Children
  26969. var directDescendants = source.getDescendants(true);
  26970. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26971. var child = directDescendants[index_1];
  26972. if (child.clone) {
  26973. child.clone(name + "." + child.name, _this);
  26974. }
  26975. }
  26976. }
  26977. // Physics clone
  26978. var physicsEngine = _this.getScene().getPhysicsEngine();
  26979. if (clonePhysicsImpostor && physicsEngine) {
  26980. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26981. if (impostor) {
  26982. _this.physicsImpostor = impostor.clone(_this);
  26983. }
  26984. }
  26985. // Particles
  26986. for (index = 0; index < scene.particleSystems.length; index++) {
  26987. var system = scene.particleSystems[index];
  26988. if (system.emitter === source) {
  26989. system.clone(system.name, _this);
  26990. }
  26991. }
  26992. _this.computeWorldMatrix(true);
  26993. }
  26994. // Parent
  26995. if (parent !== null) {
  26996. _this.parent = parent;
  26997. }
  26998. return _this;
  26999. }
  27000. Object.defineProperty(Mesh, "FRONTSIDE", {
  27001. /**
  27002. * Mesh side orientation : usually the external or front surface
  27003. */
  27004. get: function () {
  27005. return Mesh._FRONTSIDE;
  27006. },
  27007. enumerable: true,
  27008. configurable: true
  27009. });
  27010. Object.defineProperty(Mesh, "BACKSIDE", {
  27011. /**
  27012. * Mesh side orientation : usually the internal or back surface
  27013. */
  27014. get: function () {
  27015. return Mesh._BACKSIDE;
  27016. },
  27017. enumerable: true,
  27018. configurable: true
  27019. });
  27020. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27021. /**
  27022. * Mesh side orientation : both internal and external or front and back surfaces
  27023. */
  27024. get: function () {
  27025. return Mesh._DOUBLESIDE;
  27026. },
  27027. enumerable: true,
  27028. configurable: true
  27029. });
  27030. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27031. /**
  27032. * Mesh side orientation : by default, `FRONTSIDE`
  27033. */
  27034. get: function () {
  27035. return Mesh._DEFAULTSIDE;
  27036. },
  27037. enumerable: true,
  27038. configurable: true
  27039. });
  27040. Object.defineProperty(Mesh, "NO_CAP", {
  27041. /**
  27042. * Mesh cap setting : no cap
  27043. */
  27044. get: function () {
  27045. return Mesh._NO_CAP;
  27046. },
  27047. enumerable: true,
  27048. configurable: true
  27049. });
  27050. Object.defineProperty(Mesh, "CAP_START", {
  27051. /**
  27052. * Mesh cap setting : one cap at the beginning of the mesh
  27053. */
  27054. get: function () {
  27055. return Mesh._CAP_START;
  27056. },
  27057. enumerable: true,
  27058. configurable: true
  27059. });
  27060. Object.defineProperty(Mesh, "CAP_END", {
  27061. /**
  27062. * Mesh cap setting : one cap at the end of the mesh
  27063. */
  27064. get: function () {
  27065. return Mesh._CAP_END;
  27066. },
  27067. enumerable: true,
  27068. configurable: true
  27069. });
  27070. Object.defineProperty(Mesh, "CAP_ALL", {
  27071. /**
  27072. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27073. */
  27074. get: function () {
  27075. return Mesh._CAP_ALL;
  27076. },
  27077. enumerable: true,
  27078. configurable: true
  27079. });
  27080. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27081. set: function (callback) {
  27082. if (this._onBeforeDrawObserver) {
  27083. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27084. }
  27085. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27086. },
  27087. enumerable: true,
  27088. configurable: true
  27089. });
  27090. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27091. get: function () {
  27092. return this._morphTargetManager;
  27093. },
  27094. set: function (value) {
  27095. if (this._morphTargetManager === value) {
  27096. return;
  27097. }
  27098. this._morphTargetManager = value;
  27099. this._syncGeometryWithMorphTargetManager();
  27100. },
  27101. enumerable: true,
  27102. configurable: true
  27103. });
  27104. Object.defineProperty(Mesh.prototype, "source", {
  27105. get: function () {
  27106. return this._source;
  27107. },
  27108. enumerable: true,
  27109. configurable: true
  27110. });
  27111. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27112. get: function () {
  27113. return this._unIndexed;
  27114. },
  27115. set: function (value) {
  27116. if (this._unIndexed !== value) {
  27117. this._unIndexed = value;
  27118. this._markSubMeshesAsAttributesDirty();
  27119. }
  27120. },
  27121. enumerable: true,
  27122. configurable: true
  27123. });
  27124. // Methods
  27125. /**
  27126. * Returns the string "Mesh".
  27127. */
  27128. Mesh.prototype.getClassName = function () {
  27129. return "Mesh";
  27130. };
  27131. /**
  27132. * Returns a string.
  27133. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27134. */
  27135. Mesh.prototype.toString = function (fullDetails) {
  27136. var ret = _super.prototype.toString.call(this, fullDetails);
  27137. ret += ", n vertices: " + this.getTotalVertices();
  27138. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27139. if (this.animations) {
  27140. for (var i = 0; i < this.animations.length; i++) {
  27141. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27142. }
  27143. }
  27144. if (fullDetails) {
  27145. if (this._geometry) {
  27146. var ib = this.getIndices();
  27147. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27148. if (vb && ib) {
  27149. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27150. }
  27151. }
  27152. else {
  27153. ret += ", flat shading: UNKNOWN";
  27154. }
  27155. }
  27156. return ret;
  27157. };
  27158. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27159. /**
  27160. * True if the mesh has some Levels Of Details (LOD).
  27161. * Returns a boolean.
  27162. */
  27163. get: function () {
  27164. return this._LODLevels.length > 0;
  27165. },
  27166. enumerable: true,
  27167. configurable: true
  27168. });
  27169. /**
  27170. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27171. * @returns an array of {BABYLON.MeshLODLevel}
  27172. */
  27173. Mesh.prototype.getLODLevels = function () {
  27174. return this._LODLevels;
  27175. };
  27176. Mesh.prototype._sortLODLevels = function () {
  27177. this._LODLevels.sort(function (a, b) {
  27178. if (a.distance < b.distance) {
  27179. return 1;
  27180. }
  27181. if (a.distance > b.distance) {
  27182. return -1;
  27183. }
  27184. return 0;
  27185. });
  27186. };
  27187. /**
  27188. * Add a mesh as LOD level triggered at the given distance.
  27189. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27190. * @param {number} distance The distance from the center of the object to show this level
  27191. * @param {Mesh} mesh The mesh to be added as LOD level
  27192. * @return {Mesh} This mesh (for chaining)
  27193. */
  27194. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27195. if (mesh && mesh._masterMesh) {
  27196. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27197. return this;
  27198. }
  27199. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27200. this._LODLevels.push(level);
  27201. if (mesh) {
  27202. mesh._masterMesh = this;
  27203. }
  27204. this._sortLODLevels();
  27205. return this;
  27206. };
  27207. /**
  27208. * Returns the LOD level mesh at the passed distance or null if not found.
  27209. * It is related to the method `addLODLevel(distance, mesh)`.
  27210. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27211. * Returns an object Mesh or `null`.
  27212. */
  27213. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27214. for (var index = 0; index < this._LODLevels.length; index++) {
  27215. var level = this._LODLevels[index];
  27216. if (level.distance === distance) {
  27217. return level.mesh;
  27218. }
  27219. }
  27220. return null;
  27221. };
  27222. /**
  27223. * Remove a mesh from the LOD array
  27224. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27225. * @param {Mesh} mesh The mesh to be removed.
  27226. * @return {Mesh} This mesh (for chaining)
  27227. */
  27228. Mesh.prototype.removeLODLevel = function (mesh) {
  27229. for (var index = 0; index < this._LODLevels.length; index++) {
  27230. if (this._LODLevels[index].mesh === mesh) {
  27231. this._LODLevels.splice(index, 1);
  27232. if (mesh) {
  27233. mesh._masterMesh = null;
  27234. }
  27235. }
  27236. }
  27237. this._sortLODLevels();
  27238. return this;
  27239. };
  27240. /**
  27241. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27242. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27243. */
  27244. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27245. if (!this._LODLevels || this._LODLevels.length === 0) {
  27246. return this;
  27247. }
  27248. var bSphere;
  27249. if (boundingSphere) {
  27250. bSphere = boundingSphere;
  27251. }
  27252. else {
  27253. var boundingInfo = this.getBoundingInfo();
  27254. bSphere = boundingInfo.boundingSphere;
  27255. }
  27256. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27257. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27258. if (this.onLODLevelSelection) {
  27259. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27260. }
  27261. return this;
  27262. }
  27263. for (var index = 0; index < this._LODLevels.length; index++) {
  27264. var level = this._LODLevels[index];
  27265. if (level.distance < distanceToCamera) {
  27266. if (level.mesh) {
  27267. level.mesh._preActivate();
  27268. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27269. }
  27270. if (this.onLODLevelSelection) {
  27271. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27272. }
  27273. return level.mesh;
  27274. }
  27275. }
  27276. if (this.onLODLevelSelection) {
  27277. this.onLODLevelSelection(distanceToCamera, this, this);
  27278. }
  27279. return this;
  27280. };
  27281. Object.defineProperty(Mesh.prototype, "geometry", {
  27282. /**
  27283. * Returns the mesh internal Geometry object.
  27284. */
  27285. get: function () {
  27286. return this._geometry;
  27287. },
  27288. enumerable: true,
  27289. configurable: true
  27290. });
  27291. /**
  27292. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27293. */
  27294. Mesh.prototype.getTotalVertices = function () {
  27295. if (this._geometry === null || this._geometry === undefined) {
  27296. return 0;
  27297. }
  27298. return this._geometry.getTotalVertices();
  27299. };
  27300. /**
  27301. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27302. * 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.
  27303. * You can force the copy with forceCopy === true
  27304. * Returns null if the mesh has no geometry or no vertex buffer.
  27305. * Possible `kind` values :
  27306. * - BABYLON.VertexBuffer.PositionKind
  27307. * - BABYLON.VertexBuffer.UVKind
  27308. * - BABYLON.VertexBuffer.UV2Kind
  27309. * - BABYLON.VertexBuffer.UV3Kind
  27310. * - BABYLON.VertexBuffer.UV4Kind
  27311. * - BABYLON.VertexBuffer.UV5Kind
  27312. * - BABYLON.VertexBuffer.UV6Kind
  27313. * - BABYLON.VertexBuffer.ColorKind
  27314. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27315. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27316. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27317. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27318. */
  27319. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27320. if (!this._geometry) {
  27321. return null;
  27322. }
  27323. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27324. };
  27325. /**
  27326. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27327. * Returns `null` if the mesh has no geometry.
  27328. * Possible `kind` values :
  27329. * - BABYLON.VertexBuffer.PositionKind
  27330. * - BABYLON.VertexBuffer.UVKind
  27331. * - BABYLON.VertexBuffer.UV2Kind
  27332. * - BABYLON.VertexBuffer.UV3Kind
  27333. * - BABYLON.VertexBuffer.UV4Kind
  27334. * - BABYLON.VertexBuffer.UV5Kind
  27335. * - BABYLON.VertexBuffer.UV6Kind
  27336. * - BABYLON.VertexBuffer.ColorKind
  27337. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27338. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27339. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27340. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27341. */
  27342. Mesh.prototype.getVertexBuffer = function (kind) {
  27343. if (!this._geometry) {
  27344. return null;
  27345. }
  27346. return this._geometry.getVertexBuffer(kind);
  27347. };
  27348. /**
  27349. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27350. * Possible `kind` values :
  27351. * - BABYLON.VertexBuffer.PositionKind
  27352. * - BABYLON.VertexBuffer.UVKind
  27353. * - BABYLON.VertexBuffer.UV2Kind
  27354. * - BABYLON.VertexBuffer.UV3Kind
  27355. * - BABYLON.VertexBuffer.UV4Kind
  27356. * - BABYLON.VertexBuffer.UV5Kind
  27357. * - BABYLON.VertexBuffer.UV6Kind
  27358. * - BABYLON.VertexBuffer.ColorKind
  27359. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27360. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27361. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27362. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27363. */
  27364. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27365. if (!this._geometry) {
  27366. if (this._delayInfo) {
  27367. return this._delayInfo.indexOf(kind) !== -1;
  27368. }
  27369. return false;
  27370. }
  27371. return this._geometry.isVerticesDataPresent(kind);
  27372. };
  27373. /**
  27374. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27375. * Possible `kind` values :
  27376. * - BABYLON.VertexBuffer.PositionKind
  27377. * - BABYLON.VertexBuffer.UVKind
  27378. * - BABYLON.VertexBuffer.UV2Kind
  27379. * - BABYLON.VertexBuffer.UV3Kind
  27380. * - BABYLON.VertexBuffer.UV4Kind
  27381. * - BABYLON.VertexBuffer.UV5Kind
  27382. * - BABYLON.VertexBuffer.UV6Kind
  27383. * - BABYLON.VertexBuffer.ColorKind
  27384. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27385. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27386. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27387. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27388. */
  27389. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27390. if (!this._geometry) {
  27391. if (this._delayInfo) {
  27392. return this._delayInfo.indexOf(kind) !== -1;
  27393. }
  27394. return false;
  27395. }
  27396. return this._geometry.isVertexBufferUpdatable(kind);
  27397. };
  27398. /**
  27399. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27400. * Possible `kind` values :
  27401. * - BABYLON.VertexBuffer.PositionKind
  27402. * - BABYLON.VertexBuffer.UVKind
  27403. * - BABYLON.VertexBuffer.UV2Kind
  27404. * - BABYLON.VertexBuffer.UV3Kind
  27405. * - BABYLON.VertexBuffer.UV4Kind
  27406. * - BABYLON.VertexBuffer.UV5Kind
  27407. * - BABYLON.VertexBuffer.UV6Kind
  27408. * - BABYLON.VertexBuffer.ColorKind
  27409. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27410. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27411. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27412. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27413. */
  27414. Mesh.prototype.getVerticesDataKinds = function () {
  27415. if (!this._geometry) {
  27416. var result = new Array();
  27417. if (this._delayInfo) {
  27418. this._delayInfo.forEach(function (kind, index, array) {
  27419. result.push(kind);
  27420. });
  27421. }
  27422. return result;
  27423. }
  27424. return this._geometry.getVerticesDataKinds();
  27425. };
  27426. /**
  27427. * Returns a positive integer : the total number of indices in this mesh geometry.
  27428. * Returns zero if the mesh has no geometry.
  27429. */
  27430. Mesh.prototype.getTotalIndices = function () {
  27431. if (!this._geometry) {
  27432. return 0;
  27433. }
  27434. return this._geometry.getTotalIndices();
  27435. };
  27436. /**
  27437. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27438. * 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.
  27439. * Returns an empty array if the mesh has no geometry.
  27440. */
  27441. Mesh.prototype.getIndices = function (copyWhenShared) {
  27442. if (!this._geometry) {
  27443. return [];
  27444. }
  27445. return this._geometry.getIndices(copyWhenShared);
  27446. };
  27447. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27448. get: function () {
  27449. return this._masterMesh !== null && this._masterMesh !== undefined;
  27450. },
  27451. enumerable: true,
  27452. configurable: true
  27453. });
  27454. /**
  27455. * Determine if the current mesh is ready to be rendered
  27456. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27457. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27458. * @returns true if all associated assets are ready (material, textures, shaders)
  27459. */
  27460. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27461. if (completeCheck === void 0) { completeCheck = false; }
  27462. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27463. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27464. return false;
  27465. }
  27466. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27467. return false;
  27468. }
  27469. if (!this.subMeshes || this.subMeshes.length === 0) {
  27470. return true;
  27471. }
  27472. if (!completeCheck) {
  27473. return true;
  27474. }
  27475. var engine = this.getEngine();
  27476. var scene = this.getScene();
  27477. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27478. this.computeWorldMatrix();
  27479. var mat = this.material || scene.defaultMaterial;
  27480. if (mat) {
  27481. if (mat.storeEffectOnSubMeshes) {
  27482. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27483. var subMesh = _a[_i];
  27484. var effectiveMaterial = subMesh.getMaterial();
  27485. if (effectiveMaterial) {
  27486. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27487. return false;
  27488. }
  27489. }
  27490. }
  27491. }
  27492. else {
  27493. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27494. return false;
  27495. }
  27496. }
  27497. }
  27498. // Shadows
  27499. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27500. var light = _c[_b];
  27501. var generator = light.getShadowGenerator();
  27502. if (generator) {
  27503. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27504. var subMesh = _e[_d];
  27505. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27506. return false;
  27507. }
  27508. }
  27509. }
  27510. }
  27511. // LOD
  27512. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27513. var lod = _g[_f];
  27514. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27515. return false;
  27516. }
  27517. }
  27518. return true;
  27519. };
  27520. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27521. /**
  27522. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27523. * This property is pertinent only for updatable parametric shapes.
  27524. */
  27525. get: function () {
  27526. return this._areNormalsFrozen;
  27527. },
  27528. enumerable: true,
  27529. configurable: true
  27530. });
  27531. /**
  27532. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27533. * It has no effect at all on other shapes.
  27534. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27535. * Returns the Mesh.
  27536. */
  27537. Mesh.prototype.freezeNormals = function () {
  27538. this._areNormalsFrozen = true;
  27539. return this;
  27540. };
  27541. /**
  27542. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27543. * It has no effect at all on other shapes.
  27544. * It reactivates the mesh normals computation if it was previously frozen.
  27545. * Returns the Mesh.
  27546. */
  27547. Mesh.prototype.unfreezeNormals = function () {
  27548. this._areNormalsFrozen = false;
  27549. return this;
  27550. };
  27551. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27552. /**
  27553. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27554. */
  27555. set: function (count) {
  27556. this._overridenInstanceCount = count;
  27557. },
  27558. enumerable: true,
  27559. configurable: true
  27560. });
  27561. // Methods
  27562. Mesh.prototype._preActivate = function () {
  27563. var sceneRenderId = this.getScene().getRenderId();
  27564. if (this._preActivateId === sceneRenderId) {
  27565. return this;
  27566. }
  27567. this._preActivateId = sceneRenderId;
  27568. this._visibleInstances = null;
  27569. return this;
  27570. };
  27571. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27572. if (this._visibleInstances) {
  27573. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27574. }
  27575. return this;
  27576. };
  27577. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27578. if (!this._visibleInstances) {
  27579. this._visibleInstances = {};
  27580. this._visibleInstances.defaultRenderId = renderId;
  27581. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27582. }
  27583. if (!this._visibleInstances[renderId]) {
  27584. this._visibleInstances[renderId] = new Array();
  27585. }
  27586. this._visibleInstances[renderId].push(instance);
  27587. return this;
  27588. };
  27589. /**
  27590. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27591. * This means the mesh underlying bounding box and sphere are recomputed.
  27592. * Returns the Mesh.
  27593. */
  27594. Mesh.prototype.refreshBoundingInfo = function () {
  27595. return this._refreshBoundingInfo(false);
  27596. };
  27597. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27598. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27599. return this;
  27600. }
  27601. var data = this._getPositionData(applySkeleton);
  27602. if (data) {
  27603. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27604. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27605. }
  27606. if (this.subMeshes) {
  27607. for (var index = 0; index < this.subMeshes.length; index++) {
  27608. this.subMeshes[index].refreshBoundingInfo();
  27609. }
  27610. }
  27611. this._updateBoundingInfo();
  27612. return this;
  27613. };
  27614. Mesh.prototype._getPositionData = function (applySkeleton) {
  27615. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27616. if (data && applySkeleton && this.skeleton) {
  27617. data = BABYLON.Tools.Slice(data);
  27618. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27619. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27620. if (matricesWeightsData && matricesIndicesData) {
  27621. var needExtras = this.numBoneInfluencers > 4;
  27622. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27623. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27624. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27625. var tempVector = BABYLON.Tmp.Vector3[0];
  27626. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27627. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27628. var matWeightIdx = 0;
  27629. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27630. finalMatrix.reset();
  27631. var inf;
  27632. var weight;
  27633. for (inf = 0; inf < 4; inf++) {
  27634. weight = matricesWeightsData[matWeightIdx + inf];
  27635. if (weight <= 0)
  27636. break;
  27637. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27638. finalMatrix.addToSelf(tempMatrix);
  27639. }
  27640. if (needExtras) {
  27641. for (inf = 0; inf < 4; inf++) {
  27642. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27643. if (weight <= 0)
  27644. break;
  27645. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  27646. finalMatrix.addToSelf(tempMatrix);
  27647. }
  27648. }
  27649. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27650. tempVector.toArray(data, index);
  27651. }
  27652. }
  27653. }
  27654. return data;
  27655. };
  27656. Mesh.prototype._createGlobalSubMesh = function (force) {
  27657. var totalVertices = this.getTotalVertices();
  27658. if (!totalVertices || !this.getIndices()) {
  27659. return null;
  27660. }
  27661. // Check if we need to recreate the submeshes
  27662. if (this.subMeshes && this.subMeshes.length > 0) {
  27663. var ib = this.getIndices();
  27664. if (!ib) {
  27665. return null;
  27666. }
  27667. var totalIndices = ib.length;
  27668. var needToRecreate = false;
  27669. if (force) {
  27670. needToRecreate = true;
  27671. }
  27672. else {
  27673. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27674. var submesh = _a[_i];
  27675. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27676. needToRecreate = true;
  27677. break;
  27678. }
  27679. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27680. needToRecreate = true;
  27681. break;
  27682. }
  27683. }
  27684. }
  27685. if (!needToRecreate) {
  27686. return this.subMeshes[0];
  27687. }
  27688. }
  27689. this.releaseSubMeshes();
  27690. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27691. };
  27692. Mesh.prototype.subdivide = function (count) {
  27693. if (count < 1) {
  27694. return;
  27695. }
  27696. var totalIndices = this.getTotalIndices();
  27697. var subdivisionSize = (totalIndices / count) | 0;
  27698. var offset = 0;
  27699. // Ensure that subdivisionSize is a multiple of 3
  27700. while (subdivisionSize % 3 !== 0) {
  27701. subdivisionSize++;
  27702. }
  27703. this.releaseSubMeshes();
  27704. for (var index = 0; index < count; index++) {
  27705. if (offset >= totalIndices) {
  27706. break;
  27707. }
  27708. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27709. offset += subdivisionSize;
  27710. }
  27711. this.synchronizeInstances();
  27712. };
  27713. /**
  27714. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27715. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27716. * The `data` are either a numeric array either a Float32Array.
  27717. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27718. * 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).
  27719. * Note that a new underlying VertexBuffer object is created each call.
  27720. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27721. *
  27722. * Possible `kind` values :
  27723. * - BABYLON.VertexBuffer.PositionKind
  27724. * - BABYLON.VertexBuffer.UVKind
  27725. * - BABYLON.VertexBuffer.UV2Kind
  27726. * - BABYLON.VertexBuffer.UV3Kind
  27727. * - BABYLON.VertexBuffer.UV4Kind
  27728. * - BABYLON.VertexBuffer.UV5Kind
  27729. * - BABYLON.VertexBuffer.UV6Kind
  27730. * - BABYLON.VertexBuffer.ColorKind
  27731. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27732. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27733. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27734. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27735. *
  27736. * Returns the Mesh.
  27737. */
  27738. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27739. if (updatable === void 0) { updatable = false; }
  27740. if (!this._geometry) {
  27741. var vertexData = new BABYLON.VertexData();
  27742. vertexData.set(data, kind);
  27743. var scene = this.getScene();
  27744. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27745. }
  27746. else {
  27747. this._geometry.setVerticesData(kind, data, updatable, stride);
  27748. }
  27749. return this;
  27750. };
  27751. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27752. if (updatable === void 0) { updatable = true; }
  27753. var vb = this.getVertexBuffer(kind);
  27754. if (!vb || vb.isUpdatable() === updatable) {
  27755. return;
  27756. }
  27757. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27758. };
  27759. /**
  27760. * Sets the mesh VertexBuffer.
  27761. * Returns the Mesh.
  27762. */
  27763. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27764. if (!this._geometry) {
  27765. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27766. }
  27767. this._geometry.setVerticesBuffer(buffer);
  27768. return this;
  27769. };
  27770. /**
  27771. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27772. * If the mesh has no geometry, it is simply returned as it is.
  27773. * The `data` are either a numeric array either a Float32Array.
  27774. * No new underlying VertexBuffer object is created.
  27775. * 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.
  27776. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27777. *
  27778. * Possible `kind` values :
  27779. * - BABYLON.VertexBuffer.PositionKind
  27780. * - BABYLON.VertexBuffer.UVKind
  27781. * - BABYLON.VertexBuffer.UV2Kind
  27782. * - BABYLON.VertexBuffer.UV3Kind
  27783. * - BABYLON.VertexBuffer.UV4Kind
  27784. * - BABYLON.VertexBuffer.UV5Kind
  27785. * - BABYLON.VertexBuffer.UV6Kind
  27786. * - BABYLON.VertexBuffer.ColorKind
  27787. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27788. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27789. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27790. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27791. *
  27792. * Returns the Mesh.
  27793. */
  27794. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27795. if (!this._geometry) {
  27796. return this;
  27797. }
  27798. if (!makeItUnique) {
  27799. this._geometry.updateVerticesData(kind, data, updateExtends);
  27800. }
  27801. else {
  27802. this.makeGeometryUnique();
  27803. this.updateVerticesData(kind, data, updateExtends, false);
  27804. }
  27805. return this;
  27806. };
  27807. /**
  27808. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27809. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27810. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27811. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27812. * Returns the Mesh.
  27813. */
  27814. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27815. if (computeNormals === void 0) { computeNormals = true; }
  27816. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27817. if (!positions) {
  27818. return this;
  27819. }
  27820. positionFunction(positions);
  27821. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27822. if (computeNormals) {
  27823. var indices = this.getIndices();
  27824. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27825. if (!normals) {
  27826. return this;
  27827. }
  27828. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27829. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27830. }
  27831. return this;
  27832. };
  27833. /**
  27834. * Creates a un-shared specific occurence of the geometry for the mesh.
  27835. * Returns the Mesh.
  27836. */
  27837. Mesh.prototype.makeGeometryUnique = function () {
  27838. if (!this._geometry) {
  27839. return this;
  27840. }
  27841. var oldGeometry = this._geometry;
  27842. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27843. oldGeometry.releaseForMesh(this, true);
  27844. geometry.applyToMesh(this);
  27845. return this;
  27846. };
  27847. /**
  27848. * Sets the mesh indices.
  27849. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27850. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27851. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27852. * This method creates a new index buffer each call.
  27853. * Returns the Mesh.
  27854. */
  27855. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27856. if (totalVertices === void 0) { totalVertices = null; }
  27857. if (updatable === void 0) { updatable = false; }
  27858. if (!this._geometry) {
  27859. var vertexData = new BABYLON.VertexData();
  27860. vertexData.indices = indices;
  27861. var scene = this.getScene();
  27862. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27863. }
  27864. else {
  27865. this._geometry.setIndices(indices, totalVertices, updatable);
  27866. }
  27867. return this;
  27868. };
  27869. /**
  27870. * Update the current index buffer
  27871. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27872. * Returns the Mesh.
  27873. */
  27874. Mesh.prototype.updateIndices = function (indices, offset) {
  27875. if (!this._geometry) {
  27876. return this;
  27877. }
  27878. this._geometry.updateIndices(indices, offset);
  27879. return this;
  27880. };
  27881. /**
  27882. * Invert the geometry to move from a right handed system to a left handed one.
  27883. * Returns the Mesh.
  27884. */
  27885. Mesh.prototype.toLeftHanded = function () {
  27886. if (!this._geometry) {
  27887. return this;
  27888. }
  27889. this._geometry.toLeftHanded();
  27890. return this;
  27891. };
  27892. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27893. if (!this._geometry) {
  27894. return this;
  27895. }
  27896. var engine = this.getScene().getEngine();
  27897. // Wireframe
  27898. var indexToBind;
  27899. if (this._unIndexed) {
  27900. indexToBind = null;
  27901. }
  27902. else {
  27903. switch (fillMode) {
  27904. case BABYLON.Material.PointFillMode:
  27905. indexToBind = null;
  27906. break;
  27907. case BABYLON.Material.WireFrameFillMode:
  27908. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27909. break;
  27910. default:
  27911. case BABYLON.Material.TriangleFillMode:
  27912. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27913. break;
  27914. }
  27915. }
  27916. // VBOs
  27917. this._geometry._bind(effect, indexToBind);
  27918. return this;
  27919. };
  27920. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27921. if (alternate === void 0) { alternate = false; }
  27922. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27923. return this;
  27924. }
  27925. this.onBeforeDrawObservable.notifyObservers(this);
  27926. var scene = this.getScene();
  27927. var engine = scene.getEngine();
  27928. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27929. // or triangles as points
  27930. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27931. }
  27932. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27933. // Triangles as wireframe
  27934. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27935. }
  27936. else {
  27937. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27938. }
  27939. if (scene._isAlternateRenderingEnabled && !alternate) {
  27940. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27941. if (!effect || !scene.activeCamera) {
  27942. return this;
  27943. }
  27944. scene._switchToAlternateCameraConfiguration(true);
  27945. this._effectiveMaterial.bindView(effect);
  27946. this._effectiveMaterial.bindViewProjection(effect);
  27947. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27948. this._draw(subMesh, fillMode, instancesCount, true);
  27949. engine.setViewport(scene.activeCamera.viewport);
  27950. scene._switchToAlternateCameraConfiguration(false);
  27951. this._effectiveMaterial.bindView(effect);
  27952. this._effectiveMaterial.bindViewProjection(effect);
  27953. }
  27954. return this;
  27955. };
  27956. /**
  27957. * Registers for this mesh a javascript function called just before the rendering process.
  27958. * This function is passed the current mesh.
  27959. * Return the Mesh.
  27960. */
  27961. Mesh.prototype.registerBeforeRender = function (func) {
  27962. this.onBeforeRenderObservable.add(func);
  27963. return this;
  27964. };
  27965. /**
  27966. * Disposes a previously registered javascript function called before the rendering.
  27967. * This function is passed the current mesh.
  27968. * Returns the Mesh.
  27969. */
  27970. Mesh.prototype.unregisterBeforeRender = function (func) {
  27971. this.onBeforeRenderObservable.removeCallback(func);
  27972. return this;
  27973. };
  27974. /**
  27975. * Registers for this mesh a javascript function called just after the rendering is complete.
  27976. * This function is passed the current mesh.
  27977. * Returns the Mesh.
  27978. */
  27979. Mesh.prototype.registerAfterRender = function (func) {
  27980. this.onAfterRenderObservable.add(func);
  27981. return this;
  27982. };
  27983. /**
  27984. * Disposes a previously registered javascript function called after the rendering.
  27985. * This function is passed the current mesh.
  27986. * Return the Mesh.
  27987. */
  27988. Mesh.prototype.unregisterAfterRender = function (func) {
  27989. this.onAfterRenderObservable.removeCallback(func);
  27990. return this;
  27991. };
  27992. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27993. var scene = this.getScene();
  27994. this._batchCache.mustReturn = false;
  27995. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27996. this._batchCache.visibleInstances[subMeshId] = null;
  27997. if (this._visibleInstances) {
  27998. var currentRenderId = scene.getRenderId();
  27999. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28000. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28001. var selfRenderId = this._renderId;
  28002. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28003. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28004. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28005. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28006. }
  28007. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28008. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28009. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28010. this._batchCache.mustReturn = true;
  28011. return this._batchCache;
  28012. }
  28013. if (currentRenderId !== selfRenderId) {
  28014. this._batchCache.renderSelf[subMeshId] = false;
  28015. }
  28016. }
  28017. this._renderIdForInstances[subMeshId] = currentRenderId;
  28018. }
  28019. return this._batchCache;
  28020. };
  28021. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28022. var visibleInstances = batch.visibleInstances[subMesh._id];
  28023. if (!visibleInstances) {
  28024. return this;
  28025. }
  28026. var matricesCount = visibleInstances.length + 1;
  28027. var bufferSize = matricesCount * 16 * 4;
  28028. var currentInstancesBufferSize = this._instancesBufferSize;
  28029. var instancesBuffer = this._instancesBuffer;
  28030. while (this._instancesBufferSize < bufferSize) {
  28031. this._instancesBufferSize *= 2;
  28032. }
  28033. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28034. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28035. }
  28036. var offset = 0;
  28037. var instancesCount = 0;
  28038. var world = this.getWorldMatrix();
  28039. if (batch.renderSelf[subMesh._id]) {
  28040. world.copyToArray(this._instancesData, offset);
  28041. offset += 16;
  28042. instancesCount++;
  28043. }
  28044. if (visibleInstances) {
  28045. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28046. var instance = visibleInstances[instanceIndex];
  28047. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28048. offset += 16;
  28049. instancesCount++;
  28050. }
  28051. }
  28052. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28053. if (instancesBuffer) {
  28054. instancesBuffer.dispose();
  28055. }
  28056. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28057. this._instancesBuffer = instancesBuffer;
  28058. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28059. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28060. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28061. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28062. }
  28063. else {
  28064. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28065. }
  28066. this._bind(subMesh, effect, fillMode);
  28067. this._draw(subMesh, fillMode, instancesCount);
  28068. engine.unbindInstanceAttributes();
  28069. return this;
  28070. };
  28071. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28072. var scene = this.getScene();
  28073. var engine = scene.getEngine();
  28074. if (hardwareInstancedRendering) {
  28075. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28076. }
  28077. else {
  28078. if (batch.renderSelf[subMesh._id]) {
  28079. // Draw
  28080. if (onBeforeDraw) {
  28081. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28082. }
  28083. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28084. }
  28085. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28086. if (visibleInstancesForSubMesh) {
  28087. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28088. var instance = visibleInstancesForSubMesh[instanceIndex];
  28089. // World
  28090. var world = instance.getWorldMatrix();
  28091. if (onBeforeDraw) {
  28092. onBeforeDraw(true, world, effectiveMaterial);
  28093. }
  28094. // Draw
  28095. this._draw(subMesh, fillMode);
  28096. }
  28097. }
  28098. }
  28099. return this;
  28100. };
  28101. /**
  28102. * Triggers the draw call for the mesh.
  28103. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28104. * Returns the Mesh.
  28105. */
  28106. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28107. this.checkOcclusionQuery();
  28108. if (this._isOccluded) {
  28109. return this;
  28110. }
  28111. var scene = this.getScene();
  28112. // Managing instances
  28113. var batch = this._getInstancesRenderList(subMesh._id);
  28114. if (batch.mustReturn) {
  28115. return this;
  28116. }
  28117. // Checking geometry state
  28118. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28119. return this;
  28120. }
  28121. this.onBeforeRenderObservable.notifyObservers(this);
  28122. var engine = scene.getEngine();
  28123. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28124. // Material
  28125. var material = subMesh.getMaterial();
  28126. if (!material) {
  28127. return this;
  28128. }
  28129. this._effectiveMaterial = material;
  28130. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28131. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28132. return this;
  28133. }
  28134. }
  28135. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28136. return this;
  28137. }
  28138. // Alpha mode
  28139. if (enableAlphaMode) {
  28140. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28141. }
  28142. // Outline - step 1
  28143. var savedDepthWrite = engine.getDepthWrite();
  28144. if (this.renderOutline) {
  28145. engine.setDepthWrite(false);
  28146. scene.getOutlineRenderer().render(subMesh, batch);
  28147. engine.setDepthWrite(savedDepthWrite);
  28148. }
  28149. var effect;
  28150. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28151. effect = subMesh.effect;
  28152. }
  28153. else {
  28154. effect = this._effectiveMaterial.getEffect();
  28155. }
  28156. if (!effect) {
  28157. return this;
  28158. }
  28159. var sideOrientation = this.overrideMaterialSideOrientation;
  28160. if (sideOrientation == null) {
  28161. sideOrientation = this._effectiveMaterial.sideOrientation;
  28162. if (this._getWorldMatrixDeterminant() < 0) {
  28163. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28164. }
  28165. }
  28166. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28167. if (this._effectiveMaterial.forceDepthWrite) {
  28168. engine.setDepthWrite(true);
  28169. }
  28170. // Bind
  28171. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28172. if (!hardwareInstancedRendering) {
  28173. this._bind(subMesh, effect, fillMode);
  28174. }
  28175. var world = this.getWorldMatrix();
  28176. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28177. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28178. }
  28179. else {
  28180. this._effectiveMaterial.bind(world, this);
  28181. }
  28182. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28183. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28184. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28185. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28186. }
  28187. // Draw
  28188. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28189. // Unbind
  28190. this._effectiveMaterial.unbind();
  28191. // Outline - step 2
  28192. if (this.renderOutline && savedDepthWrite) {
  28193. engine.setDepthWrite(true);
  28194. engine.setColorWrite(false);
  28195. scene.getOutlineRenderer().render(subMesh, batch);
  28196. engine.setColorWrite(true);
  28197. }
  28198. // Overlay
  28199. if (this.renderOverlay) {
  28200. var currentMode = engine.getAlphaMode();
  28201. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28202. scene.getOutlineRenderer().render(subMesh, batch, true);
  28203. engine.setAlphaMode(currentMode);
  28204. }
  28205. this.onAfterRenderObservable.notifyObservers(this);
  28206. return this;
  28207. };
  28208. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28209. if (isInstance && effectiveMaterial) {
  28210. effectiveMaterial.bindOnlyWorldMatrix(world);
  28211. }
  28212. };
  28213. /**
  28214. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28215. */
  28216. Mesh.prototype.getEmittedParticleSystems = function () {
  28217. var results = new Array();
  28218. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28219. var particleSystem = this.getScene().particleSystems[index];
  28220. if (particleSystem.emitter === this) {
  28221. results.push(particleSystem);
  28222. }
  28223. }
  28224. return results;
  28225. };
  28226. /**
  28227. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28228. */
  28229. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28230. var results = new Array();
  28231. var descendants = this.getDescendants();
  28232. descendants.push(this);
  28233. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28234. var particleSystem = this.getScene().particleSystems[index];
  28235. var emitter = particleSystem.emitter;
  28236. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28237. results.push(particleSystem);
  28238. }
  28239. }
  28240. return results;
  28241. };
  28242. Mesh.prototype._checkDelayState = function () {
  28243. var scene = this.getScene();
  28244. if (this._geometry) {
  28245. this._geometry.load(scene);
  28246. }
  28247. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28248. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28249. this._queueLoad(scene);
  28250. }
  28251. return this;
  28252. };
  28253. Mesh.prototype._queueLoad = function (scene) {
  28254. var _this = this;
  28255. scene._addPendingData(this);
  28256. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28257. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28258. if (data instanceof ArrayBuffer) {
  28259. _this._delayLoadingFunction(data, _this);
  28260. }
  28261. else {
  28262. _this._delayLoadingFunction(JSON.parse(data), _this);
  28263. }
  28264. _this.instances.forEach(function (instance) {
  28265. instance._syncSubMeshes();
  28266. });
  28267. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28268. scene._removePendingData(_this);
  28269. }, function () { }, scene.database, getBinaryData);
  28270. return this;
  28271. };
  28272. /**
  28273. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28274. */
  28275. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28276. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28277. return false;
  28278. }
  28279. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28280. return false;
  28281. }
  28282. this._checkDelayState();
  28283. return true;
  28284. };
  28285. /**
  28286. * Sets the mesh material by the material or multiMaterial `id` property.
  28287. * The material `id` is a string identifying the material or the multiMaterial.
  28288. * This method returns the Mesh.
  28289. */
  28290. Mesh.prototype.setMaterialByID = function (id) {
  28291. var materials = this.getScene().materials;
  28292. var index;
  28293. for (index = materials.length - 1; index > -1; index--) {
  28294. if (materials[index].id === id) {
  28295. this.material = materials[index];
  28296. return this;
  28297. }
  28298. }
  28299. // Multi
  28300. var multiMaterials = this.getScene().multiMaterials;
  28301. for (index = multiMaterials.length - 1; index > -1; index--) {
  28302. if (multiMaterials[index].id === id) {
  28303. this.material = multiMaterials[index];
  28304. return this;
  28305. }
  28306. }
  28307. return this;
  28308. };
  28309. /**
  28310. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28311. */
  28312. Mesh.prototype.getAnimatables = function () {
  28313. var results = new Array();
  28314. if (this.material) {
  28315. results.push(this.material);
  28316. }
  28317. if (this.skeleton) {
  28318. results.push(this.skeleton);
  28319. }
  28320. return results;
  28321. };
  28322. /**
  28323. * Modifies the mesh geometry according to the passed transformation matrix.
  28324. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28325. * The mesh normals are modified accordingly the same transformation.
  28326. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28327. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28328. * Returns the Mesh.
  28329. */
  28330. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28331. // Position
  28332. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28333. return this;
  28334. }
  28335. var submeshes = this.subMeshes.splice(0);
  28336. this._resetPointsArrayCache();
  28337. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28338. var temp = new Array();
  28339. var index;
  28340. for (index = 0; index < data.length; index += 3) {
  28341. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28342. }
  28343. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28344. // Normals
  28345. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28346. return this;
  28347. }
  28348. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28349. temp = [];
  28350. for (index = 0; index < data.length; index += 3) {
  28351. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28352. }
  28353. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28354. // flip faces?
  28355. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28356. this.flipFaces();
  28357. }
  28358. // Restore submeshes
  28359. this.releaseSubMeshes();
  28360. this.subMeshes = submeshes;
  28361. return this;
  28362. };
  28363. /**
  28364. * Modifies the mesh geometry according to its own current World Matrix.
  28365. * The mesh World Matrix is then reset.
  28366. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28367. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28368. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28369. * Returns the Mesh.
  28370. */
  28371. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28372. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28373. this.scaling.copyFromFloats(1, 1, 1);
  28374. this.position.copyFromFloats(0, 0, 0);
  28375. this.rotation.copyFromFloats(0, 0, 0);
  28376. //only if quaternion is already set
  28377. if (this.rotationQuaternion) {
  28378. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28379. }
  28380. this._worldMatrix = BABYLON.Matrix.Identity();
  28381. return this;
  28382. };
  28383. Object.defineProperty(Mesh.prototype, "_positions", {
  28384. // Cache
  28385. get: function () {
  28386. if (this._geometry) {
  28387. return this._geometry._positions;
  28388. }
  28389. return null;
  28390. },
  28391. enumerable: true,
  28392. configurable: true
  28393. });
  28394. Mesh.prototype._resetPointsArrayCache = function () {
  28395. if (this._geometry) {
  28396. this._geometry._resetPointsArrayCache();
  28397. }
  28398. return this;
  28399. };
  28400. Mesh.prototype._generatePointsArray = function () {
  28401. if (this._geometry) {
  28402. return this._geometry._generatePointsArray();
  28403. }
  28404. return false;
  28405. };
  28406. /**
  28407. * Returns a new Mesh object generated from the current mesh properties.
  28408. * This method must not get confused with createInstance().
  28409. * The parameter `name` is a string, the name given to the new mesh.
  28410. * The optional parameter `newParent` can be any Node object (default `null`).
  28411. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28412. * 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.
  28413. */
  28414. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28415. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28416. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28417. };
  28418. /**
  28419. * Disposes the Mesh.
  28420. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28421. * Returns nothing.
  28422. */
  28423. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28424. var _this = this;
  28425. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28426. this.morphTargetManager = null;
  28427. if (this._geometry) {
  28428. this._geometry.releaseForMesh(this, true);
  28429. }
  28430. // Sources
  28431. var meshes = this.getScene().meshes;
  28432. meshes.forEach(function (abstractMesh) {
  28433. var mesh = abstractMesh;
  28434. if (mesh._source && mesh._source === _this) {
  28435. mesh._source = null;
  28436. }
  28437. });
  28438. this._source = null;
  28439. // Instances
  28440. if (this._instancesBuffer) {
  28441. this._instancesBuffer.dispose();
  28442. this._instancesBuffer = null;
  28443. }
  28444. while (this.instances.length) {
  28445. this.instances[0].dispose();
  28446. }
  28447. // Effect layers.
  28448. var effectLayers = this.getScene().effectLayers;
  28449. for (var i = 0; i < effectLayers.length; i++) {
  28450. var effectLayer = effectLayers[i];
  28451. if (effectLayer) {
  28452. effectLayer._disposeMesh(this);
  28453. }
  28454. }
  28455. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28456. };
  28457. /**
  28458. * Modifies the mesh geometry according to a displacement map.
  28459. * 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.
  28460. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28461. * This method returns nothing.
  28462. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28463. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28464. * 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.
  28465. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28466. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28467. *
  28468. * Returns the Mesh.
  28469. */
  28470. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28471. var _this = this;
  28472. var scene = this.getScene();
  28473. var onload = function (img) {
  28474. // Getting height map data
  28475. var canvas = document.createElement("canvas");
  28476. var context = canvas.getContext("2d");
  28477. var heightMapWidth = img.width;
  28478. var heightMapHeight = img.height;
  28479. canvas.width = heightMapWidth;
  28480. canvas.height = heightMapHeight;
  28481. context.drawImage(img, 0, 0);
  28482. // Create VertexData from map data
  28483. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28484. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28485. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28486. //execute success callback, if set
  28487. if (onSuccess) {
  28488. onSuccess(_this);
  28489. }
  28490. };
  28491. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28492. return this;
  28493. };
  28494. /**
  28495. * Modifies the mesh geometry according to a displacementMap buffer.
  28496. * 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.
  28497. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28498. * This method returns nothing.
  28499. * 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.
  28500. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28501. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28502. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28503. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28504. *
  28505. * Returns the Mesh.
  28506. */
  28507. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28508. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28509. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28510. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28511. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28512. return this;
  28513. }
  28514. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28515. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28516. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28517. var position = BABYLON.Vector3.Zero();
  28518. var normal = BABYLON.Vector3.Zero();
  28519. var uv = BABYLON.Vector2.Zero();
  28520. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28521. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28522. for (var index = 0; index < positions.length; index += 3) {
  28523. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28524. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28525. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28526. // Compute height
  28527. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28528. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28529. var pos = (u + v * heightMapWidth) * 4;
  28530. var r = buffer[pos] / 255.0;
  28531. var g = buffer[pos + 1] / 255.0;
  28532. var b = buffer[pos + 2] / 255.0;
  28533. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28534. normal.normalize();
  28535. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28536. position = position.add(normal);
  28537. position.toArray(positions, index);
  28538. }
  28539. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28540. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28541. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28542. return this;
  28543. };
  28544. /**
  28545. * Modify the mesh to get a flat shading rendering.
  28546. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28547. * This method returns the Mesh.
  28548. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28549. */
  28550. Mesh.prototype.convertToFlatShadedMesh = function () {
  28551. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28552. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28553. var kinds = this.getVerticesDataKinds();
  28554. var vbs = {};
  28555. var data = {};
  28556. var newdata = {};
  28557. var updatableNormals = false;
  28558. var kindIndex;
  28559. var kind;
  28560. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28561. kind = kinds[kindIndex];
  28562. var vertexBuffer = this.getVertexBuffer(kind);
  28563. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28564. updatableNormals = vertexBuffer.isUpdatable();
  28565. kinds.splice(kindIndex, 1);
  28566. kindIndex--;
  28567. continue;
  28568. }
  28569. vbs[kind] = vertexBuffer;
  28570. data[kind] = vbs[kind].getData();
  28571. newdata[kind] = [];
  28572. }
  28573. // Save previous submeshes
  28574. var previousSubmeshes = this.subMeshes.slice(0);
  28575. var indices = this.getIndices();
  28576. var totalIndices = this.getTotalIndices();
  28577. // Generating unique vertices per face
  28578. var index;
  28579. for (index = 0; index < totalIndices; index++) {
  28580. var vertexIndex = indices[index];
  28581. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28582. kind = kinds[kindIndex];
  28583. var stride = vbs[kind].getStrideSize();
  28584. for (var offset = 0; offset < stride; offset++) {
  28585. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28586. }
  28587. }
  28588. }
  28589. // Updating faces & normal
  28590. var normals = [];
  28591. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28592. for (index = 0; index < totalIndices; index += 3) {
  28593. indices[index] = index;
  28594. indices[index + 1] = index + 1;
  28595. indices[index + 2] = index + 2;
  28596. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28597. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28598. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28599. var p1p2 = p1.subtract(p2);
  28600. var p3p2 = p3.subtract(p2);
  28601. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28602. // Store same normals for every vertex
  28603. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28604. normals.push(normal.x);
  28605. normals.push(normal.y);
  28606. normals.push(normal.z);
  28607. }
  28608. }
  28609. this.setIndices(indices);
  28610. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28611. // Updating vertex buffers
  28612. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28613. kind = kinds[kindIndex];
  28614. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28615. }
  28616. // Updating submeshes
  28617. this.releaseSubMeshes();
  28618. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28619. var previousOne = previousSubmeshes[submeshIndex];
  28620. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28621. }
  28622. this.synchronizeInstances();
  28623. return this;
  28624. };
  28625. /**
  28626. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28627. * In other words, more vertices, no more indices and a single bigger VBO.
  28628. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28629. * Returns the Mesh.
  28630. */
  28631. Mesh.prototype.convertToUnIndexedMesh = function () {
  28632. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28633. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28634. var kinds = this.getVerticesDataKinds();
  28635. var vbs = {};
  28636. var data = {};
  28637. var newdata = {};
  28638. var kindIndex;
  28639. var kind;
  28640. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28641. kind = kinds[kindIndex];
  28642. var vertexBuffer = this.getVertexBuffer(kind);
  28643. vbs[kind] = vertexBuffer;
  28644. data[kind] = vbs[kind].getData();
  28645. newdata[kind] = [];
  28646. }
  28647. // Save previous submeshes
  28648. var previousSubmeshes = this.subMeshes.slice(0);
  28649. var indices = this.getIndices();
  28650. var totalIndices = this.getTotalIndices();
  28651. // Generating unique vertices per face
  28652. var index;
  28653. for (index = 0; index < totalIndices; index++) {
  28654. var vertexIndex = indices[index];
  28655. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28656. kind = kinds[kindIndex];
  28657. var stride = vbs[kind].getStrideSize();
  28658. for (var offset = 0; offset < stride; offset++) {
  28659. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28660. }
  28661. }
  28662. }
  28663. // Updating indices
  28664. for (index = 0; index < totalIndices; index += 3) {
  28665. indices[index] = index;
  28666. indices[index + 1] = index + 1;
  28667. indices[index + 2] = index + 2;
  28668. }
  28669. this.setIndices(indices);
  28670. // Updating vertex buffers
  28671. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28672. kind = kinds[kindIndex];
  28673. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28674. }
  28675. // Updating submeshes
  28676. this.releaseSubMeshes();
  28677. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28678. var previousOne = previousSubmeshes[submeshIndex];
  28679. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28680. }
  28681. this._unIndexed = true;
  28682. this.synchronizeInstances();
  28683. return this;
  28684. };
  28685. /**
  28686. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28687. * This method returns the Mesh.
  28688. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28689. */
  28690. Mesh.prototype.flipFaces = function (flipNormals) {
  28691. if (flipNormals === void 0) { flipNormals = false; }
  28692. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28693. var i;
  28694. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28695. for (i = 0; i < vertex_data.normals.length; i++) {
  28696. vertex_data.normals[i] *= -1;
  28697. }
  28698. }
  28699. if (vertex_data.indices) {
  28700. var temp;
  28701. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28702. // reassign indices
  28703. temp = vertex_data.indices[i + 1];
  28704. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28705. vertex_data.indices[i + 2] = temp;
  28706. }
  28707. }
  28708. vertex_data.applyToMesh(this);
  28709. return this;
  28710. };
  28711. // Instances
  28712. /**
  28713. * Creates a new InstancedMesh object from the mesh model.
  28714. * An instance shares the same properties and the same material than its model.
  28715. * Only these properties of each instance can then be set individually :
  28716. * - position
  28717. * - rotation
  28718. * - rotationQuaternion
  28719. * - setPivotMatrix
  28720. * - scaling
  28721. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28722. * Warning : this method is not supported for Line mesh and LineSystem
  28723. */
  28724. Mesh.prototype.createInstance = function (name) {
  28725. return new BABYLON.InstancedMesh(name, this);
  28726. };
  28727. /**
  28728. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28729. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28730. * This method returns the Mesh.
  28731. */
  28732. Mesh.prototype.synchronizeInstances = function () {
  28733. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28734. var instance = this.instances[instanceIndex];
  28735. instance._syncSubMeshes();
  28736. }
  28737. return this;
  28738. };
  28739. /**
  28740. * Simplify the mesh according to the given array of settings.
  28741. * Function will return immediately and will simplify async. It returns the Mesh.
  28742. * @param settings a collection of simplification settings.
  28743. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28744. * @param type the type of simplification to run.
  28745. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28746. */
  28747. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28748. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28749. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28750. this.getScene().simplificationQueue.addTask({
  28751. settings: settings,
  28752. parallelProcessing: parallelProcessing,
  28753. mesh: this,
  28754. simplificationType: simplificationType,
  28755. successCallback: successCallback
  28756. });
  28757. return this;
  28758. };
  28759. /**
  28760. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28761. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28762. * This should be used together with the simplification to avoid disappearing triangles.
  28763. * Returns the Mesh.
  28764. * @param successCallback an optional success callback to be called after the optimization finished.
  28765. */
  28766. Mesh.prototype.optimizeIndices = function (successCallback) {
  28767. var _this = this;
  28768. var indices = this.getIndices();
  28769. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28770. if (!positions || !indices) {
  28771. return this;
  28772. }
  28773. var vectorPositions = new Array();
  28774. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28775. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28776. }
  28777. var dupes = new Array();
  28778. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28779. var realPos = vectorPositions.length - 1 - iteration;
  28780. var testedPosition = vectorPositions[realPos];
  28781. for (var j = 0; j < realPos; ++j) {
  28782. var againstPosition = vectorPositions[j];
  28783. if (testedPosition.equals(againstPosition)) {
  28784. dupes[realPos] = j;
  28785. break;
  28786. }
  28787. }
  28788. }, function () {
  28789. for (var i = 0; i < indices.length; ++i) {
  28790. indices[i] = dupes[indices[i]] || indices[i];
  28791. }
  28792. //indices are now reordered
  28793. var originalSubMeshes = _this.subMeshes.slice(0);
  28794. _this.setIndices(indices);
  28795. _this.subMeshes = originalSubMeshes;
  28796. if (successCallback) {
  28797. successCallback(_this);
  28798. }
  28799. });
  28800. return this;
  28801. };
  28802. Mesh.prototype.serialize = function (serializationObject) {
  28803. serializationObject.name = this.name;
  28804. serializationObject.id = this.id;
  28805. serializationObject.type = this.getClassName();
  28806. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28807. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28808. }
  28809. serializationObject.position = this.position.asArray();
  28810. if (this.rotationQuaternion) {
  28811. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28812. }
  28813. else if (this.rotation) {
  28814. serializationObject.rotation = this.rotation.asArray();
  28815. }
  28816. serializationObject.scaling = this.scaling.asArray();
  28817. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28818. serializationObject.isEnabled = this.isEnabled(false);
  28819. serializationObject.isVisible = this.isVisible;
  28820. serializationObject.infiniteDistance = this.infiniteDistance;
  28821. serializationObject.pickable = this.isPickable;
  28822. serializationObject.receiveShadows = this.receiveShadows;
  28823. serializationObject.billboardMode = this.billboardMode;
  28824. serializationObject.visibility = this.visibility;
  28825. serializationObject.checkCollisions = this.checkCollisions;
  28826. serializationObject.isBlocker = this.isBlocker;
  28827. // Parent
  28828. if (this.parent) {
  28829. serializationObject.parentId = this.parent.id;
  28830. }
  28831. // Geometry
  28832. serializationObject.isUnIndexed = this.isUnIndexed;
  28833. var geometry = this._geometry;
  28834. if (geometry) {
  28835. var geometryId = geometry.id;
  28836. serializationObject.geometryId = geometryId;
  28837. // SubMeshes
  28838. serializationObject.subMeshes = [];
  28839. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28840. var subMesh = this.subMeshes[subIndex];
  28841. serializationObject.subMeshes.push({
  28842. materialIndex: subMesh.materialIndex,
  28843. verticesStart: subMesh.verticesStart,
  28844. verticesCount: subMesh.verticesCount,
  28845. indexStart: subMesh.indexStart,
  28846. indexCount: subMesh.indexCount
  28847. });
  28848. }
  28849. }
  28850. // Material
  28851. if (this.material) {
  28852. serializationObject.materialId = this.material.id;
  28853. }
  28854. else {
  28855. this.material = null;
  28856. }
  28857. // Morph targets
  28858. if (this.morphTargetManager) {
  28859. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28860. }
  28861. // Skeleton
  28862. if (this.skeleton) {
  28863. serializationObject.skeletonId = this.skeleton.id;
  28864. }
  28865. // Physics
  28866. //TODO implement correct serialization for physics impostors.
  28867. var impostor = this.getPhysicsImpostor();
  28868. if (impostor) {
  28869. serializationObject.physicsMass = impostor.getParam("mass");
  28870. serializationObject.physicsFriction = impostor.getParam("friction");
  28871. serializationObject.physicsRestitution = impostor.getParam("mass");
  28872. serializationObject.physicsImpostor = impostor.type;
  28873. }
  28874. // Metadata
  28875. if (this.metadata) {
  28876. serializationObject.metadata = this.metadata;
  28877. }
  28878. // Instances
  28879. serializationObject.instances = [];
  28880. for (var index = 0; index < this.instances.length; index++) {
  28881. var instance = this.instances[index];
  28882. var serializationInstance = {
  28883. name: instance.name,
  28884. id: instance.id,
  28885. position: instance.position.asArray(),
  28886. scaling: instance.scaling.asArray()
  28887. };
  28888. if (instance.rotationQuaternion) {
  28889. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28890. }
  28891. else if (instance.rotation) {
  28892. serializationInstance.rotation = instance.rotation.asArray();
  28893. }
  28894. serializationObject.instances.push(serializationInstance);
  28895. // Animations
  28896. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28897. serializationInstance.ranges = instance.serializeAnimationRanges();
  28898. }
  28899. //
  28900. // Animations
  28901. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28902. serializationObject.ranges = this.serializeAnimationRanges();
  28903. // Layer mask
  28904. serializationObject.layerMask = this.layerMask;
  28905. // Alpha
  28906. serializationObject.alphaIndex = this.alphaIndex;
  28907. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28908. // Overlay
  28909. serializationObject.overlayAlpha = this.overlayAlpha;
  28910. serializationObject.overlayColor = this.overlayColor.asArray();
  28911. serializationObject.renderOverlay = this.renderOverlay;
  28912. // Fog
  28913. serializationObject.applyFog = this.applyFog;
  28914. // Action Manager
  28915. if (this.actionManager) {
  28916. serializationObject.actions = this.actionManager.serialize(this.name);
  28917. }
  28918. };
  28919. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28920. if (!this.geometry) {
  28921. return;
  28922. }
  28923. this._markSubMeshesAsAttributesDirty();
  28924. var morphTargetManager = this._morphTargetManager;
  28925. if (morphTargetManager && morphTargetManager.vertexCount) {
  28926. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28927. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28928. this.morphTargetManager = null;
  28929. return;
  28930. }
  28931. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28932. var morphTarget = morphTargetManager.getActiveTarget(index);
  28933. var positions = morphTarget.getPositions();
  28934. if (!positions) {
  28935. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28936. return;
  28937. }
  28938. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28939. var normals = morphTarget.getNormals();
  28940. if (normals) {
  28941. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28942. }
  28943. var tangents = morphTarget.getTangents();
  28944. if (tangents) {
  28945. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28946. }
  28947. }
  28948. }
  28949. else {
  28950. var index = 0;
  28951. // Positions
  28952. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28953. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28954. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28955. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28956. }
  28957. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28958. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28959. }
  28960. index++;
  28961. }
  28962. }
  28963. };
  28964. // Statics
  28965. /**
  28966. * Returns a new Mesh object parsed from the source provided.
  28967. * The parameter `parsedMesh` is the source.
  28968. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28969. */
  28970. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28971. var mesh;
  28972. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28973. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28974. }
  28975. else {
  28976. mesh = new Mesh(parsedMesh.name, scene);
  28977. }
  28978. mesh.id = parsedMesh.id;
  28979. if (BABYLON.Tags) {
  28980. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28981. }
  28982. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28983. if (parsedMesh.metadata !== undefined) {
  28984. mesh.metadata = parsedMesh.metadata;
  28985. }
  28986. if (parsedMesh.rotationQuaternion) {
  28987. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28988. }
  28989. else if (parsedMesh.rotation) {
  28990. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28991. }
  28992. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28993. if (parsedMesh.localMatrix) {
  28994. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28995. }
  28996. else if (parsedMesh.pivotMatrix) {
  28997. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28998. }
  28999. mesh.setEnabled(parsedMesh.isEnabled);
  29000. mesh.isVisible = parsedMesh.isVisible;
  29001. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29002. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29003. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29004. if (parsedMesh.applyFog !== undefined) {
  29005. mesh.applyFog = parsedMesh.applyFog;
  29006. }
  29007. if (parsedMesh.pickable !== undefined) {
  29008. mesh.isPickable = parsedMesh.pickable;
  29009. }
  29010. if (parsedMesh.alphaIndex !== undefined) {
  29011. mesh.alphaIndex = parsedMesh.alphaIndex;
  29012. }
  29013. mesh.receiveShadows = parsedMesh.receiveShadows;
  29014. mesh.billboardMode = parsedMesh.billboardMode;
  29015. if (parsedMesh.visibility !== undefined) {
  29016. mesh.visibility = parsedMesh.visibility;
  29017. }
  29018. mesh.checkCollisions = parsedMesh.checkCollisions;
  29019. if (parsedMesh.isBlocker !== undefined) {
  29020. mesh.isBlocker = parsedMesh.isBlocker;
  29021. }
  29022. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29023. // freezeWorldMatrix
  29024. if (parsedMesh.freezeWorldMatrix) {
  29025. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29026. }
  29027. // Parent
  29028. if (parsedMesh.parentId) {
  29029. mesh._waitingParentId = parsedMesh.parentId;
  29030. }
  29031. // Actions
  29032. if (parsedMesh.actions !== undefined) {
  29033. mesh._waitingActions = parsedMesh.actions;
  29034. }
  29035. // Overlay
  29036. if (parsedMesh.overlayAlpha !== undefined) {
  29037. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29038. }
  29039. if (parsedMesh.overlayColor !== undefined) {
  29040. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29041. }
  29042. if (parsedMesh.renderOverlay !== undefined) {
  29043. mesh.renderOverlay = parsedMesh.renderOverlay;
  29044. }
  29045. // Geometry
  29046. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29047. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29048. if (parsedMesh.delayLoadingFile) {
  29049. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29050. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29051. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29052. if (parsedMesh._binaryInfo) {
  29053. mesh._binaryInfo = parsedMesh._binaryInfo;
  29054. }
  29055. mesh._delayInfo = [];
  29056. if (parsedMesh.hasUVs) {
  29057. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29058. }
  29059. if (parsedMesh.hasUVs2) {
  29060. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29061. }
  29062. if (parsedMesh.hasUVs3) {
  29063. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29064. }
  29065. if (parsedMesh.hasUVs4) {
  29066. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29067. }
  29068. if (parsedMesh.hasUVs5) {
  29069. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29070. }
  29071. if (parsedMesh.hasUVs6) {
  29072. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29073. }
  29074. if (parsedMesh.hasColors) {
  29075. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29076. }
  29077. if (parsedMesh.hasMatricesIndices) {
  29078. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29079. }
  29080. if (parsedMesh.hasMatricesWeights) {
  29081. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29082. }
  29083. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29084. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29085. mesh._checkDelayState();
  29086. }
  29087. }
  29088. else {
  29089. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29090. }
  29091. // Material
  29092. if (parsedMesh.materialId) {
  29093. mesh.setMaterialByID(parsedMesh.materialId);
  29094. }
  29095. else {
  29096. mesh.material = null;
  29097. }
  29098. // Morph targets
  29099. if (parsedMesh.morphTargetManagerId > -1) {
  29100. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29101. }
  29102. // Skeleton
  29103. if (parsedMesh.skeletonId > -1) {
  29104. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29105. if (parsedMesh.numBoneInfluencers) {
  29106. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29107. }
  29108. }
  29109. // Animations
  29110. if (parsedMesh.animations) {
  29111. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29112. var parsedAnimation = parsedMesh.animations[animationIndex];
  29113. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29114. }
  29115. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29116. }
  29117. if (parsedMesh.autoAnimate) {
  29118. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29119. }
  29120. // Layer Mask
  29121. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29122. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29123. }
  29124. else {
  29125. mesh.layerMask = 0x0FFFFFFF;
  29126. }
  29127. // Physics
  29128. if (parsedMesh.physicsImpostor) {
  29129. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29130. mass: parsedMesh.physicsMass,
  29131. friction: parsedMesh.physicsFriction,
  29132. restitution: parsedMesh.physicsRestitution
  29133. }, scene);
  29134. }
  29135. // Instances
  29136. if (parsedMesh.instances) {
  29137. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29138. var parsedInstance = parsedMesh.instances[index];
  29139. var instance = mesh.createInstance(parsedInstance.name);
  29140. if (parsedInstance.id) {
  29141. instance.id = parsedInstance.id;
  29142. }
  29143. if (BABYLON.Tags) {
  29144. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29145. }
  29146. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29147. if (parsedInstance.parentId) {
  29148. instance._waitingParentId = parsedInstance.parentId;
  29149. }
  29150. if (parsedInstance.rotationQuaternion) {
  29151. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29152. }
  29153. else if (parsedInstance.rotation) {
  29154. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29155. }
  29156. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29157. instance.checkCollisions = mesh.checkCollisions;
  29158. if (parsedMesh.animations) {
  29159. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29160. parsedAnimation = parsedMesh.animations[animationIndex];
  29161. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29162. }
  29163. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29164. }
  29165. }
  29166. }
  29167. return mesh;
  29168. };
  29169. /**
  29170. * Creates a ribbon mesh.
  29171. * Please consider using the same method from the MeshBuilder class instead.
  29172. * 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.
  29173. *
  29174. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29175. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29176. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29177. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29178. * 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.
  29179. * 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.
  29180. * 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
  29181. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29182. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29183. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29184. */
  29185. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29186. if (closeArray === void 0) { closeArray = false; }
  29187. if (updatable === void 0) { updatable = false; }
  29188. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29189. pathArray: pathArray,
  29190. closeArray: closeArray,
  29191. closePath: closePath,
  29192. offset: offset,
  29193. updatable: updatable,
  29194. sideOrientation: sideOrientation,
  29195. instance: instance
  29196. }, scene);
  29197. };
  29198. /**
  29199. * Creates a plane polygonal mesh. By default, this is a disc.
  29200. * Please consider using the same method from the MeshBuilder class instead.
  29201. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29202. * 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.
  29203. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29204. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29206. */
  29207. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29208. if (scene === void 0) { scene = null; }
  29209. var options = {
  29210. radius: radius,
  29211. tessellation: tessellation,
  29212. sideOrientation: sideOrientation,
  29213. updatable: updatable
  29214. };
  29215. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29216. };
  29217. /**
  29218. * Creates a box mesh.
  29219. * Please consider using the same method from the MeshBuilder class instead.
  29220. * The parameter `size` sets the size (float) of each box side (default 1).
  29221. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29222. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29224. */
  29225. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29226. if (scene === void 0) { scene = null; }
  29227. var options = {
  29228. size: size,
  29229. sideOrientation: sideOrientation,
  29230. updatable: updatable
  29231. };
  29232. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29233. };
  29234. /**
  29235. * Creates a sphere mesh.
  29236. * Please consider using the same method from the MeshBuilder class instead.
  29237. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29238. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29239. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29240. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29241. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29242. */
  29243. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29244. var options = {
  29245. segments: segments,
  29246. diameterX: diameter,
  29247. diameterY: diameter,
  29248. diameterZ: diameter,
  29249. sideOrientation: sideOrientation,
  29250. updatable: updatable
  29251. };
  29252. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29253. };
  29254. /**
  29255. * Creates a cylinder or a cone mesh.
  29256. * Please consider using the same method from the MeshBuilder class instead.
  29257. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29258. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29259. * 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.
  29260. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29261. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29262. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29263. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29265. */
  29266. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29267. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29268. if (scene !== undefined) {
  29269. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29270. updatable = scene;
  29271. }
  29272. scene = subdivisions;
  29273. subdivisions = 1;
  29274. }
  29275. var options = {
  29276. height: height,
  29277. diameterTop: diameterTop,
  29278. diameterBottom: diameterBottom,
  29279. tessellation: tessellation,
  29280. subdivisions: subdivisions,
  29281. sideOrientation: sideOrientation,
  29282. updatable: updatable
  29283. };
  29284. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29285. };
  29286. // Torus (Code from SharpDX.org)
  29287. /**
  29288. * Creates a torus mesh.
  29289. * Please consider using the same method from the MeshBuilder class instead.
  29290. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29291. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29292. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29294. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29296. */
  29297. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29298. var options = {
  29299. diameter: diameter,
  29300. thickness: thickness,
  29301. tessellation: tessellation,
  29302. sideOrientation: sideOrientation,
  29303. updatable: updatable
  29304. };
  29305. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29306. };
  29307. /**
  29308. * Creates a torus knot mesh.
  29309. * Please consider using the same method from the MeshBuilder class instead.
  29310. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29311. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29312. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29313. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29314. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29315. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29316. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29317. */
  29318. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29319. var options = {
  29320. radius: radius,
  29321. tube: tube,
  29322. radialSegments: radialSegments,
  29323. tubularSegments: tubularSegments,
  29324. p: p,
  29325. q: q,
  29326. sideOrientation: sideOrientation,
  29327. updatable: updatable
  29328. };
  29329. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29330. };
  29331. /**
  29332. * Creates a line mesh.
  29333. * Please consider using the same method from the MeshBuilder class instead.
  29334. * 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.
  29335. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29336. * The parameter `points` is an array successive Vector3.
  29337. * 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
  29338. * When updating an instance, remember that only point positions can change, not the number of points.
  29339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29340. */
  29341. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29342. if (scene === void 0) { scene = null; }
  29343. if (updatable === void 0) { updatable = false; }
  29344. if (instance === void 0) { instance = null; }
  29345. var options = {
  29346. points: points,
  29347. updatable: updatable,
  29348. instance: instance
  29349. };
  29350. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29351. };
  29352. /**
  29353. * Creates a dashed line mesh.
  29354. * Please consider using the same method from the MeshBuilder class instead.
  29355. * 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.
  29356. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29357. * The parameter `points` is an array successive Vector3.
  29358. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29359. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29360. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29361. * 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
  29362. * When updating an instance, remember that only point positions can change, not the number of points.
  29363. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29364. */
  29365. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29366. if (scene === void 0) { scene = null; }
  29367. var options = {
  29368. points: points,
  29369. dashSize: dashSize,
  29370. gapSize: gapSize,
  29371. dashNb: dashNb,
  29372. updatable: updatable,
  29373. instance: instance
  29374. };
  29375. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29376. };
  29377. /**
  29378. * Creates a polygon mesh.
  29379. * Please consider using the same method from the MeshBuilder class instead.
  29380. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29381. * 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.
  29382. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29383. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29384. * Remember you can only change the shape positions, not their number when updating a polygon.
  29385. */
  29386. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29387. var options = {
  29388. shape: shape,
  29389. holes: holes,
  29390. updatable: updatable,
  29391. sideOrientation: sideOrientation
  29392. };
  29393. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29394. };
  29395. /**
  29396. * Creates an extruded polygon mesh, with depth in the Y direction.
  29397. * Please consider using the same method from the MeshBuilder class instead.
  29398. */
  29399. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29400. var options = {
  29401. shape: shape,
  29402. holes: holes,
  29403. depth: depth,
  29404. updatable: updatable,
  29405. sideOrientation: sideOrientation
  29406. };
  29407. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29408. };
  29409. /**
  29410. * Creates an extruded shape mesh.
  29411. * 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.
  29412. * Please consider using the same method from the MeshBuilder class instead.
  29413. *
  29414. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29415. * 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
  29416. * extruded along the Z axis.
  29417. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29418. * 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.
  29419. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29420. * 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
  29421. * 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
  29422. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29423. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29424. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29426. */
  29427. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29428. if (scene === void 0) { scene = null; }
  29429. var options = {
  29430. shape: shape,
  29431. path: path,
  29432. scale: scale,
  29433. rotation: rotation,
  29434. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29435. sideOrientation: sideOrientation,
  29436. instance: instance,
  29437. updatable: updatable
  29438. };
  29439. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29440. };
  29441. /**
  29442. * Creates an custom extruded shape mesh.
  29443. * 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.
  29444. * Please consider using the same method from the MeshBuilder class instead.
  29445. *
  29446. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29447. * 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
  29448. * extruded along the Z axis.
  29449. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29450. * 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
  29451. * and the distance of this point from the begining of the path :
  29452. * ```javascript
  29453. * var rotationFunction = function(i, distance) {
  29454. * // do things
  29455. * return rotationValue; }
  29456. * ```
  29457. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29458. * 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
  29459. * and the distance of this point from the begining of the path :
  29460. * ```javascript
  29461. * var scaleFunction = function(i, distance) {
  29462. * // do things
  29463. * return scaleValue;}
  29464. * ```
  29465. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29466. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29467. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29468. * 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
  29469. * 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
  29470. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29474. */
  29475. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29476. var options = {
  29477. shape: shape,
  29478. path: path,
  29479. scaleFunction: scaleFunction,
  29480. rotationFunction: rotationFunction,
  29481. ribbonCloseArray: ribbonCloseArray,
  29482. ribbonClosePath: ribbonClosePath,
  29483. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29484. sideOrientation: sideOrientation,
  29485. instance: instance,
  29486. updatable: updatable
  29487. };
  29488. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29489. };
  29490. /**
  29491. * Creates lathe mesh.
  29492. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29493. * Please consider using the same method from the MeshBuilder class instead.
  29494. * 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
  29495. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29496. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29497. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29498. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29499. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29500. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29501. */
  29502. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29503. var options = {
  29504. shape: shape,
  29505. radius: radius,
  29506. tessellation: tessellation,
  29507. sideOrientation: sideOrientation,
  29508. updatable: updatable
  29509. };
  29510. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29511. };
  29512. /**
  29513. * Creates a plane mesh.
  29514. * Please consider using the same method from the MeshBuilder class instead.
  29515. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29516. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29517. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29518. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29519. */
  29520. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29521. var options = {
  29522. size: size,
  29523. width: size,
  29524. height: size,
  29525. sideOrientation: sideOrientation,
  29526. updatable: updatable
  29527. };
  29528. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29529. };
  29530. /**
  29531. * Creates a ground mesh.
  29532. * Please consider using the same method from the MeshBuilder class instead.
  29533. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29534. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29536. */
  29537. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29538. var options = {
  29539. width: width,
  29540. height: height,
  29541. subdivisions: subdivisions,
  29542. updatable: updatable
  29543. };
  29544. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29545. };
  29546. /**
  29547. * Creates a tiled ground mesh.
  29548. * Please consider using the same method from the MeshBuilder class instead.
  29549. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29550. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29551. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29552. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29553. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29554. * numbers of subdivisions on the ground width and height of each tile.
  29555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29556. */
  29557. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29558. var options = {
  29559. xmin: xmin,
  29560. zmin: zmin,
  29561. xmax: xmax,
  29562. zmax: zmax,
  29563. subdivisions: subdivisions,
  29564. precision: precision,
  29565. updatable: updatable
  29566. };
  29567. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29568. };
  29569. /**
  29570. * Creates a ground mesh from a height map.
  29571. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29572. * Please consider using the same method from the MeshBuilder class instead.
  29573. * The parameter `url` sets the URL of the height map image resource.
  29574. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29575. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29576. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29577. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29578. * 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).
  29579. * This function is passed the newly built mesh :
  29580. * ```javascript
  29581. * function(mesh) { // do things
  29582. * return; }
  29583. * ```
  29584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29585. */
  29586. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29587. var options = {
  29588. width: width,
  29589. height: height,
  29590. subdivisions: subdivisions,
  29591. minHeight: minHeight,
  29592. maxHeight: maxHeight,
  29593. updatable: updatable,
  29594. onReady: onReady
  29595. };
  29596. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29597. };
  29598. /**
  29599. * Creates a tube mesh.
  29600. * 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.
  29601. * Please consider using the same method from the MeshBuilder class instead.
  29602. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29603. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29604. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29605. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29606. * 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.
  29607. * It must return a radius value (positive float) :
  29608. * ```javascript
  29609. * var radiusFunction = function(i, distance) {
  29610. * // do things
  29611. * return radius; }
  29612. * ```
  29613. * 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
  29614. * 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
  29615. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29616. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29617. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29618. */
  29619. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29620. var options = {
  29621. path: path,
  29622. radius: radius,
  29623. tessellation: tessellation,
  29624. radiusFunction: radiusFunction,
  29625. arc: 1,
  29626. cap: cap,
  29627. updatable: updatable,
  29628. sideOrientation: sideOrientation,
  29629. instance: instance
  29630. };
  29631. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29632. };
  29633. /**
  29634. * Creates a polyhedron mesh.
  29635. * Please consider using the same method from the MeshBuilder class instead.
  29636. * 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
  29637. * to choose the wanted type.
  29638. * The parameter `size` (positive float, default 1) sets the polygon size.
  29639. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29640. * 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`.
  29641. * 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
  29642. * 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)`).
  29643. * 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
  29644. * 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.
  29645. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29646. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29647. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29648. */
  29649. Mesh.CreatePolyhedron = function (name, options, scene) {
  29650. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29651. };
  29652. /**
  29653. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29654. * Please consider using the same method from the MeshBuilder class instead.
  29655. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29656. * 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`).
  29657. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29658. * 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.
  29659. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29660. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29662. */
  29663. Mesh.CreateIcoSphere = function (name, options, scene) {
  29664. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29665. };
  29666. /**
  29667. * Creates a decal mesh.
  29668. * Please consider using the same method from the MeshBuilder class instead.
  29669. * 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.
  29670. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29671. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29672. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29673. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29674. */
  29675. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29676. var options = {
  29677. position: position,
  29678. normal: normal,
  29679. size: size,
  29680. angle: angle
  29681. };
  29682. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29683. };
  29684. // Skeletons
  29685. /**
  29686. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29687. */
  29688. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29689. if (!this._sourcePositions) {
  29690. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29691. if (!source) {
  29692. return this._sourcePositions;
  29693. }
  29694. this._sourcePositions = new Float32Array(source);
  29695. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29696. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29697. }
  29698. }
  29699. return this._sourcePositions;
  29700. };
  29701. /**
  29702. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29703. */
  29704. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29705. if (!this._sourceNormals) {
  29706. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29707. if (!source) {
  29708. return this._sourceNormals;
  29709. }
  29710. this._sourceNormals = new Float32Array(source);
  29711. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29712. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29713. }
  29714. }
  29715. return this._sourceNormals;
  29716. };
  29717. /**
  29718. * Updates the vertex buffer by applying transformation from the bones.
  29719. * Returns the Mesh.
  29720. *
  29721. * @param {skeleton} skeleton to apply
  29722. */
  29723. Mesh.prototype.applySkeleton = function (skeleton) {
  29724. if (!this.geometry) {
  29725. return this;
  29726. }
  29727. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29728. return this;
  29729. }
  29730. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29731. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29732. return this;
  29733. }
  29734. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29735. return this;
  29736. }
  29737. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29738. return this;
  29739. }
  29740. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29741. return this;
  29742. }
  29743. if (!this._sourcePositions) {
  29744. var submeshes = this.subMeshes.slice();
  29745. this.setPositionsForCPUSkinning();
  29746. this.subMeshes = submeshes;
  29747. }
  29748. if (!this._sourceNormals) {
  29749. this.setNormalsForCPUSkinning();
  29750. }
  29751. // positionsData checks for not being Float32Array will only pass at most once
  29752. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29753. if (!positionsData) {
  29754. return this;
  29755. }
  29756. if (!(positionsData instanceof Float32Array)) {
  29757. positionsData = new Float32Array(positionsData);
  29758. }
  29759. // normalsData checks for not being Float32Array will only pass at most once
  29760. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29761. if (!normalsData) {
  29762. return this;
  29763. }
  29764. if (!(normalsData instanceof Float32Array)) {
  29765. normalsData = new Float32Array(normalsData);
  29766. }
  29767. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29768. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29769. if (!matricesWeightsData || !matricesIndicesData) {
  29770. return this;
  29771. }
  29772. var needExtras = this.numBoneInfluencers > 4;
  29773. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29774. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29775. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29776. var tempVector3 = BABYLON.Vector3.Zero();
  29777. var finalMatrix = new BABYLON.Matrix();
  29778. var tempMatrix = new BABYLON.Matrix();
  29779. var matWeightIdx = 0;
  29780. var inf;
  29781. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29782. var weight;
  29783. for (inf = 0; inf < 4; inf++) {
  29784. weight = matricesWeightsData[matWeightIdx + inf];
  29785. if (weight > 0) {
  29786. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29787. finalMatrix.addToSelf(tempMatrix);
  29788. }
  29789. else
  29790. break;
  29791. }
  29792. if (needExtras) {
  29793. for (inf = 0; inf < 4; inf++) {
  29794. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29795. if (weight > 0) {
  29796. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  29797. finalMatrix.addToSelf(tempMatrix);
  29798. }
  29799. else
  29800. break;
  29801. }
  29802. }
  29803. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29804. tempVector3.toArray(positionsData, index);
  29805. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29806. tempVector3.toArray(normalsData, index);
  29807. finalMatrix.reset();
  29808. }
  29809. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29810. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29811. return this;
  29812. };
  29813. // Tools
  29814. /**
  29815. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29816. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29817. */
  29818. Mesh.MinMax = function (meshes) {
  29819. var minVector = null;
  29820. var maxVector = null;
  29821. meshes.forEach(function (mesh, index, array) {
  29822. var boundingInfo = mesh.getBoundingInfo();
  29823. var boundingBox = boundingInfo.boundingBox;
  29824. if (!minVector || !maxVector) {
  29825. minVector = boundingBox.minimumWorld;
  29826. maxVector = boundingBox.maximumWorld;
  29827. }
  29828. else {
  29829. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29830. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29831. }
  29832. });
  29833. if (!minVector || !maxVector) {
  29834. return {
  29835. min: BABYLON.Vector3.Zero(),
  29836. max: BABYLON.Vector3.Zero()
  29837. };
  29838. }
  29839. return {
  29840. min: minVector,
  29841. max: maxVector
  29842. };
  29843. };
  29844. /**
  29845. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29846. */
  29847. Mesh.Center = function (meshesOrMinMaxVector) {
  29848. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29849. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29850. };
  29851. /**
  29852. * Merge the array of meshes into a single mesh for performance reasons.
  29853. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29854. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29855. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29856. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29857. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29858. */
  29859. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29860. if (disposeSource === void 0) { disposeSource = true; }
  29861. var index;
  29862. if (!allow32BitsIndices) {
  29863. var totalVertices = 0;
  29864. // Counting vertices
  29865. for (index = 0; index < meshes.length; index++) {
  29866. if (meshes[index]) {
  29867. totalVertices += meshes[index].getTotalVertices();
  29868. if (totalVertices > 65536) {
  29869. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29870. return null;
  29871. }
  29872. }
  29873. }
  29874. }
  29875. // Merge
  29876. var vertexData = null;
  29877. var otherVertexData;
  29878. var indiceArray = new Array();
  29879. var source = null;
  29880. for (index = 0; index < meshes.length; index++) {
  29881. if (meshes[index]) {
  29882. meshes[index].computeWorldMatrix(true);
  29883. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29884. otherVertexData.transform(meshes[index].getWorldMatrix());
  29885. if (vertexData) {
  29886. vertexData.merge(otherVertexData);
  29887. }
  29888. else {
  29889. vertexData = otherVertexData;
  29890. source = meshes[index];
  29891. }
  29892. if (subdivideWithSubMeshes) {
  29893. indiceArray.push(meshes[index].getTotalIndices());
  29894. }
  29895. }
  29896. }
  29897. source = source;
  29898. if (!meshSubclass) {
  29899. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29900. }
  29901. vertexData.applyToMesh(meshSubclass);
  29902. // Setting properties
  29903. meshSubclass.material = source.material;
  29904. meshSubclass.checkCollisions = source.checkCollisions;
  29905. // Cleaning
  29906. if (disposeSource) {
  29907. for (index = 0; index < meshes.length; index++) {
  29908. if (meshes[index]) {
  29909. meshes[index].dispose();
  29910. }
  29911. }
  29912. }
  29913. // Subdivide
  29914. if (subdivideWithSubMeshes) {
  29915. //-- Suppresions du submesh global
  29916. meshSubclass.releaseSubMeshes();
  29917. index = 0;
  29918. var offset = 0;
  29919. //-- aplique la subdivision en fonction du tableau d'indices
  29920. while (index < indiceArray.length) {
  29921. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29922. offset += indiceArray[index];
  29923. index++;
  29924. }
  29925. }
  29926. return meshSubclass;
  29927. };
  29928. // Consts
  29929. Mesh._FRONTSIDE = 0;
  29930. Mesh._BACKSIDE = 1;
  29931. Mesh._DOUBLESIDE = 2;
  29932. Mesh._DEFAULTSIDE = 0;
  29933. Mesh._NO_CAP = 0;
  29934. Mesh._CAP_START = 1;
  29935. Mesh._CAP_END = 2;
  29936. Mesh._CAP_ALL = 3;
  29937. return Mesh;
  29938. }(BABYLON.AbstractMesh));
  29939. BABYLON.Mesh = Mesh;
  29940. })(BABYLON || (BABYLON = {}));
  29941. //# sourceMappingURL=babylon.mesh.js.map
  29942. var BABYLON;
  29943. (function (BABYLON) {
  29944. var BaseSubMesh = /** @class */ (function () {
  29945. function BaseSubMesh() {
  29946. }
  29947. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29948. get: function () {
  29949. return this._materialEffect;
  29950. },
  29951. enumerable: true,
  29952. configurable: true
  29953. });
  29954. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29955. if (defines === void 0) { defines = null; }
  29956. if (this._materialEffect === effect) {
  29957. if (!effect) {
  29958. this._materialDefines = null;
  29959. }
  29960. return;
  29961. }
  29962. this._materialDefines = defines;
  29963. this._materialEffect = effect;
  29964. };
  29965. return BaseSubMesh;
  29966. }());
  29967. BABYLON.BaseSubMesh = BaseSubMesh;
  29968. var SubMesh = /** @class */ (function (_super) {
  29969. __extends(SubMesh, _super);
  29970. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29971. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29972. var _this = _super.call(this) || this;
  29973. _this.materialIndex = materialIndex;
  29974. _this.verticesStart = verticesStart;
  29975. _this.verticesCount = verticesCount;
  29976. _this.indexStart = indexStart;
  29977. _this.indexCount = indexCount;
  29978. _this._renderId = 0;
  29979. _this._mesh = mesh;
  29980. _this._renderingMesh = renderingMesh || mesh;
  29981. mesh.subMeshes.push(_this);
  29982. _this._trianglePlanes = [];
  29983. _this._id = mesh.subMeshes.length - 1;
  29984. if (createBoundingBox) {
  29985. _this.refreshBoundingInfo();
  29986. mesh.computeWorldMatrix(true);
  29987. }
  29988. return _this;
  29989. }
  29990. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29991. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29992. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29993. };
  29994. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29995. get: function () {
  29996. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29997. },
  29998. enumerable: true,
  29999. configurable: true
  30000. });
  30001. /**
  30002. * Returns the submesh BoudingInfo object.
  30003. */
  30004. SubMesh.prototype.getBoundingInfo = function () {
  30005. if (this.IsGlobal) {
  30006. return this._mesh.getBoundingInfo();
  30007. }
  30008. return this._boundingInfo;
  30009. };
  30010. /**
  30011. * Sets the submesh BoundingInfo.
  30012. * Return the SubMesh.
  30013. */
  30014. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30015. this._boundingInfo = boundingInfo;
  30016. return this;
  30017. };
  30018. /**
  30019. * Returns the mesh of the current submesh.
  30020. */
  30021. SubMesh.prototype.getMesh = function () {
  30022. return this._mesh;
  30023. };
  30024. /**
  30025. * Returns the rendering mesh of the submesh.
  30026. */
  30027. SubMesh.prototype.getRenderingMesh = function () {
  30028. return this._renderingMesh;
  30029. };
  30030. /**
  30031. * Returns the submesh material.
  30032. */
  30033. SubMesh.prototype.getMaterial = function () {
  30034. var rootMaterial = this._renderingMesh.material;
  30035. if (rootMaterial === null || rootMaterial === undefined) {
  30036. return this._mesh.getScene().defaultMaterial;
  30037. }
  30038. else if (rootMaterial.getSubMaterial) {
  30039. var multiMaterial = rootMaterial;
  30040. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30041. if (this._currentMaterial !== effectiveMaterial) {
  30042. this._currentMaterial = effectiveMaterial;
  30043. this._materialDefines = null;
  30044. }
  30045. return effectiveMaterial;
  30046. }
  30047. return rootMaterial;
  30048. };
  30049. // Methods
  30050. /**
  30051. * Sets a new updated BoundingInfo object to the submesh.
  30052. * Returns the SubMesh.
  30053. */
  30054. SubMesh.prototype.refreshBoundingInfo = function () {
  30055. this._lastColliderWorldVertices = null;
  30056. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30057. return this;
  30058. }
  30059. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30060. if (!data) {
  30061. this._boundingInfo = this._mesh.getBoundingInfo();
  30062. return this;
  30063. }
  30064. var indices = this._renderingMesh.getIndices();
  30065. var extend;
  30066. //is this the only submesh?
  30067. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30068. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30069. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30070. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30071. }
  30072. else {
  30073. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30074. }
  30075. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30076. return this;
  30077. };
  30078. SubMesh.prototype._checkCollision = function (collider) {
  30079. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30080. return boundingInfo._checkCollision(collider);
  30081. };
  30082. /**
  30083. * Updates the submesh BoundingInfo.
  30084. * Returns the Submesh.
  30085. */
  30086. SubMesh.prototype.updateBoundingInfo = function (world) {
  30087. var boundingInfo = this.getBoundingInfo();
  30088. if (!boundingInfo) {
  30089. this.refreshBoundingInfo();
  30090. boundingInfo = this.getBoundingInfo();
  30091. }
  30092. boundingInfo.update(world);
  30093. return this;
  30094. };
  30095. /**
  30096. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30097. * Boolean returned.
  30098. */
  30099. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30100. var boundingInfo = this.getBoundingInfo();
  30101. if (!boundingInfo) {
  30102. return false;
  30103. }
  30104. return boundingInfo.isInFrustum(frustumPlanes);
  30105. };
  30106. /**
  30107. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30108. * Boolean returned.
  30109. */
  30110. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30111. var boundingInfo = this.getBoundingInfo();
  30112. if (!boundingInfo) {
  30113. return false;
  30114. }
  30115. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30116. };
  30117. /**
  30118. * Renders the submesh.
  30119. * Returns it.
  30120. */
  30121. SubMesh.prototype.render = function (enableAlphaMode) {
  30122. this._renderingMesh.render(this, enableAlphaMode);
  30123. return this;
  30124. };
  30125. /**
  30126. * Returns a new Index Buffer.
  30127. * Type returned : WebGLBuffer.
  30128. */
  30129. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30130. if (!this._linesIndexBuffer) {
  30131. var linesIndices = [];
  30132. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30133. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30134. }
  30135. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30136. this.linesIndexCount = linesIndices.length;
  30137. }
  30138. return this._linesIndexBuffer;
  30139. };
  30140. /**
  30141. * True is the passed Ray intersects the submesh bounding box.
  30142. * Boolean returned.
  30143. */
  30144. SubMesh.prototype.canIntersects = function (ray) {
  30145. var boundingInfo = this.getBoundingInfo();
  30146. if (!boundingInfo) {
  30147. return false;
  30148. }
  30149. return ray.intersectsBox(boundingInfo.boundingBox);
  30150. };
  30151. /**
  30152. * Returns an object IntersectionInfo.
  30153. */
  30154. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30155. var intersectInfo = null;
  30156. // LineMesh first as it's also a Mesh...
  30157. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30158. var lineMesh = this._mesh;
  30159. // Line test
  30160. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30161. var p0 = positions[indices[index]];
  30162. var p1 = positions[indices[index + 1]];
  30163. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30164. if (length < 0) {
  30165. continue;
  30166. }
  30167. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30168. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30169. if (fastCheck) {
  30170. break;
  30171. }
  30172. }
  30173. }
  30174. }
  30175. else {
  30176. // Triangles test
  30177. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30178. var p0 = positions[indices[index]];
  30179. var p1 = positions[indices[index + 1]];
  30180. var p2 = positions[indices[index + 2]];
  30181. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30182. if (currentIntersectInfo) {
  30183. if (currentIntersectInfo.distance < 0) {
  30184. continue;
  30185. }
  30186. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30187. intersectInfo = currentIntersectInfo;
  30188. intersectInfo.faceId = index / 3;
  30189. if (fastCheck) {
  30190. break;
  30191. }
  30192. }
  30193. }
  30194. }
  30195. }
  30196. return intersectInfo;
  30197. };
  30198. SubMesh.prototype._rebuild = function () {
  30199. if (this._linesIndexBuffer) {
  30200. this._linesIndexBuffer = null;
  30201. }
  30202. };
  30203. // Clone
  30204. /**
  30205. * Creates a new Submesh from the passed Mesh.
  30206. */
  30207. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30208. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30209. if (!this.IsGlobal) {
  30210. var boundingInfo = this.getBoundingInfo();
  30211. if (!boundingInfo) {
  30212. return result;
  30213. }
  30214. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30215. }
  30216. return result;
  30217. };
  30218. // Dispose
  30219. /**
  30220. * Disposes the Submesh.
  30221. * Returns nothing.
  30222. */
  30223. SubMesh.prototype.dispose = function () {
  30224. if (this._linesIndexBuffer) {
  30225. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30226. this._linesIndexBuffer = null;
  30227. }
  30228. // Remove from mesh
  30229. var index = this._mesh.subMeshes.indexOf(this);
  30230. this._mesh.subMeshes.splice(index, 1);
  30231. };
  30232. // Statics
  30233. /**
  30234. * Creates a new Submesh from the passed parameters :
  30235. * - materialIndex (integer) : the index of the main mesh material.
  30236. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30237. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30238. * - mesh (Mesh) : the main mesh to create the submesh from.
  30239. * - renderingMesh (optional Mesh) : rendering mesh.
  30240. */
  30241. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30242. var minVertexIndex = Number.MAX_VALUE;
  30243. var maxVertexIndex = -Number.MAX_VALUE;
  30244. renderingMesh = (renderingMesh || mesh);
  30245. var indices = renderingMesh.getIndices();
  30246. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30247. var vertexIndex = indices[index];
  30248. if (vertexIndex < minVertexIndex)
  30249. minVertexIndex = vertexIndex;
  30250. if (vertexIndex > maxVertexIndex)
  30251. maxVertexIndex = vertexIndex;
  30252. }
  30253. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30254. };
  30255. return SubMesh;
  30256. }(BaseSubMesh));
  30257. BABYLON.SubMesh = SubMesh;
  30258. })(BABYLON || (BABYLON = {}));
  30259. //# sourceMappingURL=babylon.subMesh.js.map
  30260. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30261. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30262. s = arguments[i];
  30263. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30264. t[p] = s[p];
  30265. }
  30266. return t;
  30267. };
  30268. var BABYLON;
  30269. (function (BABYLON) {
  30270. /**
  30271. * Manages the defines for the Material.
  30272. */
  30273. var MaterialDefines = /** @class */ (function () {
  30274. function MaterialDefines() {
  30275. this._isDirty = true;
  30276. this._areLightsDirty = true;
  30277. this._areAttributesDirty = true;
  30278. this._areTexturesDirty = true;
  30279. this._areFresnelDirty = true;
  30280. this._areMiscDirty = true;
  30281. this._areImageProcessingDirty = true;
  30282. this._normals = false;
  30283. this._uvs = false;
  30284. this._needNormals = false;
  30285. this._needUVs = false;
  30286. }
  30287. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30288. /**
  30289. * Specifies if the material needs to be re-calculated.
  30290. */
  30291. get: function () {
  30292. return this._isDirty;
  30293. },
  30294. enumerable: true,
  30295. configurable: true
  30296. });
  30297. /**
  30298. * Marks the material to indicate that it has been re-calculated.
  30299. */
  30300. MaterialDefines.prototype.markAsProcessed = function () {
  30301. this._isDirty = false;
  30302. this._areAttributesDirty = false;
  30303. this._areTexturesDirty = false;
  30304. this._areFresnelDirty = false;
  30305. this._areLightsDirty = false;
  30306. this._areMiscDirty = false;
  30307. this._areImageProcessingDirty = false;
  30308. };
  30309. /**
  30310. * Marks the material to indicate that it needs to be re-calculated.
  30311. */
  30312. MaterialDefines.prototype.markAsUnprocessed = function () {
  30313. this._isDirty = true;
  30314. };
  30315. /**
  30316. * Marks the material to indicate all of its defines need to be re-calculated.
  30317. */
  30318. MaterialDefines.prototype.markAllAsDirty = function () {
  30319. this._areTexturesDirty = true;
  30320. this._areAttributesDirty = true;
  30321. this._areLightsDirty = true;
  30322. this._areFresnelDirty = true;
  30323. this._areMiscDirty = true;
  30324. this._areImageProcessingDirty = true;
  30325. this._isDirty = true;
  30326. };
  30327. /**
  30328. * Marks the material to indicate that image processing needs to be re-calculated.
  30329. */
  30330. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30331. this._areImageProcessingDirty = true;
  30332. this._isDirty = true;
  30333. };
  30334. /**
  30335. * Marks the material to indicate the lights need to be re-calculated.
  30336. */
  30337. MaterialDefines.prototype.markAsLightDirty = function () {
  30338. this._areLightsDirty = true;
  30339. this._isDirty = true;
  30340. };
  30341. /**
  30342. * Marks the attribute state as changed.
  30343. */
  30344. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30345. this._areAttributesDirty = true;
  30346. this._isDirty = true;
  30347. };
  30348. /**
  30349. * Marks the texture state as changed.
  30350. */
  30351. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30352. this._areTexturesDirty = true;
  30353. this._isDirty = true;
  30354. };
  30355. /**
  30356. * Marks the fresnel state as changed.
  30357. */
  30358. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30359. this._areFresnelDirty = true;
  30360. this._isDirty = true;
  30361. };
  30362. /**
  30363. * Marks the misc state as changed.
  30364. */
  30365. MaterialDefines.prototype.markAsMiscDirty = function () {
  30366. this._areMiscDirty = true;
  30367. this._isDirty = true;
  30368. };
  30369. /**
  30370. * Rebuilds the material defines.
  30371. */
  30372. MaterialDefines.prototype.rebuild = function () {
  30373. if (this._keys) {
  30374. delete this._keys;
  30375. }
  30376. this._keys = [];
  30377. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30378. var key = _a[_i];
  30379. if (key[0] === "_") {
  30380. continue;
  30381. }
  30382. this._keys.push(key);
  30383. }
  30384. };
  30385. /**
  30386. * Specifies if two material defines are equal.
  30387. * @param other - A material define instance to compare to.
  30388. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30389. */
  30390. MaterialDefines.prototype.isEqual = function (other) {
  30391. if (this._keys.length !== other._keys.length) {
  30392. return false;
  30393. }
  30394. for (var index = 0; index < this._keys.length; index++) {
  30395. var prop = this._keys[index];
  30396. if (this[prop] !== other[prop]) {
  30397. return false;
  30398. }
  30399. }
  30400. return true;
  30401. };
  30402. /**
  30403. * Clones this instance's defines to another instance.
  30404. * @param other - material defines to clone values to.
  30405. */
  30406. MaterialDefines.prototype.cloneTo = function (other) {
  30407. if (this._keys.length !== other._keys.length) {
  30408. other._keys = this._keys.slice(0);
  30409. }
  30410. for (var index = 0; index < this._keys.length; index++) {
  30411. var prop = this._keys[index];
  30412. other[prop] = this[prop];
  30413. }
  30414. };
  30415. /**
  30416. * Resets the material define values.
  30417. */
  30418. MaterialDefines.prototype.reset = function () {
  30419. for (var index = 0; index < this._keys.length; index++) {
  30420. var prop = this._keys[index];
  30421. if (typeof (this[prop]) === "number") {
  30422. this[prop] = 0;
  30423. }
  30424. else {
  30425. this[prop] = false;
  30426. }
  30427. }
  30428. };
  30429. /**
  30430. * Converts the material define values to a string.
  30431. * @returns - String of material define information.
  30432. */
  30433. MaterialDefines.prototype.toString = function () {
  30434. var result = "";
  30435. for (var index = 0; index < this._keys.length; index++) {
  30436. var prop = this._keys[index];
  30437. var value = this[prop];
  30438. if (typeof (value) === "number") {
  30439. result += "#define " + prop + " " + this[prop] + "\n";
  30440. }
  30441. else if (value) {
  30442. result += "#define " + prop + "\n";
  30443. }
  30444. }
  30445. return result;
  30446. };
  30447. return MaterialDefines;
  30448. }());
  30449. BABYLON.MaterialDefines = MaterialDefines;
  30450. /**
  30451. * This offers the main features of a material in BJS.
  30452. */
  30453. var Material = /** @class */ (function () {
  30454. /**
  30455. * Creates a material instance.
  30456. * @param name - The name of the material.
  30457. * @param scene - The BJS scene to reference.
  30458. * @param doNotAdd - Specifies if the material should be added to the scene.
  30459. */
  30460. function Material(name, scene, doNotAdd) {
  30461. /**
  30462. * Specifies if the ready state should be checked on each call.
  30463. */
  30464. this.checkReadyOnEveryCall = false;
  30465. /**
  30466. * Specifies if the ready state should be checked once.
  30467. */
  30468. this.checkReadyOnlyOnce = false;
  30469. /**
  30470. * The state of the material.
  30471. */
  30472. this.state = "";
  30473. /**
  30474. * The alpha value of the material.
  30475. */
  30476. this._alpha = 1.0;
  30477. /**
  30478. * Specifies if back face culling is enabled.
  30479. */
  30480. this._backFaceCulling = true;
  30481. /**
  30482. * Specifies if the material should be serialized.
  30483. */
  30484. this.doNotSerialize = false;
  30485. /**
  30486. * Specifies if the effect should be stored on sub meshes.
  30487. */
  30488. this.storeEffectOnSubMeshes = false;
  30489. /**
  30490. * An event triggered when the material is disposed.
  30491. * @type {BABYLON.Observable}
  30492. */
  30493. this.onDisposeObservable = new BABYLON.Observable();
  30494. /**
  30495. * An event triggered when the material is bound.
  30496. * @type {BABYLON.Observable}
  30497. */
  30498. this.onBindObservable = new BABYLON.Observable();
  30499. /**
  30500. * An event triggered when the material is unbound.
  30501. * @type {BABYLON.Observable}
  30502. */
  30503. this.onUnBindObservable = new BABYLON.Observable();
  30504. /**
  30505. * Stores the value of the alpha mode.
  30506. */
  30507. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30508. /**
  30509. * Stores the state of the need depth pre-pass value.
  30510. */
  30511. this._needDepthPrePass = false;
  30512. /**
  30513. * Specifies if depth writing should be disabled.
  30514. */
  30515. this.disableDepthWrite = false;
  30516. /**
  30517. * Specifies if depth writing should be forced.
  30518. */
  30519. this.forceDepthWrite = false;
  30520. /**
  30521. * Specifies if there should be a separate pass for culling.
  30522. */
  30523. this.separateCullingPass = false;
  30524. /**
  30525. * Stores the state specifing if fog should be enabled.
  30526. */
  30527. this._fogEnabled = true;
  30528. /**
  30529. * Stores the size of points.
  30530. */
  30531. this.pointSize = 1.0;
  30532. /**
  30533. * Stores the z offset value.
  30534. */
  30535. this.zOffset = 0;
  30536. /**
  30537. * Specifies if the material was previously ready.
  30538. */
  30539. this._wasPreviouslyReady = false;
  30540. /**
  30541. * Stores the fill mode state.
  30542. */
  30543. this._fillMode = Material.TriangleFillMode;
  30544. this.name = name;
  30545. this.id = name || BABYLON.Tools.RandomId();
  30546. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30547. if (this._scene.useRightHandedSystem) {
  30548. this.sideOrientation = Material.ClockWiseSideOrientation;
  30549. }
  30550. else {
  30551. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30552. }
  30553. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30554. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30555. if (!doNotAdd) {
  30556. this._scene.materials.push(this);
  30557. }
  30558. }
  30559. Object.defineProperty(Material, "TriangleFillMode", {
  30560. /**
  30561. * Returns the triangle fill mode.
  30562. */
  30563. get: function () {
  30564. return Material._TriangleFillMode;
  30565. },
  30566. enumerable: true,
  30567. configurable: true
  30568. });
  30569. Object.defineProperty(Material, "WireFrameFillMode", {
  30570. /**
  30571. * Returns the wireframe mode.
  30572. */
  30573. get: function () {
  30574. return Material._WireFrameFillMode;
  30575. },
  30576. enumerable: true,
  30577. configurable: true
  30578. });
  30579. Object.defineProperty(Material, "PointFillMode", {
  30580. /**
  30581. * Returns the point fill mode.
  30582. */
  30583. get: function () {
  30584. return Material._PointFillMode;
  30585. },
  30586. enumerable: true,
  30587. configurable: true
  30588. });
  30589. Object.defineProperty(Material, "PointListDrawMode", {
  30590. /**
  30591. * Returns the point list draw mode.
  30592. */
  30593. get: function () {
  30594. return Material._PointListDrawMode;
  30595. },
  30596. enumerable: true,
  30597. configurable: true
  30598. });
  30599. Object.defineProperty(Material, "LineListDrawMode", {
  30600. /**
  30601. * Returns the line list draw mode.
  30602. */
  30603. get: function () {
  30604. return Material._LineListDrawMode;
  30605. },
  30606. enumerable: true,
  30607. configurable: true
  30608. });
  30609. Object.defineProperty(Material, "LineLoopDrawMode", {
  30610. /**
  30611. * Returns the line loop draw mode.
  30612. */
  30613. get: function () {
  30614. return Material._LineLoopDrawMode;
  30615. },
  30616. enumerable: true,
  30617. configurable: true
  30618. });
  30619. Object.defineProperty(Material, "LineStripDrawMode", {
  30620. /**
  30621. * Returns the line strip draw mode.
  30622. */
  30623. get: function () {
  30624. return Material._LineStripDrawMode;
  30625. },
  30626. enumerable: true,
  30627. configurable: true
  30628. });
  30629. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30630. /**
  30631. * Returns the triangle strip draw mode.
  30632. */
  30633. get: function () {
  30634. return Material._TriangleStripDrawMode;
  30635. },
  30636. enumerable: true,
  30637. configurable: true
  30638. });
  30639. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30640. /**
  30641. * Returns the triangle fan draw mode.
  30642. */
  30643. get: function () {
  30644. return Material._TriangleFanDrawMode;
  30645. },
  30646. enumerable: true,
  30647. configurable: true
  30648. });
  30649. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30650. /**
  30651. * Returns the clock-wise side orientation.
  30652. */
  30653. get: function () {
  30654. return Material._ClockWiseSideOrientation;
  30655. },
  30656. enumerable: true,
  30657. configurable: true
  30658. });
  30659. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30660. /**
  30661. * Returns the counter clock-wise side orientation.
  30662. */
  30663. get: function () {
  30664. return Material._CounterClockWiseSideOrientation;
  30665. },
  30666. enumerable: true,
  30667. configurable: true
  30668. });
  30669. Object.defineProperty(Material, "TextureDirtyFlag", {
  30670. /**
  30671. * Returns the dirty texture flag value.
  30672. */
  30673. get: function () {
  30674. return Material._TextureDirtyFlag;
  30675. },
  30676. enumerable: true,
  30677. configurable: true
  30678. });
  30679. Object.defineProperty(Material, "LightDirtyFlag", {
  30680. /**
  30681. * Returns the dirty light flag value.
  30682. */
  30683. get: function () {
  30684. return Material._LightDirtyFlag;
  30685. },
  30686. enumerable: true,
  30687. configurable: true
  30688. });
  30689. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30690. /**
  30691. * Returns the dirty fresnel flag value.
  30692. */
  30693. get: function () {
  30694. return Material._FresnelDirtyFlag;
  30695. },
  30696. enumerable: true,
  30697. configurable: true
  30698. });
  30699. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30700. /**
  30701. * Returns the dirty attributes flag value.
  30702. */
  30703. get: function () {
  30704. return Material._AttributesDirtyFlag;
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Object.defineProperty(Material, "MiscDirtyFlag", {
  30710. /**
  30711. * Returns the dirty misc flag value.
  30712. */
  30713. get: function () {
  30714. return Material._MiscDirtyFlag;
  30715. },
  30716. enumerable: true,
  30717. configurable: true
  30718. });
  30719. Object.defineProperty(Material.prototype, "alpha", {
  30720. /**
  30721. * Gets the alpha value of the material.
  30722. */
  30723. get: function () {
  30724. return this._alpha;
  30725. },
  30726. /**
  30727. * Sets the alpha value of the material.
  30728. */
  30729. set: function (value) {
  30730. if (this._alpha === value) {
  30731. return;
  30732. }
  30733. this._alpha = value;
  30734. this.markAsDirty(Material.MiscDirtyFlag);
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30740. /**
  30741. * Gets the back-face culling state.
  30742. */
  30743. get: function () {
  30744. return this._backFaceCulling;
  30745. },
  30746. /**
  30747. * Sets the back-face culling state.
  30748. */
  30749. set: function (value) {
  30750. if (this._backFaceCulling === value) {
  30751. return;
  30752. }
  30753. this._backFaceCulling = value;
  30754. this.markAsDirty(Material.TextureDirtyFlag);
  30755. },
  30756. enumerable: true,
  30757. configurable: true
  30758. });
  30759. Object.defineProperty(Material.prototype, "onDispose", {
  30760. /**
  30761. * Called during a dispose event.
  30762. */
  30763. set: function (callback) {
  30764. if (this._onDisposeObserver) {
  30765. this.onDisposeObservable.remove(this._onDisposeObserver);
  30766. }
  30767. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30768. },
  30769. enumerable: true,
  30770. configurable: true
  30771. });
  30772. Object.defineProperty(Material.prototype, "onBind", {
  30773. /**
  30774. * Called during a bind event.
  30775. */
  30776. set: function (callback) {
  30777. if (this._onBindObserver) {
  30778. this.onBindObservable.remove(this._onBindObserver);
  30779. }
  30780. this._onBindObserver = this.onBindObservable.add(callback);
  30781. },
  30782. enumerable: true,
  30783. configurable: true
  30784. });
  30785. Object.defineProperty(Material.prototype, "alphaMode", {
  30786. /**
  30787. * Gets the value of the alpha mode.
  30788. */
  30789. get: function () {
  30790. return this._alphaMode;
  30791. },
  30792. /**
  30793. * Sets the value of the alpha mode.
  30794. */
  30795. set: function (value) {
  30796. if (this._alphaMode === value) {
  30797. return;
  30798. }
  30799. this._alphaMode = value;
  30800. this.markAsDirty(Material.TextureDirtyFlag);
  30801. },
  30802. enumerable: true,
  30803. configurable: true
  30804. });
  30805. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30806. /**
  30807. * Gets the depth pre-pass value.
  30808. */
  30809. get: function () {
  30810. return this._needDepthPrePass;
  30811. },
  30812. /**
  30813. * Sets the need depth pre-pass value.
  30814. */
  30815. set: function (value) {
  30816. if (this._needDepthPrePass === value) {
  30817. return;
  30818. }
  30819. this._needDepthPrePass = value;
  30820. if (this._needDepthPrePass) {
  30821. this.checkReadyOnEveryCall = true;
  30822. }
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. Object.defineProperty(Material.prototype, "fogEnabled", {
  30828. /**
  30829. * Gets the value of the fog enabled state.
  30830. */
  30831. get: function () {
  30832. return this._fogEnabled;
  30833. },
  30834. /**
  30835. * Sets the state for enabling fog.
  30836. */
  30837. set: function (value) {
  30838. if (this._fogEnabled === value) {
  30839. return;
  30840. }
  30841. this._fogEnabled = value;
  30842. this.markAsDirty(Material.MiscDirtyFlag);
  30843. },
  30844. enumerable: true,
  30845. configurable: true
  30846. });
  30847. Object.defineProperty(Material.prototype, "wireframe", {
  30848. /**
  30849. * Gets a value specifying if wireframe mode is enabled.
  30850. */
  30851. get: function () {
  30852. return this._fillMode === Material.WireFrameFillMode;
  30853. },
  30854. /**
  30855. * Sets the state of wireframe mode.
  30856. */
  30857. set: function (value) {
  30858. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30859. },
  30860. enumerable: true,
  30861. configurable: true
  30862. });
  30863. Object.defineProperty(Material.prototype, "pointsCloud", {
  30864. /**
  30865. * Gets the value specifying if point clouds are enabled.
  30866. */
  30867. get: function () {
  30868. return this._fillMode === Material.PointFillMode;
  30869. },
  30870. /**
  30871. * Sets the state of point cloud mode.
  30872. */
  30873. set: function (value) {
  30874. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30875. },
  30876. enumerable: true,
  30877. configurable: true
  30878. });
  30879. Object.defineProperty(Material.prototype, "fillMode", {
  30880. /**
  30881. * Gets the material fill mode.
  30882. */
  30883. get: function () {
  30884. return this._fillMode;
  30885. },
  30886. /**
  30887. * Sets the material fill mode.
  30888. */
  30889. set: function (value) {
  30890. if (this._fillMode === value) {
  30891. return;
  30892. }
  30893. this._fillMode = value;
  30894. this.markAsDirty(Material.MiscDirtyFlag);
  30895. },
  30896. enumerable: true,
  30897. configurable: true
  30898. });
  30899. /**
  30900. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30901. * subclasses should override adding information pertainent to themselves.
  30902. * @returns - String with material information.
  30903. */
  30904. Material.prototype.toString = function (fullDetails) {
  30905. var ret = "Name: " + this.name;
  30906. if (fullDetails) {
  30907. }
  30908. return ret;
  30909. };
  30910. /**
  30911. * Gets the class name of the material.
  30912. * @returns - String with the class name of the material.
  30913. */
  30914. Material.prototype.getClassName = function () {
  30915. return "Material";
  30916. };
  30917. Object.defineProperty(Material.prototype, "isFrozen", {
  30918. /**
  30919. * Specifies if updates for the material been locked.
  30920. */
  30921. get: function () {
  30922. return this.checkReadyOnlyOnce;
  30923. },
  30924. enumerable: true,
  30925. configurable: true
  30926. });
  30927. /**
  30928. * Locks updates for the material.
  30929. */
  30930. Material.prototype.freeze = function () {
  30931. this.checkReadyOnlyOnce = true;
  30932. };
  30933. /**
  30934. * Unlocks updates for the material.
  30935. */
  30936. Material.prototype.unfreeze = function () {
  30937. this.checkReadyOnlyOnce = false;
  30938. };
  30939. /**
  30940. * Specifies if the material is ready to be used.
  30941. * @param mesh - BJS mesh.
  30942. * @param useInstances - Specifies if instances should be used.
  30943. * @returns - Boolean indicating if the material is ready to be used.
  30944. */
  30945. Material.prototype.isReady = function (mesh, useInstances) {
  30946. return true;
  30947. };
  30948. /**
  30949. * Specifies that the submesh is ready to be used.
  30950. * @param mesh - BJS mesh.
  30951. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30952. * @param useInstances - Specifies that instances should be used.
  30953. * @returns - boolean indicating that the submesh is ready or not.
  30954. */
  30955. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30956. return false;
  30957. };
  30958. /**
  30959. * Returns the material effect.
  30960. * @returns - Nullable material effect.
  30961. */
  30962. Material.prototype.getEffect = function () {
  30963. return this._effect;
  30964. };
  30965. /**
  30966. * Returns the BJS scene.
  30967. * @returns - BJS Scene.
  30968. */
  30969. Material.prototype.getScene = function () {
  30970. return this._scene;
  30971. };
  30972. /**
  30973. * Specifies if the material will require alpha blending
  30974. * @returns - Boolean specifying if alpha blending is needed.
  30975. */
  30976. Material.prototype.needAlphaBlending = function () {
  30977. return (this.alpha < 1.0);
  30978. };
  30979. /**
  30980. * Specifies if the mesh will require alpha blending.
  30981. * @param mesh - BJS mesh.
  30982. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30983. */
  30984. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30985. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30986. };
  30987. /**
  30988. * Specifies if this material should be rendered in alpha test mode.
  30989. * @returns - Boolean specifying if an alpha test is needed.
  30990. */
  30991. Material.prototype.needAlphaTesting = function () {
  30992. return false;
  30993. };
  30994. /**
  30995. * Gets the texture used for the alpha test.
  30996. * @returns - Nullable alpha test texture.
  30997. */
  30998. Material.prototype.getAlphaTestTexture = function () {
  30999. return null;
  31000. };
  31001. /**
  31002. * Marks the material to indicate that it needs to be re-calculated.
  31003. */
  31004. Material.prototype.markDirty = function () {
  31005. this._wasPreviouslyReady = false;
  31006. };
  31007. Material.prototype._preBind = function (effect, overrideOrientation) {
  31008. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31009. var engine = this._scene.getEngine();
  31010. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31011. var reverse = orientation === Material.ClockWiseSideOrientation;
  31012. engine.enableEffect(effect ? effect : this._effect);
  31013. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31014. return reverse;
  31015. };
  31016. /**
  31017. * Binds the material to the mesh.
  31018. * @param world - World transformation matrix.
  31019. * @param mesh - Mesh to bind the material to.
  31020. */
  31021. Material.prototype.bind = function (world, mesh) {
  31022. };
  31023. /**
  31024. * Binds the submesh to the material.
  31025. * @param world - World transformation matrix.
  31026. * @param mesh - Mesh containing the submesh.
  31027. * @param subMesh - Submesh to bind the material to.
  31028. */
  31029. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31030. };
  31031. /**
  31032. * Binds the world matrix to the material.
  31033. * @param world - World transformation matrix.
  31034. */
  31035. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31036. };
  31037. /**
  31038. * Binds the scene's uniform buffer to the effect.
  31039. * @param effect - Effect to bind to the scene uniform buffer.
  31040. * @param sceneUbo - Scene uniform buffer.
  31041. */
  31042. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31043. sceneUbo.bindToEffect(effect, "Scene");
  31044. };
  31045. /**
  31046. * Binds the view matrix to the effect.
  31047. * @param effect - Effect to bind the view matrix to.
  31048. */
  31049. Material.prototype.bindView = function (effect) {
  31050. if (!this._useUBO) {
  31051. effect.setMatrix("view", this.getScene().getViewMatrix());
  31052. }
  31053. else {
  31054. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31055. }
  31056. };
  31057. /**
  31058. * Binds the view projection matrix to the effect.
  31059. * @param effect - Effect to bind the view projection matrix to.
  31060. */
  31061. Material.prototype.bindViewProjection = function (effect) {
  31062. if (!this._useUBO) {
  31063. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31064. }
  31065. else {
  31066. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31067. }
  31068. };
  31069. /**
  31070. * Specifies if material alpha testing should be turned on for the mesh.
  31071. * @param mesh - BJS mesh.
  31072. */
  31073. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31074. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31075. };
  31076. /**
  31077. * Processes to execute after binding the material to a mesh.
  31078. * @param mesh - BJS mesh.
  31079. */
  31080. Material.prototype._afterBind = function (mesh) {
  31081. this._scene._cachedMaterial = this;
  31082. if (mesh) {
  31083. this._scene._cachedVisibility = mesh.visibility;
  31084. }
  31085. else {
  31086. this._scene._cachedVisibility = 1;
  31087. }
  31088. if (mesh) {
  31089. this.onBindObservable.notifyObservers(mesh);
  31090. }
  31091. if (this.disableDepthWrite) {
  31092. var engine = this._scene.getEngine();
  31093. this._cachedDepthWriteState = engine.getDepthWrite();
  31094. engine.setDepthWrite(false);
  31095. }
  31096. };
  31097. /**
  31098. * Unbinds the material from the mesh.
  31099. */
  31100. Material.prototype.unbind = function () {
  31101. this.onUnBindObservable.notifyObservers(this);
  31102. if (this.disableDepthWrite) {
  31103. var engine = this._scene.getEngine();
  31104. engine.setDepthWrite(this._cachedDepthWriteState);
  31105. }
  31106. };
  31107. /**
  31108. * Gets the active textures from the material.
  31109. * @returns - Array of textures.
  31110. */
  31111. Material.prototype.getActiveTextures = function () {
  31112. return [];
  31113. };
  31114. /**
  31115. * Specifies if the material uses a texture.
  31116. * @param texture - Texture to check against the material.
  31117. * @returns - Boolean specifying if the material uses the texture.
  31118. */
  31119. Material.prototype.hasTexture = function (texture) {
  31120. return false;
  31121. };
  31122. /**
  31123. * Makes a duplicate of the material, and gives it a new name.
  31124. * @param name - Name to call the duplicated material.
  31125. * @returns - Nullable cloned material
  31126. */
  31127. Material.prototype.clone = function (name) {
  31128. return null;
  31129. };
  31130. /**
  31131. * Gets the meshes bound to the material.
  31132. * @returns - Array of meshes bound to the material.
  31133. */
  31134. Material.prototype.getBindedMeshes = function () {
  31135. var result = new Array();
  31136. for (var index = 0; index < this._scene.meshes.length; index++) {
  31137. var mesh = this._scene.meshes[index];
  31138. if (mesh.material === this) {
  31139. result.push(mesh);
  31140. }
  31141. }
  31142. return result;
  31143. };
  31144. /**
  31145. * Force shader compilation
  31146. * @param mesh - BJS mesh.
  31147. * @param onCompiled - function to execute once the material is compiled.
  31148. * @param options - options to pass to this function.
  31149. */
  31150. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31151. var _this = this;
  31152. var localOptions = __assign({ clipPlane: false }, options);
  31153. var subMesh = new BABYLON.BaseSubMesh();
  31154. var scene = this.getScene();
  31155. var checkReady = function () {
  31156. if (!_this._scene || !_this._scene.getEngine()) {
  31157. return;
  31158. }
  31159. if (subMesh._materialDefines) {
  31160. subMesh._materialDefines._renderId = -1;
  31161. }
  31162. var clipPlaneState = scene.clipPlane;
  31163. if (localOptions.clipPlane) {
  31164. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31165. }
  31166. if (_this.storeEffectOnSubMeshes) {
  31167. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31168. if (onCompiled) {
  31169. onCompiled(_this);
  31170. }
  31171. }
  31172. else {
  31173. setTimeout(checkReady, 16);
  31174. }
  31175. }
  31176. else {
  31177. if (_this.isReady(mesh)) {
  31178. if (onCompiled) {
  31179. onCompiled(_this);
  31180. }
  31181. }
  31182. else {
  31183. setTimeout(checkReady, 16);
  31184. }
  31185. }
  31186. if (localOptions.clipPlane) {
  31187. scene.clipPlane = clipPlaneState;
  31188. }
  31189. };
  31190. checkReady();
  31191. };
  31192. /**
  31193. * Force shader compilation.
  31194. * @param mesh The mesh that will use this material
  31195. * @param options Additional options for compiling the shaders
  31196. * @returns A promise that resolves when the compilation completes
  31197. */
  31198. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31199. var _this = this;
  31200. return new Promise(function (resolve) {
  31201. _this.forceCompilation(mesh, function () {
  31202. resolve();
  31203. }, options);
  31204. });
  31205. };
  31206. /**
  31207. * Marks a define in the material to indicate that it needs to be re-computed.
  31208. * @param flag - Material define flag.
  31209. */
  31210. Material.prototype.markAsDirty = function (flag) {
  31211. if (flag & Material.TextureDirtyFlag) {
  31212. this._markAllSubMeshesAsTexturesDirty();
  31213. }
  31214. if (flag & Material.LightDirtyFlag) {
  31215. this._markAllSubMeshesAsLightsDirty();
  31216. }
  31217. if (flag & Material.FresnelDirtyFlag) {
  31218. this._markAllSubMeshesAsFresnelDirty();
  31219. }
  31220. if (flag & Material.AttributesDirtyFlag) {
  31221. this._markAllSubMeshesAsAttributesDirty();
  31222. }
  31223. if (flag & Material.MiscDirtyFlag) {
  31224. this._markAllSubMeshesAsMiscDirty();
  31225. }
  31226. this.getScene().resetCachedMaterial();
  31227. };
  31228. /**
  31229. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31230. * @param func - function which checks material defines against the submeshes.
  31231. */
  31232. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31233. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31234. var mesh = _a[_i];
  31235. if (!mesh.subMeshes) {
  31236. continue;
  31237. }
  31238. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31239. var subMesh = _c[_b];
  31240. if (subMesh.getMaterial() !== this) {
  31241. continue;
  31242. }
  31243. if (!subMesh._materialDefines) {
  31244. continue;
  31245. }
  31246. func(subMesh._materialDefines);
  31247. }
  31248. }
  31249. };
  31250. /**
  31251. * Indicates that image processing needs to be re-calculated for all submeshes.
  31252. */
  31253. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31254. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31255. };
  31256. /**
  31257. * Indicates that textures need to be re-calculated for all submeshes.
  31258. */
  31259. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31260. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31261. };
  31262. /**
  31263. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31264. */
  31265. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31266. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31267. };
  31268. /**
  31269. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31270. */
  31271. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31272. this._markAllSubMeshesAsDirty(function (defines) {
  31273. defines.markAsFresnelDirty();
  31274. defines.markAsMiscDirty();
  31275. });
  31276. };
  31277. /**
  31278. * Indicates that lights need to be re-calculated for all submeshes.
  31279. */
  31280. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31281. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31282. };
  31283. /**
  31284. * Indicates that attributes need to be re-calculated for all submeshes.
  31285. */
  31286. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31287. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31288. };
  31289. /**
  31290. * Indicates that misc needs to be re-calculated for all submeshes.
  31291. */
  31292. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31293. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31294. };
  31295. /**
  31296. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31297. */
  31298. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31299. this._markAllSubMeshesAsDirty(function (defines) {
  31300. defines.markAsTexturesDirty();
  31301. defines.markAsMiscDirty();
  31302. });
  31303. };
  31304. /**
  31305. * Disposes the material.
  31306. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31307. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31308. */
  31309. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31310. // Animations
  31311. this.getScene().stopAnimation(this);
  31312. // Remove from scene
  31313. var index = this._scene.materials.indexOf(this);
  31314. if (index >= 0) {
  31315. this._scene.materials.splice(index, 1);
  31316. }
  31317. // Remove from meshes
  31318. for (index = 0; index < this._scene.meshes.length; index++) {
  31319. var mesh = this._scene.meshes[index];
  31320. if (mesh.material === this) {
  31321. mesh.material = null;
  31322. if (mesh.geometry) {
  31323. var geometry = (mesh.geometry);
  31324. if (this.storeEffectOnSubMeshes) {
  31325. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31326. var subMesh = _a[_i];
  31327. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31328. if (forceDisposeEffect && subMesh._materialEffect) {
  31329. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31330. }
  31331. }
  31332. }
  31333. else {
  31334. geometry._releaseVertexArrayObject(this._effect);
  31335. }
  31336. }
  31337. }
  31338. }
  31339. this._uniformBuffer.dispose();
  31340. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31341. if (forceDisposeEffect && this._effect) {
  31342. if (!this.storeEffectOnSubMeshes) {
  31343. this._scene.getEngine()._releaseEffect(this._effect);
  31344. }
  31345. this._effect = null;
  31346. }
  31347. // Callback
  31348. this.onDisposeObservable.notifyObservers(this);
  31349. this.onDisposeObservable.clear();
  31350. this.onBindObservable.clear();
  31351. this.onUnBindObservable.clear();
  31352. };
  31353. /**
  31354. * Serializes this material.
  31355. * @returns - serialized material object.
  31356. */
  31357. Material.prototype.serialize = function () {
  31358. return BABYLON.SerializationHelper.Serialize(this);
  31359. };
  31360. /**
  31361. * Creates a MultiMaterial from parse MultiMaterial data.
  31362. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31363. * @param scene - BJS scene.
  31364. * @returns - MultiMaterial.
  31365. */
  31366. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31367. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31368. multiMaterial.id = parsedMultiMaterial.id;
  31369. if (BABYLON.Tags) {
  31370. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31371. }
  31372. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31373. var subMatId = parsedMultiMaterial.materials[matIndex];
  31374. if (subMatId) {
  31375. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31376. }
  31377. else {
  31378. multiMaterial.subMaterials.push(null);
  31379. }
  31380. }
  31381. return multiMaterial;
  31382. };
  31383. /**
  31384. * Creates a material from parsed material data.
  31385. * @param parsedMaterial - Parsed material data.
  31386. * @param scene - BJS scene.
  31387. * @param rootUrl - Root URL containing the material information.
  31388. * @returns - Parsed material.
  31389. */
  31390. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31391. if (!parsedMaterial.customType) {
  31392. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31393. }
  31394. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31395. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31396. if (!BABYLON.LegacyPBRMaterial) {
  31397. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31398. return;
  31399. }
  31400. }
  31401. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31402. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31403. ;
  31404. };
  31405. // Triangle views
  31406. Material._TriangleFillMode = 0;
  31407. Material._WireFrameFillMode = 1;
  31408. Material._PointFillMode = 2;
  31409. // Draw modes
  31410. Material._PointListDrawMode = 3;
  31411. Material._LineListDrawMode = 4;
  31412. Material._LineLoopDrawMode = 5;
  31413. Material._LineStripDrawMode = 6;
  31414. Material._TriangleStripDrawMode = 7;
  31415. Material._TriangleFanDrawMode = 8;
  31416. /**
  31417. * Stores the clock-wise side orientation.
  31418. */
  31419. Material._ClockWiseSideOrientation = 0;
  31420. /**
  31421. * Stores the counter clock-wise side orientation.
  31422. */
  31423. Material._CounterClockWiseSideOrientation = 1;
  31424. /**
  31425. * The dirty texture flag value.
  31426. */
  31427. Material._TextureDirtyFlag = 1;
  31428. /**
  31429. * The dirty light flag value.
  31430. */
  31431. Material._LightDirtyFlag = 2;
  31432. /**
  31433. * The dirty fresnel flag value.
  31434. */
  31435. Material._FresnelDirtyFlag = 4;
  31436. /**
  31437. * The dirty attribute flag value.
  31438. */
  31439. Material._AttributesDirtyFlag = 8;
  31440. /**
  31441. * The dirty misc flag value.
  31442. */
  31443. Material._MiscDirtyFlag = 16;
  31444. __decorate([
  31445. BABYLON.serialize()
  31446. ], Material.prototype, "id", void 0);
  31447. __decorate([
  31448. BABYLON.serialize()
  31449. ], Material.prototype, "name", void 0);
  31450. __decorate([
  31451. BABYLON.serialize()
  31452. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31453. __decorate([
  31454. BABYLON.serialize()
  31455. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31456. __decorate([
  31457. BABYLON.serialize()
  31458. ], Material.prototype, "state", void 0);
  31459. __decorate([
  31460. BABYLON.serialize("alpha")
  31461. ], Material.prototype, "_alpha", void 0);
  31462. __decorate([
  31463. BABYLON.serialize("backFaceCulling")
  31464. ], Material.prototype, "_backFaceCulling", void 0);
  31465. __decorate([
  31466. BABYLON.serialize()
  31467. ], Material.prototype, "sideOrientation", void 0);
  31468. __decorate([
  31469. BABYLON.serialize("alphaMode")
  31470. ], Material.prototype, "_alphaMode", void 0);
  31471. __decorate([
  31472. BABYLON.serialize()
  31473. ], Material.prototype, "_needDepthPrePass", void 0);
  31474. __decorate([
  31475. BABYLON.serialize()
  31476. ], Material.prototype, "disableDepthWrite", void 0);
  31477. __decorate([
  31478. BABYLON.serialize()
  31479. ], Material.prototype, "forceDepthWrite", void 0);
  31480. __decorate([
  31481. BABYLON.serialize()
  31482. ], Material.prototype, "separateCullingPass", void 0);
  31483. __decorate([
  31484. BABYLON.serialize("fogEnabled")
  31485. ], Material.prototype, "_fogEnabled", void 0);
  31486. __decorate([
  31487. BABYLON.serialize()
  31488. ], Material.prototype, "pointSize", void 0);
  31489. __decorate([
  31490. BABYLON.serialize()
  31491. ], Material.prototype, "zOffset", void 0);
  31492. __decorate([
  31493. BABYLON.serialize()
  31494. ], Material.prototype, "wireframe", null);
  31495. __decorate([
  31496. BABYLON.serialize()
  31497. ], Material.prototype, "pointsCloud", null);
  31498. __decorate([
  31499. BABYLON.serialize()
  31500. ], Material.prototype, "fillMode", null);
  31501. return Material;
  31502. }());
  31503. BABYLON.Material = Material;
  31504. })(BABYLON || (BABYLON = {}));
  31505. //# sourceMappingURL=babylon.material.js.map
  31506. var BABYLON;
  31507. (function (BABYLON) {
  31508. var UniformBuffer = /** @class */ (function () {
  31509. /**
  31510. * Uniform buffer objects.
  31511. *
  31512. * Handles blocks of uniform on the GPU.
  31513. *
  31514. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31515. *
  31516. * For more information, please refer to :
  31517. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31518. */
  31519. function UniformBuffer(engine, data, dynamic) {
  31520. this._engine = engine;
  31521. this._noUBO = !engine.supportsUniformBuffers;
  31522. this._dynamic = dynamic;
  31523. this._data = data || [];
  31524. this._uniformLocations = {};
  31525. this._uniformSizes = {};
  31526. this._uniformLocationPointer = 0;
  31527. this._needSync = false;
  31528. if (this._noUBO) {
  31529. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31530. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31531. this.updateFloat = this._updateFloatForEffect;
  31532. this.updateFloat2 = this._updateFloat2ForEffect;
  31533. this.updateFloat3 = this._updateFloat3ForEffect;
  31534. this.updateFloat4 = this._updateFloat4ForEffect;
  31535. this.updateMatrix = this._updateMatrixForEffect;
  31536. this.updateVector3 = this._updateVector3ForEffect;
  31537. this.updateVector4 = this._updateVector4ForEffect;
  31538. this.updateColor3 = this._updateColor3ForEffect;
  31539. this.updateColor4 = this._updateColor4ForEffect;
  31540. }
  31541. else {
  31542. this._engine._uniformBuffers.push(this);
  31543. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31544. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31545. this.updateFloat = this._updateFloatForUniform;
  31546. this.updateFloat2 = this._updateFloat2ForUniform;
  31547. this.updateFloat3 = this._updateFloat3ForUniform;
  31548. this.updateFloat4 = this._updateFloat4ForUniform;
  31549. this.updateMatrix = this._updateMatrixForUniform;
  31550. this.updateVector3 = this._updateVector3ForUniform;
  31551. this.updateVector4 = this._updateVector4ForUniform;
  31552. this.updateColor3 = this._updateColor3ForUniform;
  31553. this.updateColor4 = this._updateColor4ForUniform;
  31554. }
  31555. }
  31556. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31557. // Properties
  31558. /**
  31559. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31560. * or just falling back on setUniformXXX calls.
  31561. */
  31562. get: function () {
  31563. return !this._noUBO;
  31564. },
  31565. enumerable: true,
  31566. configurable: true
  31567. });
  31568. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31569. /**
  31570. * Indicates if the WebGL underlying uniform buffer is in sync
  31571. * with the javascript cache data.
  31572. */
  31573. get: function () {
  31574. return !this._needSync;
  31575. },
  31576. enumerable: true,
  31577. configurable: true
  31578. });
  31579. /**
  31580. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31581. * Also, a dynamic UniformBuffer will disable cache verification and always
  31582. * update the underlying WebGL uniform buffer to the GPU.
  31583. */
  31584. UniformBuffer.prototype.isDynamic = function () {
  31585. return this._dynamic !== undefined;
  31586. };
  31587. /**
  31588. * The data cache on JS side.
  31589. */
  31590. UniformBuffer.prototype.getData = function () {
  31591. return this._bufferData;
  31592. };
  31593. /**
  31594. * The underlying WebGL Uniform buffer.
  31595. */
  31596. UniformBuffer.prototype.getBuffer = function () {
  31597. return this._buffer;
  31598. };
  31599. /**
  31600. * std140 layout specifies how to align data within an UBO structure.
  31601. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31602. * for specs.
  31603. */
  31604. UniformBuffer.prototype._fillAlignment = function (size) {
  31605. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31606. // and 4x4 matrices
  31607. // TODO : change if other types are used
  31608. var alignment;
  31609. if (size <= 2) {
  31610. alignment = size;
  31611. }
  31612. else {
  31613. alignment = 4;
  31614. }
  31615. if ((this._uniformLocationPointer % alignment) !== 0) {
  31616. var oldPointer = this._uniformLocationPointer;
  31617. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31618. var diff = this._uniformLocationPointer - oldPointer;
  31619. for (var i = 0; i < diff; i++) {
  31620. this._data.push(0);
  31621. }
  31622. }
  31623. };
  31624. /**
  31625. * Adds an uniform in the buffer.
  31626. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31627. * for the layout to be correct !
  31628. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31629. * @param {number|number[]} size Data size, or data directly.
  31630. */
  31631. UniformBuffer.prototype.addUniform = function (name, size) {
  31632. if (this._noUBO) {
  31633. return;
  31634. }
  31635. if (this._uniformLocations[name] !== undefined) {
  31636. // Already existing uniform
  31637. return;
  31638. }
  31639. // This function must be called in the order of the shader layout !
  31640. // size can be the size of the uniform, or data directly
  31641. var data;
  31642. if (size instanceof Array) {
  31643. data = size;
  31644. size = data.length;
  31645. }
  31646. else {
  31647. size = size;
  31648. data = [];
  31649. // Fill with zeros
  31650. for (var i = 0; i < size; i++) {
  31651. data.push(0);
  31652. }
  31653. }
  31654. this._fillAlignment(size);
  31655. this._uniformSizes[name] = size;
  31656. this._uniformLocations[name] = this._uniformLocationPointer;
  31657. this._uniformLocationPointer += size;
  31658. for (var i = 0; i < size; i++) {
  31659. this._data.push(data[i]);
  31660. }
  31661. this._needSync = true;
  31662. };
  31663. /**
  31664. * Wrapper for addUniform.
  31665. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31666. * @param {Matrix} mat A 4x4 matrix.
  31667. */
  31668. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31669. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31670. };
  31671. /**
  31672. * Wrapper for addUniform.
  31673. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31674. * @param {number} x
  31675. * @param {number} y
  31676. */
  31677. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31678. var temp = [x, y];
  31679. this.addUniform(name, temp);
  31680. };
  31681. /**
  31682. * Wrapper for addUniform.
  31683. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31684. * @param {number} x
  31685. * @param {number} y
  31686. * @param {number} z
  31687. */
  31688. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31689. var temp = [x, y, z];
  31690. this.addUniform(name, temp);
  31691. };
  31692. /**
  31693. * Wrapper for addUniform.
  31694. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31695. * @param {Color3} color
  31696. */
  31697. UniformBuffer.prototype.addColor3 = function (name, color) {
  31698. var temp = new Array();
  31699. color.toArray(temp);
  31700. this.addUniform(name, temp);
  31701. };
  31702. /**
  31703. * Wrapper for addUniform.
  31704. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31705. * @param {Color3} color
  31706. * @param {number} alpha
  31707. */
  31708. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31709. var temp = new Array();
  31710. color.toArray(temp);
  31711. temp.push(alpha);
  31712. this.addUniform(name, temp);
  31713. };
  31714. /**
  31715. * Wrapper for addUniform.
  31716. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31717. * @param {Vector3} vector
  31718. */
  31719. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31720. var temp = new Array();
  31721. vector.toArray(temp);
  31722. this.addUniform(name, temp);
  31723. };
  31724. /**
  31725. * Wrapper for addUniform.
  31726. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31727. */
  31728. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31729. this.addUniform(name, 12);
  31730. };
  31731. /**
  31732. * Wrapper for addUniform.
  31733. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31734. */
  31735. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31736. this.addUniform(name, 8);
  31737. };
  31738. /**
  31739. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31740. */
  31741. UniformBuffer.prototype.create = function () {
  31742. if (this._noUBO) {
  31743. return;
  31744. }
  31745. if (this._buffer) {
  31746. return; // nothing to do
  31747. }
  31748. // See spec, alignment must be filled as a vec4
  31749. this._fillAlignment(4);
  31750. this._bufferData = new Float32Array(this._data);
  31751. this._rebuild();
  31752. this._needSync = true;
  31753. };
  31754. UniformBuffer.prototype._rebuild = function () {
  31755. if (this._noUBO) {
  31756. return;
  31757. }
  31758. if (this._dynamic) {
  31759. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31760. }
  31761. else {
  31762. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31763. }
  31764. };
  31765. /**
  31766. * Updates the WebGL Uniform Buffer on the GPU.
  31767. * If the `dynamic` flag is set to true, no cache comparison is done.
  31768. * Otherwise, the buffer will be updated only if the cache differs.
  31769. */
  31770. UniformBuffer.prototype.update = function () {
  31771. if (!this._buffer) {
  31772. this.create();
  31773. return;
  31774. }
  31775. if (!this._dynamic && !this._needSync) {
  31776. return;
  31777. }
  31778. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31779. this._needSync = false;
  31780. };
  31781. /**
  31782. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31783. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31784. * @param {number[]|Float32Array} data Flattened data
  31785. * @param {number} size Size of the data.
  31786. */
  31787. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31788. var location = this._uniformLocations[uniformName];
  31789. if (location === undefined) {
  31790. if (this._buffer) {
  31791. // Cannot add an uniform if the buffer is already created
  31792. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31793. return;
  31794. }
  31795. this.addUniform(uniformName, size);
  31796. location = this._uniformLocations[uniformName];
  31797. }
  31798. if (!this._buffer) {
  31799. this.create();
  31800. }
  31801. if (!this._dynamic) {
  31802. // Cache for static uniform buffers
  31803. var changed = false;
  31804. for (var i = 0; i < size; i++) {
  31805. if (this._bufferData[location + i] !== data[i]) {
  31806. changed = true;
  31807. this._bufferData[location + i] = data[i];
  31808. }
  31809. }
  31810. this._needSync = this._needSync || changed;
  31811. }
  31812. else {
  31813. // No cache for dynamic
  31814. for (var i = 0; i < size; i++) {
  31815. this._bufferData[location + i] = data[i];
  31816. }
  31817. }
  31818. };
  31819. // Update methods
  31820. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31821. // To match std140, matrix must be realigned
  31822. for (var i = 0; i < 3; i++) {
  31823. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31824. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31825. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31826. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31827. }
  31828. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31829. };
  31830. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31831. this._currentEffect.setMatrix3x3(name, matrix);
  31832. };
  31833. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31834. this._currentEffect.setMatrix2x2(name, matrix);
  31835. };
  31836. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31837. // To match std140, matrix must be realigned
  31838. for (var i = 0; i < 2; i++) {
  31839. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31840. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31841. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31842. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31843. }
  31844. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31845. };
  31846. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31847. this._currentEffect.setFloat(name, x);
  31848. };
  31849. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31850. UniformBuffer._tempBuffer[0] = x;
  31851. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31852. };
  31853. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31854. if (suffix === void 0) { suffix = ""; }
  31855. this._currentEffect.setFloat2(name + suffix, x, y);
  31856. };
  31857. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31858. if (suffix === void 0) { suffix = ""; }
  31859. UniformBuffer._tempBuffer[0] = x;
  31860. UniformBuffer._tempBuffer[1] = y;
  31861. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31862. };
  31863. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31864. if (suffix === void 0) { suffix = ""; }
  31865. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31866. };
  31867. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31868. if (suffix === void 0) { suffix = ""; }
  31869. UniformBuffer._tempBuffer[0] = x;
  31870. UniformBuffer._tempBuffer[1] = y;
  31871. UniformBuffer._tempBuffer[2] = z;
  31872. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31873. };
  31874. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31875. if (suffix === void 0) { suffix = ""; }
  31876. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31877. };
  31878. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31879. if (suffix === void 0) { suffix = ""; }
  31880. UniformBuffer._tempBuffer[0] = x;
  31881. UniformBuffer._tempBuffer[1] = y;
  31882. UniformBuffer._tempBuffer[2] = z;
  31883. UniformBuffer._tempBuffer[3] = w;
  31884. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31885. };
  31886. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31887. this._currentEffect.setMatrix(name, mat);
  31888. };
  31889. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31890. this.updateUniform(name, mat.toArray(), 16);
  31891. };
  31892. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31893. this._currentEffect.setVector3(name, vector);
  31894. };
  31895. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31896. vector.toArray(UniformBuffer._tempBuffer);
  31897. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31898. };
  31899. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31900. this._currentEffect.setVector4(name, vector);
  31901. };
  31902. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31903. vector.toArray(UniformBuffer._tempBuffer);
  31904. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31905. };
  31906. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31907. if (suffix === void 0) { suffix = ""; }
  31908. this._currentEffect.setColor3(name + suffix, color);
  31909. };
  31910. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31911. if (suffix === void 0) { suffix = ""; }
  31912. color.toArray(UniformBuffer._tempBuffer);
  31913. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31914. };
  31915. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31916. if (suffix === void 0) { suffix = ""; }
  31917. this._currentEffect.setColor4(name + suffix, color, alpha);
  31918. };
  31919. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31920. if (suffix === void 0) { suffix = ""; }
  31921. color.toArray(UniformBuffer._tempBuffer);
  31922. UniformBuffer._tempBuffer[3] = alpha;
  31923. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31924. };
  31925. /**
  31926. * Sets a sampler uniform on the effect.
  31927. * @param {string} name Name of the sampler.
  31928. * @param {Texture} texture
  31929. */
  31930. UniformBuffer.prototype.setTexture = function (name, texture) {
  31931. this._currentEffect.setTexture(name, texture);
  31932. };
  31933. /**
  31934. * Directly updates the value of the uniform in the cache AND on the GPU.
  31935. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31936. * @param {number[]|Float32Array} data Flattened data
  31937. */
  31938. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31939. this.updateUniform(uniformName, data, data.length);
  31940. this.update();
  31941. };
  31942. /**
  31943. * Binds this uniform buffer to an effect.
  31944. * @param {Effect} effect
  31945. * @param {string} name Name of the uniform block in the shader.
  31946. */
  31947. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31948. this._currentEffect = effect;
  31949. if (this._noUBO || !this._buffer) {
  31950. return;
  31951. }
  31952. effect.bindUniformBuffer(this._buffer, name);
  31953. };
  31954. /**
  31955. * Disposes the uniform buffer.
  31956. */
  31957. UniformBuffer.prototype.dispose = function () {
  31958. if (this._noUBO) {
  31959. return;
  31960. }
  31961. var index = this._engine._uniformBuffers.indexOf(this);
  31962. if (index !== -1) {
  31963. this._engine._uniformBuffers.splice(index, 1);
  31964. }
  31965. if (!this._buffer) {
  31966. return;
  31967. }
  31968. if (this._engine._releaseBuffer(this._buffer)) {
  31969. this._buffer = null;
  31970. }
  31971. };
  31972. // Pool for avoiding memory leaks
  31973. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31974. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31975. return UniformBuffer;
  31976. }());
  31977. BABYLON.UniformBuffer = UniformBuffer;
  31978. })(BABYLON || (BABYLON = {}));
  31979. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31980. var BABYLON;
  31981. (function (BABYLON) {
  31982. var VertexData = /** @class */ (function () {
  31983. function VertexData() {
  31984. }
  31985. VertexData.prototype.set = function (data, kind) {
  31986. switch (kind) {
  31987. case BABYLON.VertexBuffer.PositionKind:
  31988. this.positions = data;
  31989. break;
  31990. case BABYLON.VertexBuffer.NormalKind:
  31991. this.normals = data;
  31992. break;
  31993. case BABYLON.VertexBuffer.TangentKind:
  31994. this.tangents = data;
  31995. break;
  31996. case BABYLON.VertexBuffer.UVKind:
  31997. this.uvs = data;
  31998. break;
  31999. case BABYLON.VertexBuffer.UV2Kind:
  32000. this.uvs2 = data;
  32001. break;
  32002. case BABYLON.VertexBuffer.UV3Kind:
  32003. this.uvs3 = data;
  32004. break;
  32005. case BABYLON.VertexBuffer.UV4Kind:
  32006. this.uvs4 = data;
  32007. break;
  32008. case BABYLON.VertexBuffer.UV5Kind:
  32009. this.uvs5 = data;
  32010. break;
  32011. case BABYLON.VertexBuffer.UV6Kind:
  32012. this.uvs6 = data;
  32013. break;
  32014. case BABYLON.VertexBuffer.ColorKind:
  32015. this.colors = data;
  32016. break;
  32017. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32018. this.matricesIndices = data;
  32019. break;
  32020. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32021. this.matricesWeights = data;
  32022. break;
  32023. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32024. this.matricesIndicesExtra = data;
  32025. break;
  32026. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32027. this.matricesWeightsExtra = data;
  32028. break;
  32029. }
  32030. };
  32031. /**
  32032. * Associates the vertexData to the passed Mesh.
  32033. * Sets it as updatable or not (default `false`).
  32034. * Returns the VertexData.
  32035. */
  32036. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32037. this._applyTo(mesh, updatable);
  32038. return this;
  32039. };
  32040. /**
  32041. * Associates the vertexData to the passed Geometry.
  32042. * Sets it as updatable or not (default `false`).
  32043. * Returns the VertexData.
  32044. */
  32045. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32046. this._applyTo(geometry, updatable);
  32047. return this;
  32048. };
  32049. /**
  32050. * Updates the associated mesh.
  32051. * Returns the VertexData.
  32052. */
  32053. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32054. this._update(mesh);
  32055. return this;
  32056. };
  32057. /**
  32058. * Updates the associated geometry.
  32059. * Returns the VertexData.
  32060. */
  32061. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32062. this._update(geometry);
  32063. return this;
  32064. };
  32065. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32066. if (updatable === void 0) { updatable = false; }
  32067. if (this.positions) {
  32068. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32069. }
  32070. if (this.normals) {
  32071. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32072. }
  32073. if (this.tangents) {
  32074. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32075. }
  32076. if (this.uvs) {
  32077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32078. }
  32079. if (this.uvs2) {
  32080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32081. }
  32082. if (this.uvs3) {
  32083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32084. }
  32085. if (this.uvs4) {
  32086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32087. }
  32088. if (this.uvs5) {
  32089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32090. }
  32091. if (this.uvs6) {
  32092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32093. }
  32094. if (this.colors) {
  32095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32096. }
  32097. if (this.matricesIndices) {
  32098. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32099. }
  32100. if (this.matricesWeights) {
  32101. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32102. }
  32103. if (this.matricesIndicesExtra) {
  32104. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32105. }
  32106. if (this.matricesWeightsExtra) {
  32107. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32108. }
  32109. if (this.indices) {
  32110. meshOrGeometry.setIndices(this.indices, null, updatable);
  32111. }
  32112. return this;
  32113. };
  32114. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32115. if (this.positions) {
  32116. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32117. }
  32118. if (this.normals) {
  32119. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32120. }
  32121. if (this.tangents) {
  32122. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32123. }
  32124. if (this.uvs) {
  32125. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32126. }
  32127. if (this.uvs2) {
  32128. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32129. }
  32130. if (this.uvs3) {
  32131. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32132. }
  32133. if (this.uvs4) {
  32134. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32135. }
  32136. if (this.uvs5) {
  32137. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32138. }
  32139. if (this.uvs6) {
  32140. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32141. }
  32142. if (this.colors) {
  32143. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32144. }
  32145. if (this.matricesIndices) {
  32146. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32147. }
  32148. if (this.matricesWeights) {
  32149. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32150. }
  32151. if (this.matricesIndicesExtra) {
  32152. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32153. }
  32154. if (this.matricesWeightsExtra) {
  32155. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32156. }
  32157. if (this.indices) {
  32158. meshOrGeometry.setIndices(this.indices, null);
  32159. }
  32160. return this;
  32161. };
  32162. /**
  32163. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32164. * Returns the VertexData.
  32165. */
  32166. VertexData.prototype.transform = function (matrix) {
  32167. var transformed = BABYLON.Vector3.Zero();
  32168. var index;
  32169. if (this.positions) {
  32170. var position = BABYLON.Vector3.Zero();
  32171. for (index = 0; index < this.positions.length; index += 3) {
  32172. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32173. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32174. this.positions[index] = transformed.x;
  32175. this.positions[index + 1] = transformed.y;
  32176. this.positions[index + 2] = transformed.z;
  32177. }
  32178. }
  32179. if (this.normals) {
  32180. var normal = BABYLON.Vector3.Zero();
  32181. for (index = 0; index < this.normals.length; index += 3) {
  32182. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32183. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32184. this.normals[index] = transformed.x;
  32185. this.normals[index + 1] = transformed.y;
  32186. this.normals[index + 2] = transformed.z;
  32187. }
  32188. }
  32189. if (this.tangents) {
  32190. var tangent = BABYLON.Vector4.Zero();
  32191. var tangentTransformed = BABYLON.Vector4.Zero();
  32192. for (index = 0; index < this.tangents.length; index += 4) {
  32193. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32194. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32195. this.tangents[index] = tangentTransformed.x;
  32196. this.tangents[index + 1] = tangentTransformed.y;
  32197. this.tangents[index + 2] = tangentTransformed.z;
  32198. this.tangents[index + 3] = tangentTransformed.w;
  32199. }
  32200. }
  32201. return this;
  32202. };
  32203. /**
  32204. * Merges the passed VertexData into the current one.
  32205. * Returns the modified VertexData.
  32206. */
  32207. VertexData.prototype.merge = function (other) {
  32208. this._validate();
  32209. other._validate();
  32210. if (!this.normals !== !other.normals ||
  32211. !this.tangents !== !other.tangents ||
  32212. !this.uvs !== !other.uvs ||
  32213. !this.uvs2 !== !other.uvs2 ||
  32214. !this.uvs3 !== !other.uvs3 ||
  32215. !this.uvs4 !== !other.uvs4 ||
  32216. !this.uvs5 !== !other.uvs5 ||
  32217. !this.uvs6 !== !other.uvs6 ||
  32218. !this.colors !== !other.colors ||
  32219. !this.matricesIndices !== !other.matricesIndices ||
  32220. !this.matricesWeights !== !other.matricesWeights ||
  32221. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32222. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32223. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32224. }
  32225. if (other.indices) {
  32226. if (!this.indices) {
  32227. this.indices = [];
  32228. }
  32229. var offset = this.positions ? this.positions.length / 3 : 0;
  32230. for (var index = 0; index < other.indices.length; index++) {
  32231. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32232. this.indices.push(other.indices[index] + offset);
  32233. }
  32234. }
  32235. this.positions = this._mergeElement(this.positions, other.positions);
  32236. this.normals = this._mergeElement(this.normals, other.normals);
  32237. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32238. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32239. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32240. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32241. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32242. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32243. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32244. this.colors = this._mergeElement(this.colors, other.colors);
  32245. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32246. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32247. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32248. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32249. return this;
  32250. };
  32251. VertexData.prototype._mergeElement = function (source, other) {
  32252. if (!source) {
  32253. return other;
  32254. }
  32255. if (!other) {
  32256. return source;
  32257. }
  32258. var len = other.length + source.length;
  32259. var isSrcTypedArray = source instanceof Float32Array;
  32260. var isOthTypedArray = other instanceof Float32Array;
  32261. // use non-loop method when the source is Float32Array
  32262. if (isSrcTypedArray) {
  32263. var ret32 = new Float32Array(len);
  32264. ret32.set(source);
  32265. ret32.set(other, source.length);
  32266. return ret32;
  32267. // source is number[], when other is also use concat
  32268. }
  32269. else if (!isOthTypedArray) {
  32270. return source.concat(other);
  32271. // source is a number[], but other is a Float32Array, loop required
  32272. }
  32273. else {
  32274. var ret = source.slice(0); // copy source to a separate array
  32275. for (var i = 0, len = other.length; i < len; i++) {
  32276. ret.push(other[i]);
  32277. }
  32278. return ret;
  32279. }
  32280. };
  32281. VertexData.prototype._validate = function () {
  32282. if (!this.positions) {
  32283. throw new Error("Positions are required");
  32284. }
  32285. var getElementCount = function (kind, values) {
  32286. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32287. if ((values.length % stride) !== 0) {
  32288. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32289. }
  32290. return values.length / stride;
  32291. };
  32292. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32293. var validateElementCount = function (kind, values) {
  32294. var elementCount = getElementCount(kind, values);
  32295. if (elementCount !== positionsElementCount) {
  32296. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32297. }
  32298. };
  32299. if (this.normals)
  32300. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32301. if (this.tangents)
  32302. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32303. if (this.uvs)
  32304. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32305. if (this.uvs2)
  32306. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32307. if (this.uvs3)
  32308. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32309. if (this.uvs4)
  32310. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32311. if (this.uvs5)
  32312. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32313. if (this.uvs6)
  32314. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32315. if (this.colors)
  32316. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32317. if (this.matricesIndices)
  32318. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32319. if (this.matricesWeights)
  32320. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32321. if (this.matricesIndicesExtra)
  32322. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32323. if (this.matricesWeightsExtra)
  32324. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32325. };
  32326. /**
  32327. * Serializes the VertexData.
  32328. * Returns a serialized object.
  32329. */
  32330. VertexData.prototype.serialize = function () {
  32331. var serializationObject = this.serialize();
  32332. if (this.positions) {
  32333. serializationObject.positions = this.positions;
  32334. }
  32335. if (this.normals) {
  32336. serializationObject.normals = this.normals;
  32337. }
  32338. if (this.tangents) {
  32339. serializationObject.tangents = this.tangents;
  32340. }
  32341. if (this.uvs) {
  32342. serializationObject.uvs = this.uvs;
  32343. }
  32344. if (this.uvs2) {
  32345. serializationObject.uvs2 = this.uvs2;
  32346. }
  32347. if (this.uvs3) {
  32348. serializationObject.uvs3 = this.uvs3;
  32349. }
  32350. if (this.uvs4) {
  32351. serializationObject.uvs4 = this.uvs4;
  32352. }
  32353. if (this.uvs5) {
  32354. serializationObject.uvs5 = this.uvs5;
  32355. }
  32356. if (this.uvs6) {
  32357. serializationObject.uvs6 = this.uvs6;
  32358. }
  32359. if (this.colors) {
  32360. serializationObject.colors = this.colors;
  32361. }
  32362. if (this.matricesIndices) {
  32363. serializationObject.matricesIndices = this.matricesIndices;
  32364. serializationObject.matricesIndices._isExpanded = true;
  32365. }
  32366. if (this.matricesWeights) {
  32367. serializationObject.matricesWeights = this.matricesWeights;
  32368. }
  32369. if (this.matricesIndicesExtra) {
  32370. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32371. serializationObject.matricesIndicesExtra._isExpanded = true;
  32372. }
  32373. if (this.matricesWeightsExtra) {
  32374. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32375. }
  32376. serializationObject.indices = this.indices;
  32377. return serializationObject;
  32378. };
  32379. // Statics
  32380. /**
  32381. * Returns the object VertexData associated to the passed mesh.
  32382. */
  32383. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32384. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32385. };
  32386. /**
  32387. * Returns the object VertexData associated to the passed geometry.
  32388. */
  32389. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32390. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32391. };
  32392. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32393. var result = new VertexData();
  32394. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32395. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32396. }
  32397. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32398. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32399. }
  32400. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32401. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32402. }
  32403. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32404. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32405. }
  32406. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32407. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32408. }
  32409. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32410. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32411. }
  32412. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32413. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32414. }
  32415. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32416. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32417. }
  32418. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32419. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32420. }
  32421. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32422. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32423. }
  32424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32425. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32426. }
  32427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32428. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32429. }
  32430. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32431. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32432. }
  32433. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32434. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32435. }
  32436. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32437. return result;
  32438. };
  32439. /**
  32440. * Creates the vertexData of the Ribbon.
  32441. */
  32442. VertexData.CreateRibbon = function (options) {
  32443. var pathArray = options.pathArray;
  32444. var closeArray = options.closeArray || false;
  32445. var closePath = options.closePath || false;
  32446. var invertUV = options.invertUV || false;
  32447. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32448. var offset = options.offset || defaultOffset;
  32449. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32450. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32451. var customUV = options.uvs;
  32452. var customColors = options.colors;
  32453. var positions = [];
  32454. var indices = [];
  32455. var normals = [];
  32456. var uvs = [];
  32457. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32458. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32459. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32460. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32461. var minlg; // minimal length among all paths from pathArray
  32462. var lg = []; // array of path lengths : nb of vertex per path
  32463. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32464. var p; // path iterator
  32465. var i; // point iterator
  32466. var j; // point iterator
  32467. // if single path in pathArray
  32468. if (pathArray.length < 2) {
  32469. var ar1 = [];
  32470. var ar2 = [];
  32471. for (i = 0; i < pathArray[0].length - offset; i++) {
  32472. ar1.push(pathArray[0][i]);
  32473. ar2.push(pathArray[0][i + offset]);
  32474. }
  32475. pathArray = [ar1, ar2];
  32476. }
  32477. // positions and horizontal distances (u)
  32478. var idc = 0;
  32479. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32480. var path;
  32481. var l;
  32482. minlg = pathArray[0].length;
  32483. var vectlg;
  32484. var dist;
  32485. for (p = 0; p < pathArray.length; p++) {
  32486. uTotalDistance[p] = 0;
  32487. us[p] = [0];
  32488. path = pathArray[p];
  32489. l = path.length;
  32490. minlg = (minlg < l) ? minlg : l;
  32491. j = 0;
  32492. while (j < l) {
  32493. positions.push(path[j].x, path[j].y, path[j].z);
  32494. if (j > 0) {
  32495. vectlg = path[j].subtract(path[j - 1]).length();
  32496. dist = vectlg + uTotalDistance[p];
  32497. us[p].push(dist);
  32498. uTotalDistance[p] = dist;
  32499. }
  32500. j++;
  32501. }
  32502. if (closePath) {
  32503. j--;
  32504. positions.push(path[0].x, path[0].y, path[0].z);
  32505. vectlg = path[j].subtract(path[0]).length();
  32506. dist = vectlg + uTotalDistance[p];
  32507. us[p].push(dist);
  32508. uTotalDistance[p] = dist;
  32509. }
  32510. lg[p] = l + closePathCorr;
  32511. idx[p] = idc;
  32512. idc += (l + closePathCorr);
  32513. }
  32514. // vertical distances (v)
  32515. var path1;
  32516. var path2;
  32517. var vertex1 = null;
  32518. var vertex2 = null;
  32519. for (i = 0; i < minlg + closePathCorr; i++) {
  32520. vTotalDistance[i] = 0;
  32521. vs[i] = [0];
  32522. for (p = 0; p < pathArray.length - 1; p++) {
  32523. path1 = pathArray[p];
  32524. path2 = pathArray[p + 1];
  32525. if (i === minlg) {
  32526. vertex1 = path1[0];
  32527. vertex2 = path2[0];
  32528. }
  32529. else {
  32530. vertex1 = path1[i];
  32531. vertex2 = path2[i];
  32532. }
  32533. vectlg = vertex2.subtract(vertex1).length();
  32534. dist = vectlg + vTotalDistance[i];
  32535. vs[i].push(dist);
  32536. vTotalDistance[i] = dist;
  32537. }
  32538. if (closeArray && vertex2 && vertex1) {
  32539. path1 = pathArray[p];
  32540. path2 = pathArray[0];
  32541. if (i === minlg) {
  32542. vertex2 = path2[0];
  32543. }
  32544. vectlg = vertex2.subtract(vertex1).length();
  32545. dist = vectlg + vTotalDistance[i];
  32546. vTotalDistance[i] = dist;
  32547. }
  32548. }
  32549. // uvs
  32550. var u;
  32551. var v;
  32552. if (customUV) {
  32553. for (p = 0; p < customUV.length; p++) {
  32554. uvs.push(customUV[p].x, customUV[p].y);
  32555. }
  32556. }
  32557. else {
  32558. for (p = 0; p < pathArray.length; p++) {
  32559. for (i = 0; i < minlg + closePathCorr; i++) {
  32560. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32561. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32562. if (invertUV) {
  32563. uvs.push(v, u);
  32564. }
  32565. else {
  32566. uvs.push(u, v);
  32567. }
  32568. }
  32569. }
  32570. }
  32571. // indices
  32572. p = 0; // path index
  32573. var pi = 0; // positions array index
  32574. var l1 = lg[p] - 1; // path1 length
  32575. var l2 = lg[p + 1] - 1; // path2 length
  32576. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32577. var shft = idx[1] - idx[0]; // shift
  32578. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32579. while (pi <= min && p < path1nb) {
  32580. // 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
  32581. indices.push(pi, pi + shft, pi + 1);
  32582. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32583. pi += 1;
  32584. if (pi === min) {
  32585. p++;
  32586. if (p === lg.length - 1) {
  32587. shft = idx[0] - idx[p];
  32588. l1 = lg[p] - 1;
  32589. l2 = lg[0] - 1;
  32590. }
  32591. else {
  32592. shft = idx[p + 1] - idx[p];
  32593. l1 = lg[p] - 1;
  32594. l2 = lg[p + 1] - 1;
  32595. }
  32596. pi = idx[p];
  32597. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32598. }
  32599. }
  32600. // normals
  32601. VertexData.ComputeNormals(positions, indices, normals);
  32602. if (closePath) {
  32603. var indexFirst = 0;
  32604. var indexLast = 0;
  32605. for (p = 0; p < pathArray.length; p++) {
  32606. indexFirst = idx[p] * 3;
  32607. if (p + 1 < pathArray.length) {
  32608. indexLast = (idx[p + 1] - 1) * 3;
  32609. }
  32610. else {
  32611. indexLast = normals.length - 3;
  32612. }
  32613. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32614. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32615. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32616. normals[indexLast] = normals[indexFirst];
  32617. normals[indexLast + 1] = normals[indexFirst + 1];
  32618. normals[indexLast + 2] = normals[indexFirst + 2];
  32619. }
  32620. }
  32621. // sides
  32622. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32623. // Colors
  32624. var colors = null;
  32625. if (customColors) {
  32626. colors = new Float32Array(customColors.length * 4);
  32627. for (var c = 0; c < customColors.length; c++) {
  32628. colors[c * 4] = customColors[c].r;
  32629. colors[c * 4 + 1] = customColors[c].g;
  32630. colors[c * 4 + 2] = customColors[c].b;
  32631. colors[c * 4 + 3] = customColors[c].a;
  32632. }
  32633. }
  32634. // Result
  32635. var vertexData = new VertexData();
  32636. var positions32 = new Float32Array(positions);
  32637. var normals32 = new Float32Array(normals);
  32638. var uvs32 = new Float32Array(uvs);
  32639. vertexData.indices = indices;
  32640. vertexData.positions = positions32;
  32641. vertexData.normals = normals32;
  32642. vertexData.uvs = uvs32;
  32643. if (colors) {
  32644. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32645. }
  32646. if (closePath) {
  32647. vertexData._idx = idx;
  32648. }
  32649. return vertexData;
  32650. };
  32651. /**
  32652. * Creates the VertexData of the Box.
  32653. */
  32654. VertexData.CreateBox = function (options) {
  32655. var normalsSource = [
  32656. new BABYLON.Vector3(0, 0, 1),
  32657. new BABYLON.Vector3(0, 0, -1),
  32658. new BABYLON.Vector3(1, 0, 0),
  32659. new BABYLON.Vector3(-1, 0, 0),
  32660. new BABYLON.Vector3(0, 1, 0),
  32661. new BABYLON.Vector3(0, -1, 0)
  32662. ];
  32663. var indices = [];
  32664. var positions = [];
  32665. var normals = [];
  32666. var uvs = [];
  32667. var width = options.width || options.size || 1;
  32668. var height = options.height || options.size || 1;
  32669. var depth = options.depth || options.size || 1;
  32670. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32671. var faceUV = options.faceUV || new Array(6);
  32672. var faceColors = options.faceColors;
  32673. var colors = [];
  32674. // default face colors and UV if undefined
  32675. for (var f = 0; f < 6; f++) {
  32676. if (faceUV[f] === undefined) {
  32677. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32678. }
  32679. if (faceColors && faceColors[f] === undefined) {
  32680. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32681. }
  32682. }
  32683. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32684. // Create each face in turn.
  32685. for (var index = 0; index < normalsSource.length; index++) {
  32686. var normal = normalsSource[index];
  32687. // Get two vectors perpendicular to the face normal and to each other.
  32688. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32689. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32690. // Six indices (two triangles) per face.
  32691. var verticesLength = positions.length / 3;
  32692. indices.push(verticesLength);
  32693. indices.push(verticesLength + 1);
  32694. indices.push(verticesLength + 2);
  32695. indices.push(verticesLength);
  32696. indices.push(verticesLength + 2);
  32697. indices.push(verticesLength + 3);
  32698. // Four vertices per face.
  32699. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32700. positions.push(vertex.x, vertex.y, vertex.z);
  32701. normals.push(normal.x, normal.y, normal.z);
  32702. uvs.push(faceUV[index].z, faceUV[index].w);
  32703. if (faceColors) {
  32704. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32705. }
  32706. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32707. positions.push(vertex.x, vertex.y, vertex.z);
  32708. normals.push(normal.x, normal.y, normal.z);
  32709. uvs.push(faceUV[index].x, faceUV[index].w);
  32710. if (faceColors) {
  32711. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32712. }
  32713. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32714. positions.push(vertex.x, vertex.y, vertex.z);
  32715. normals.push(normal.x, normal.y, normal.z);
  32716. uvs.push(faceUV[index].x, faceUV[index].y);
  32717. if (faceColors) {
  32718. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32719. }
  32720. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32721. positions.push(vertex.x, vertex.y, vertex.z);
  32722. normals.push(normal.x, normal.y, normal.z);
  32723. uvs.push(faceUV[index].z, faceUV[index].y);
  32724. if (faceColors) {
  32725. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32726. }
  32727. }
  32728. // sides
  32729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32730. // Result
  32731. var vertexData = new VertexData();
  32732. vertexData.indices = indices;
  32733. vertexData.positions = positions;
  32734. vertexData.normals = normals;
  32735. vertexData.uvs = uvs;
  32736. if (faceColors) {
  32737. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32738. vertexData.colors = totalColors;
  32739. }
  32740. return vertexData;
  32741. };
  32742. /**
  32743. * Creates the VertexData of the Sphere.
  32744. */
  32745. VertexData.CreateSphere = function (options) {
  32746. var segments = options.segments || 32;
  32747. var diameterX = options.diameterX || options.diameter || 1;
  32748. var diameterY = options.diameterY || options.diameter || 1;
  32749. var diameterZ = options.diameterZ || options.diameter || 1;
  32750. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32751. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32752. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32753. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32754. var totalZRotationSteps = 2 + segments;
  32755. var totalYRotationSteps = 2 * totalZRotationSteps;
  32756. var indices = [];
  32757. var positions = [];
  32758. var normals = [];
  32759. var uvs = [];
  32760. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32761. var normalizedZ = zRotationStep / totalZRotationSteps;
  32762. var angleZ = normalizedZ * Math.PI * slice;
  32763. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32764. var normalizedY = yRotationStep / totalYRotationSteps;
  32765. var angleY = normalizedY * Math.PI * 2 * arc;
  32766. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32767. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32768. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32769. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32770. var vertex = complete.multiply(radius);
  32771. var normal = complete.divide(radius).normalize();
  32772. positions.push(vertex.x, vertex.y, vertex.z);
  32773. normals.push(normal.x, normal.y, normal.z);
  32774. uvs.push(normalizedY, normalizedZ);
  32775. }
  32776. if (zRotationStep > 0) {
  32777. var verticesCount = positions.length / 3;
  32778. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32779. indices.push((firstIndex));
  32780. indices.push((firstIndex + 1));
  32781. indices.push(firstIndex + totalYRotationSteps + 1);
  32782. indices.push((firstIndex + totalYRotationSteps + 1));
  32783. indices.push((firstIndex + 1));
  32784. indices.push((firstIndex + totalYRotationSteps + 2));
  32785. }
  32786. }
  32787. }
  32788. // Sides
  32789. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32790. // Result
  32791. var vertexData = new VertexData();
  32792. vertexData.indices = indices;
  32793. vertexData.positions = positions;
  32794. vertexData.normals = normals;
  32795. vertexData.uvs = uvs;
  32796. return vertexData;
  32797. };
  32798. /**
  32799. * Creates the VertexData of the Cylinder or Cone.
  32800. */
  32801. VertexData.CreateCylinder = function (options) {
  32802. var height = options.height || 2;
  32803. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32804. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32805. var tessellation = options.tessellation || 24;
  32806. var subdivisions = options.subdivisions || 1;
  32807. var hasRings = options.hasRings ? true : false;
  32808. var enclose = options.enclose ? true : false;
  32809. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32810. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32811. var faceUV = options.faceUV || new Array(3);
  32812. var faceColors = options.faceColors;
  32813. // default face colors and UV if undefined
  32814. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32815. var ringNb = (hasRings) ? subdivisions : 1;
  32816. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32817. var f;
  32818. for (f = 0; f < surfaceNb; f++) {
  32819. if (faceColors && faceColors[f] === undefined) {
  32820. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32821. }
  32822. }
  32823. for (f = 0; f < surfaceNb; f++) {
  32824. if (faceUV && faceUV[f] === undefined) {
  32825. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32826. }
  32827. }
  32828. var indices = new Array();
  32829. var positions = new Array();
  32830. var normals = new Array();
  32831. var uvs = new Array();
  32832. var colors = new Array();
  32833. var angle_step = Math.PI * 2 * arc / tessellation;
  32834. var angle;
  32835. var h;
  32836. var radius;
  32837. var tan = (diameterBottom - diameterTop) / 2 / height;
  32838. var ringVertex = BABYLON.Vector3.Zero();
  32839. var ringNormal = BABYLON.Vector3.Zero();
  32840. var ringFirstVertex = BABYLON.Vector3.Zero();
  32841. var ringFirstNormal = BABYLON.Vector3.Zero();
  32842. var quadNormal = BABYLON.Vector3.Zero();
  32843. var Y = BABYLON.Axis.Y;
  32844. // positions, normals, uvs
  32845. var i;
  32846. var j;
  32847. var r;
  32848. var ringIdx = 1;
  32849. var s = 1; // surface index
  32850. var cs = 0;
  32851. var v = 0;
  32852. for (i = 0; i <= subdivisions; i++) {
  32853. h = i / subdivisions;
  32854. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32855. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32856. for (r = 0; r < ringIdx; r++) {
  32857. if (hasRings) {
  32858. s += r;
  32859. }
  32860. if (enclose) {
  32861. s += 2 * r;
  32862. }
  32863. for (j = 0; j <= tessellation; j++) {
  32864. angle = j * angle_step;
  32865. // position
  32866. ringVertex.x = Math.cos(-angle) * radius;
  32867. ringVertex.y = -height / 2 + h * height;
  32868. ringVertex.z = Math.sin(-angle) * radius;
  32869. // normal
  32870. if (diameterTop === 0 && i === subdivisions) {
  32871. // if no top cap, reuse former normals
  32872. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32873. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32874. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32875. }
  32876. else {
  32877. ringNormal.x = ringVertex.x;
  32878. ringNormal.z = ringVertex.z;
  32879. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32880. ringNormal.normalize();
  32881. }
  32882. // keep first ring vertex values for enclose
  32883. if (j === 0) {
  32884. ringFirstVertex.copyFrom(ringVertex);
  32885. ringFirstNormal.copyFrom(ringNormal);
  32886. }
  32887. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32888. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32889. if (hasRings) {
  32890. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32891. }
  32892. else {
  32893. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32894. }
  32895. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32896. if (faceColors) {
  32897. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32898. }
  32899. }
  32900. // if enclose, add four vertices and their dedicated normals
  32901. if (arc !== 1 && enclose) {
  32902. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32903. positions.push(0, ringVertex.y, 0);
  32904. positions.push(0, ringVertex.y, 0);
  32905. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32906. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32907. quadNormal.normalize();
  32908. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32909. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32910. quadNormal.normalize();
  32911. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32912. if (hasRings) {
  32913. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32914. }
  32915. else {
  32916. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32917. }
  32918. uvs.push(faceUV[s + 1].x, v);
  32919. uvs.push(faceUV[s + 1].z, v);
  32920. if (hasRings) {
  32921. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32922. }
  32923. else {
  32924. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32925. }
  32926. uvs.push(faceUV[s + 2].x, v);
  32927. uvs.push(faceUV[s + 2].z, v);
  32928. if (faceColors) {
  32929. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32930. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32931. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32932. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32933. }
  32934. }
  32935. if (cs !== s) {
  32936. cs = s;
  32937. }
  32938. }
  32939. }
  32940. // indices
  32941. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32942. var s;
  32943. i = 0;
  32944. for (s = 0; s < subdivisions; s++) {
  32945. var i0 = 0;
  32946. var i1 = 0;
  32947. var i2 = 0;
  32948. var i3 = 0;
  32949. for (j = 0; j < tessellation; j++) {
  32950. i0 = i * (e + 1) + j;
  32951. i1 = (i + 1) * (e + 1) + j;
  32952. i2 = i * (e + 1) + (j + 1);
  32953. i3 = (i + 1) * (e + 1) + (j + 1);
  32954. indices.push(i0, i1, i2);
  32955. indices.push(i3, i2, i1);
  32956. }
  32957. if (arc !== 1 && enclose) {
  32958. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32959. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32960. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32961. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32962. }
  32963. i = (hasRings) ? (i + 2) : (i + 1);
  32964. }
  32965. // Caps
  32966. var createCylinderCap = function (isTop) {
  32967. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32968. if (radius === 0) {
  32969. return;
  32970. }
  32971. // Cap positions, normals & uvs
  32972. var angle;
  32973. var circleVector;
  32974. var i;
  32975. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32976. var c = null;
  32977. if (faceColors) {
  32978. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32979. }
  32980. // cap center
  32981. var vbase = positions.length / 3;
  32982. var offset = isTop ? height / 2 : -height / 2;
  32983. var center = new BABYLON.Vector3(0, offset, 0);
  32984. positions.push(center.x, center.y, center.z);
  32985. normals.push(0, isTop ? 1 : -1, 0);
  32986. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32987. if (c) {
  32988. colors.push(c.r, c.g, c.b, c.a);
  32989. }
  32990. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32991. for (i = 0; i <= tessellation; i++) {
  32992. angle = Math.PI * 2 * i * arc / tessellation;
  32993. var cos = Math.cos(-angle);
  32994. var sin = Math.sin(-angle);
  32995. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32996. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32997. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32998. normals.push(0, isTop ? 1 : -1, 0);
  32999. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33000. if (c) {
  33001. colors.push(c.r, c.g, c.b, c.a);
  33002. }
  33003. }
  33004. // Cap indices
  33005. for (i = 0; i < tessellation; i++) {
  33006. if (!isTop) {
  33007. indices.push(vbase);
  33008. indices.push(vbase + (i + 1));
  33009. indices.push(vbase + (i + 2));
  33010. }
  33011. else {
  33012. indices.push(vbase);
  33013. indices.push(vbase + (i + 2));
  33014. indices.push(vbase + (i + 1));
  33015. }
  33016. }
  33017. };
  33018. // add caps to geometry
  33019. createCylinderCap(false);
  33020. createCylinderCap(true);
  33021. // Sides
  33022. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33023. var vertexData = new VertexData();
  33024. vertexData.indices = indices;
  33025. vertexData.positions = positions;
  33026. vertexData.normals = normals;
  33027. vertexData.uvs = uvs;
  33028. if (faceColors) {
  33029. vertexData.colors = colors;
  33030. }
  33031. return vertexData;
  33032. };
  33033. /**
  33034. * Creates the VertexData of the Torus.
  33035. */
  33036. VertexData.CreateTorus = function (options) {
  33037. var indices = [];
  33038. var positions = [];
  33039. var normals = [];
  33040. var uvs = [];
  33041. var diameter = options.diameter || 1;
  33042. var thickness = options.thickness || 0.5;
  33043. var tessellation = options.tessellation || 16;
  33044. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33045. var stride = tessellation + 1;
  33046. for (var i = 0; i <= tessellation; i++) {
  33047. var u = i / tessellation;
  33048. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33049. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33050. for (var j = 0; j <= tessellation; j++) {
  33051. var v = 1 - j / tessellation;
  33052. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33053. var dx = Math.cos(innerAngle);
  33054. var dy = Math.sin(innerAngle);
  33055. // Create a vertex.
  33056. var normal = new BABYLON.Vector3(dx, dy, 0);
  33057. var position = normal.scale(thickness / 2);
  33058. var textureCoordinate = new BABYLON.Vector2(u, v);
  33059. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33060. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33061. positions.push(position.x, position.y, position.z);
  33062. normals.push(normal.x, normal.y, normal.z);
  33063. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33064. // And create indices for two triangles.
  33065. var nextI = (i + 1) % stride;
  33066. var nextJ = (j + 1) % stride;
  33067. indices.push(i * stride + j);
  33068. indices.push(i * stride + nextJ);
  33069. indices.push(nextI * stride + j);
  33070. indices.push(i * stride + nextJ);
  33071. indices.push(nextI * stride + nextJ);
  33072. indices.push(nextI * stride + j);
  33073. }
  33074. }
  33075. // Sides
  33076. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33077. // Result
  33078. var vertexData = new VertexData();
  33079. vertexData.indices = indices;
  33080. vertexData.positions = positions;
  33081. vertexData.normals = normals;
  33082. vertexData.uvs = uvs;
  33083. return vertexData;
  33084. };
  33085. /**
  33086. * Creates the VertexData of the LineSystem.
  33087. */
  33088. VertexData.CreateLineSystem = function (options) {
  33089. var indices = [];
  33090. var positions = [];
  33091. var lines = options.lines;
  33092. var colors = options.colors;
  33093. var vertexColors = [];
  33094. var idx = 0;
  33095. for (var l = 0; l < lines.length; l++) {
  33096. var points = lines[l];
  33097. for (var index = 0; index < points.length; index++) {
  33098. positions.push(points[index].x, points[index].y, points[index].z);
  33099. if (colors) {
  33100. var color = colors[l];
  33101. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33102. }
  33103. if (index > 0) {
  33104. indices.push(idx - 1);
  33105. indices.push(idx);
  33106. }
  33107. idx++;
  33108. }
  33109. }
  33110. var vertexData = new VertexData();
  33111. vertexData.indices = indices;
  33112. vertexData.positions = positions;
  33113. if (colors) {
  33114. vertexData.colors = vertexColors;
  33115. }
  33116. return vertexData;
  33117. };
  33118. /**
  33119. * Create the VertexData of the DashedLines.
  33120. */
  33121. VertexData.CreateDashedLines = function (options) {
  33122. var dashSize = options.dashSize || 3;
  33123. var gapSize = options.gapSize || 1;
  33124. var dashNb = options.dashNb || 200;
  33125. var points = options.points;
  33126. var positions = new Array();
  33127. var indices = new Array();
  33128. var curvect = BABYLON.Vector3.Zero();
  33129. var lg = 0;
  33130. var nb = 0;
  33131. var shft = 0;
  33132. var dashshft = 0;
  33133. var curshft = 0;
  33134. var idx = 0;
  33135. var i = 0;
  33136. for (i = 0; i < points.length - 1; i++) {
  33137. points[i + 1].subtractToRef(points[i], curvect);
  33138. lg += curvect.length();
  33139. }
  33140. shft = lg / dashNb;
  33141. dashshft = dashSize * shft / (dashSize + gapSize);
  33142. for (i = 0; i < points.length - 1; i++) {
  33143. points[i + 1].subtractToRef(points[i], curvect);
  33144. nb = Math.floor(curvect.length() / shft);
  33145. curvect.normalize();
  33146. for (var j = 0; j < nb; j++) {
  33147. curshft = shft * j;
  33148. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33149. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33150. indices.push(idx, idx + 1);
  33151. idx += 2;
  33152. }
  33153. }
  33154. // Result
  33155. var vertexData = new VertexData();
  33156. vertexData.positions = positions;
  33157. vertexData.indices = indices;
  33158. return vertexData;
  33159. };
  33160. /**
  33161. * Creates the VertexData of the Ground.
  33162. */
  33163. VertexData.CreateGround = function (options) {
  33164. var indices = [];
  33165. var positions = [];
  33166. var normals = [];
  33167. var uvs = [];
  33168. var row, col;
  33169. var width = options.width || 1;
  33170. var height = options.height || 1;
  33171. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33172. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33173. for (row = 0; row <= subdivisionsY; row++) {
  33174. for (col = 0; col <= subdivisionsX; col++) {
  33175. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33176. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33177. positions.push(position.x, position.y, position.z);
  33178. normals.push(normal.x, normal.y, normal.z);
  33179. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33180. }
  33181. }
  33182. for (row = 0; row < subdivisionsY; row++) {
  33183. for (col = 0; col < subdivisionsX; col++) {
  33184. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33185. indices.push(col + 1 + row * (subdivisionsX + 1));
  33186. indices.push(col + row * (subdivisionsX + 1));
  33187. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33188. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33189. indices.push(col + row * (subdivisionsX + 1));
  33190. }
  33191. }
  33192. // Result
  33193. var vertexData = new VertexData();
  33194. vertexData.indices = indices;
  33195. vertexData.positions = positions;
  33196. vertexData.normals = normals;
  33197. vertexData.uvs = uvs;
  33198. return vertexData;
  33199. };
  33200. /**
  33201. * Creates the VertexData of the TiledGround.
  33202. */
  33203. VertexData.CreateTiledGround = function (options) {
  33204. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33205. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33206. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33207. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33208. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33209. var precision = options.precision || { w: 1, h: 1 };
  33210. var indices = new Array();
  33211. var positions = new Array();
  33212. var normals = new Array();
  33213. var uvs = new Array();
  33214. var row, col, tileRow, tileCol;
  33215. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33216. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33217. precision.w = (precision.w < 1) ? 1 : precision.w;
  33218. precision.h = (precision.h < 1) ? 1 : precision.h;
  33219. var tileSize = {
  33220. 'w': (xmax - xmin) / subdivisions.w,
  33221. 'h': (zmax - zmin) / subdivisions.h
  33222. };
  33223. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33224. // Indices
  33225. var base = positions.length / 3;
  33226. var rowLength = precision.w + 1;
  33227. for (row = 0; row < precision.h; row++) {
  33228. for (col = 0; col < precision.w; col++) {
  33229. var square = [
  33230. base + col + row * rowLength,
  33231. base + (col + 1) + row * rowLength,
  33232. base + (col + 1) + (row + 1) * rowLength,
  33233. base + col + (row + 1) * rowLength
  33234. ];
  33235. indices.push(square[1]);
  33236. indices.push(square[2]);
  33237. indices.push(square[3]);
  33238. indices.push(square[0]);
  33239. indices.push(square[1]);
  33240. indices.push(square[3]);
  33241. }
  33242. }
  33243. // Position, normals and uvs
  33244. var position = BABYLON.Vector3.Zero();
  33245. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33246. for (row = 0; row <= precision.h; row++) {
  33247. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33248. for (col = 0; col <= precision.w; col++) {
  33249. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33250. position.y = 0;
  33251. positions.push(position.x, position.y, position.z);
  33252. normals.push(normal.x, normal.y, normal.z);
  33253. uvs.push(col / precision.w, row / precision.h);
  33254. }
  33255. }
  33256. }
  33257. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33258. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33259. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33260. }
  33261. }
  33262. // Result
  33263. var vertexData = new VertexData();
  33264. vertexData.indices = indices;
  33265. vertexData.positions = positions;
  33266. vertexData.normals = normals;
  33267. vertexData.uvs = uvs;
  33268. return vertexData;
  33269. };
  33270. /**
  33271. * Creates the VertexData of the Ground designed from a heightmap.
  33272. */
  33273. VertexData.CreateGroundFromHeightMap = function (options) {
  33274. var indices = [];
  33275. var positions = [];
  33276. var normals = [];
  33277. var uvs = [];
  33278. var row, col;
  33279. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33280. // Vertices
  33281. for (row = 0; row <= options.subdivisions; row++) {
  33282. for (col = 0; col <= options.subdivisions; col++) {
  33283. 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));
  33284. // Compute height
  33285. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33286. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33287. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33288. var r = options.buffer[pos] / 255.0;
  33289. var g = options.buffer[pos + 1] / 255.0;
  33290. var b = options.buffer[pos + 2] / 255.0;
  33291. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33292. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33293. // Add vertex
  33294. positions.push(position.x, position.y, position.z);
  33295. normals.push(0, 0, 0);
  33296. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33297. }
  33298. }
  33299. // Indices
  33300. for (row = 0; row < options.subdivisions; row++) {
  33301. for (col = 0; col < options.subdivisions; col++) {
  33302. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33303. indices.push(col + 1 + row * (options.subdivisions + 1));
  33304. indices.push(col + row * (options.subdivisions + 1));
  33305. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33306. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33307. indices.push(col + row * (options.subdivisions + 1));
  33308. }
  33309. }
  33310. // Normals
  33311. VertexData.ComputeNormals(positions, indices, normals);
  33312. // Result
  33313. var vertexData = new VertexData();
  33314. vertexData.indices = indices;
  33315. vertexData.positions = positions;
  33316. vertexData.normals = normals;
  33317. vertexData.uvs = uvs;
  33318. return vertexData;
  33319. };
  33320. /**
  33321. * Creates the VertexData of the Plane.
  33322. */
  33323. VertexData.CreatePlane = function (options) {
  33324. var indices = [];
  33325. var positions = [];
  33326. var normals = [];
  33327. var uvs = [];
  33328. var width = options.width || options.size || 1;
  33329. var height = options.height || options.size || 1;
  33330. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33331. // Vertices
  33332. var halfWidth = width / 2.0;
  33333. var halfHeight = height / 2.0;
  33334. positions.push(-halfWidth, -halfHeight, 0);
  33335. normals.push(0, 0, -1.0);
  33336. uvs.push(0.0, 0.0);
  33337. positions.push(halfWidth, -halfHeight, 0);
  33338. normals.push(0, 0, -1.0);
  33339. uvs.push(1.0, 0.0);
  33340. positions.push(halfWidth, halfHeight, 0);
  33341. normals.push(0, 0, -1.0);
  33342. uvs.push(1.0, 1.0);
  33343. positions.push(-halfWidth, halfHeight, 0);
  33344. normals.push(0, 0, -1.0);
  33345. uvs.push(0.0, 1.0);
  33346. // Indices
  33347. indices.push(0);
  33348. indices.push(1);
  33349. indices.push(2);
  33350. indices.push(0);
  33351. indices.push(2);
  33352. indices.push(3);
  33353. // Sides
  33354. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33355. // Result
  33356. var vertexData = new VertexData();
  33357. vertexData.indices = indices;
  33358. vertexData.positions = positions;
  33359. vertexData.normals = normals;
  33360. vertexData.uvs = uvs;
  33361. return vertexData;
  33362. };
  33363. /**
  33364. * Creates the VertexData of the Disc or regular Polygon.
  33365. */
  33366. VertexData.CreateDisc = function (options) {
  33367. var positions = new Array();
  33368. var indices = new Array();
  33369. var normals = new Array();
  33370. var uvs = new Array();
  33371. var radius = options.radius || 0.5;
  33372. var tessellation = options.tessellation || 64;
  33373. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33374. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33375. // positions and uvs
  33376. positions.push(0, 0, 0); // disc center first
  33377. uvs.push(0.5, 0.5);
  33378. var theta = Math.PI * 2 * arc;
  33379. var step = theta / tessellation;
  33380. for (var a = 0; a < theta; a += step) {
  33381. var x = Math.cos(a);
  33382. var y = Math.sin(a);
  33383. var u = (x + 1) / 2;
  33384. var v = (1 - y) / 2;
  33385. positions.push(radius * x, radius * y, 0);
  33386. uvs.push(u, v);
  33387. }
  33388. if (arc === 1) {
  33389. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33390. uvs.push(uvs[2], uvs[3]);
  33391. }
  33392. //indices
  33393. var vertexNb = positions.length / 3;
  33394. for (var i = 1; i < vertexNb - 1; i++) {
  33395. indices.push(i + 1, 0, i);
  33396. }
  33397. // result
  33398. VertexData.ComputeNormals(positions, indices, normals);
  33399. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33400. var vertexData = new VertexData();
  33401. vertexData.indices = indices;
  33402. vertexData.positions = positions;
  33403. vertexData.normals = normals;
  33404. vertexData.uvs = uvs;
  33405. return vertexData;
  33406. };
  33407. /**
  33408. * Re-creates the VertexData of the Polygon for sideOrientation.
  33409. */
  33410. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33411. var faceUV = fUV || new Array(3);
  33412. var faceColors = fColors;
  33413. var colors = [];
  33414. // default face colors and UV if undefined
  33415. for (var f = 0; f < 3; f++) {
  33416. if (faceUV[f] === undefined) {
  33417. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33418. }
  33419. if (faceColors && faceColors[f] === undefined) {
  33420. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33421. }
  33422. }
  33423. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33424. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33425. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33426. var indices = polygon.getIndices();
  33427. // set face colours and textures
  33428. var idx = 0;
  33429. var face = 0;
  33430. for (var index = 0; index < normals.length; index += 3) {
  33431. //Edge Face no. 1
  33432. if (Math.abs(normals[index + 1]) < 0.001) {
  33433. face = 1;
  33434. }
  33435. //Top Face no. 0
  33436. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33437. face = 0;
  33438. }
  33439. //Bottom Face no. 2
  33440. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33441. face = 2;
  33442. }
  33443. idx = index / 3;
  33444. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33445. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33446. if (faceColors) {
  33447. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33448. }
  33449. }
  33450. // sides
  33451. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33452. // Result
  33453. var vertexData = new VertexData();
  33454. vertexData.indices = indices;
  33455. vertexData.positions = positions;
  33456. vertexData.normals = normals;
  33457. vertexData.uvs = uvs;
  33458. if (faceColors) {
  33459. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33460. vertexData.colors = totalColors;
  33461. }
  33462. return vertexData;
  33463. };
  33464. /**
  33465. * Creates the VertexData of the IcoSphere.
  33466. */
  33467. VertexData.CreateIcoSphere = function (options) {
  33468. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33469. var radius = options.radius || 1;
  33470. var flat = (options.flat === undefined) ? true : options.flat;
  33471. var subdivisions = options.subdivisions || 4;
  33472. var radiusX = options.radiusX || radius;
  33473. var radiusY = options.radiusY || radius;
  33474. var radiusZ = options.radiusZ || radius;
  33475. var t = (1 + Math.sqrt(5)) / 2;
  33476. // 12 vertex x,y,z
  33477. var ico_vertices = [
  33478. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33479. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33480. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33481. ];
  33482. // index of 3 vertex makes a face of icopshere
  33483. var ico_indices = [
  33484. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33485. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33486. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33487. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33488. ];
  33489. // vertex for uv have aliased position, not for UV
  33490. var vertices_unalias_id = [
  33491. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33492. // vertex alias
  33493. 0,
  33494. 2,
  33495. 3,
  33496. 3,
  33497. 3,
  33498. 4,
  33499. 7,
  33500. 8,
  33501. 9,
  33502. 9,
  33503. 10,
  33504. 11 // 23: B + 12
  33505. ];
  33506. // uv as integer step (not pixels !)
  33507. var ico_vertexuv = [
  33508. 5, 1, 3, 1, 6, 4, 0, 0,
  33509. 5, 3, 4, 2, 2, 2, 4, 0,
  33510. 2, 0, 1, 1, 6, 0, 6, 2,
  33511. // vertex alias (for same vertex on different faces)
  33512. 0, 4,
  33513. 3, 3,
  33514. 4, 4,
  33515. 3, 1,
  33516. 4, 2,
  33517. 4, 4,
  33518. 0, 2,
  33519. 1, 1,
  33520. 2, 2,
  33521. 3, 3,
  33522. 1, 3,
  33523. 2, 4 // 23: B + 12
  33524. ];
  33525. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33526. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33527. // First island of uv mapping
  33528. // v = 4h 3+ 2
  33529. // v = 3h 9+ 4
  33530. // v = 2h 9+ 5 B
  33531. // v = 1h 9 1 0
  33532. // v = 0h 3 8 7 A
  33533. // u = 0 1 2 3 4 5 6 *a
  33534. // Second island of uv mapping
  33535. // v = 4h 0+ B+ 4+
  33536. // v = 3h A+ 2+
  33537. // v = 2h 7+ 6 3+
  33538. // v = 1h 8+ 3+
  33539. // v = 0h
  33540. // u = 0 1 2 3 4 5 6 *a
  33541. // Face layout on texture UV mapping
  33542. // ============
  33543. // \ 4 /\ 16 / ======
  33544. // \ / \ / /\ 11 /
  33545. // \/ 7 \/ / \ /
  33546. // ======= / 10 \/
  33547. // /\ 17 /\ =======
  33548. // / \ / \ \ 15 /\
  33549. // / 8 \/ 12 \ \ / \
  33550. // ============ \/ 6 \
  33551. // \ 18 /\ ============
  33552. // \ / \ \ 5 /\ 0 /
  33553. // \/ 13 \ \ / \ /
  33554. // ======= \/ 1 \/
  33555. // =============
  33556. // /\ 19 /\ 2 /\
  33557. // / \ / \ / \
  33558. // / 14 \/ 9 \/ 3 \
  33559. // ===================
  33560. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33561. var ustep = 138 / 1024;
  33562. var vstep = 239 / 1024;
  33563. var uoffset = 60 / 1024;
  33564. var voffset = 26 / 1024;
  33565. // Second island should have margin, not to touch the first island
  33566. // avoid any borderline artefact in pixel rounding
  33567. var island_u_offset = -40 / 1024;
  33568. var island_v_offset = +20 / 1024;
  33569. // face is either island 0 or 1 :
  33570. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33571. var island = [
  33572. 0, 0, 0, 0, 1,
  33573. 0, 0, 1, 1, 0,
  33574. 0, 0, 1, 1, 0,
  33575. 0, 1, 1, 1, 0 // 15 - 19
  33576. ];
  33577. var indices = new Array();
  33578. var positions = new Array();
  33579. var normals = new Array();
  33580. var uvs = new Array();
  33581. var current_indice = 0;
  33582. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33583. var face_vertex_pos = new Array(3);
  33584. var face_vertex_uv = new Array(3);
  33585. var v012;
  33586. for (v012 = 0; v012 < 3; v012++) {
  33587. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33588. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33589. }
  33590. // create all with normals
  33591. for (var face = 0; face < 20; face++) {
  33592. // 3 vertex per face
  33593. for (v012 = 0; v012 < 3; v012++) {
  33594. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33595. var v_id = ico_indices[3 * face + v012];
  33596. // vertex have 3D position (x,y,z)
  33597. 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]);
  33598. // Normalize to get normal, then scale to radius
  33599. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33600. // uv Coordinates from vertex ID
  33601. 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);
  33602. }
  33603. // Subdivide the face (interpolate pos, norm, uv)
  33604. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33605. // - norm is linear interpolation of vertex corner normal
  33606. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33607. // - uv is linear interpolation
  33608. //
  33609. // Topology is as below for sub-divide by 2
  33610. // vertex shown as v0,v1,v2
  33611. // interp index is i1 to progress in range [v0,v1[
  33612. // interp index is i2 to progress in range [v0,v2[
  33613. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33614. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33615. //
  33616. //
  33617. // i2 v2
  33618. // ^ ^
  33619. // / / \
  33620. // / / \
  33621. // / / \
  33622. // / / (0,1) \
  33623. // / #---------\
  33624. // / / \ (0,0)'/ \
  33625. // / / \ / \
  33626. // / / \ / \
  33627. // / / (0,0) \ / (1,0) \
  33628. // / #---------#---------\
  33629. // v0 v1
  33630. //
  33631. // --------------------> i1
  33632. //
  33633. // interp of (i1,i2):
  33634. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33635. // along i1 : lerp(x0,x1, i1/(S-i2))
  33636. //
  33637. // centroid of triangle is needed to get help normal computation
  33638. // (c1,c2) are used for centroid location
  33639. var interp_vertex = function (i1, i2, c1, c2) {
  33640. // vertex is interpolated from
  33641. // - face_vertex_pos[0..2]
  33642. // - face_vertex_uv[0..2]
  33643. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33644. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33645. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33646. pos_interp.normalize();
  33647. var vertex_normal;
  33648. if (flat) {
  33649. // in flat mode, recalculate normal as face centroid normal
  33650. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33651. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33652. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33653. }
  33654. else {
  33655. // in smooth mode, recalculate normal from each single vertex position
  33656. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33657. }
  33658. // Vertex normal need correction due to X,Y,Z radius scaling
  33659. vertex_normal.x /= radiusX;
  33660. vertex_normal.y /= radiusY;
  33661. vertex_normal.z /= radiusZ;
  33662. vertex_normal.normalize();
  33663. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33664. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33665. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33666. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33667. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33668. uvs.push(uv_interp.x, uv_interp.y);
  33669. // push each vertex has member of a face
  33670. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33671. indices.push(current_indice);
  33672. current_indice++;
  33673. };
  33674. for (var i2 = 0; i2 < subdivisions; i2++) {
  33675. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33676. // face : (i1,i2) for /\ :
  33677. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33678. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33679. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33680. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33681. if (i1 + i2 + 1 < subdivisions) {
  33682. // face : (i1,i2)' for \/ :
  33683. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33684. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33685. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33686. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33687. }
  33688. }
  33689. }
  33690. }
  33691. // Sides
  33692. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33693. // Result
  33694. var vertexData = new VertexData();
  33695. vertexData.indices = indices;
  33696. vertexData.positions = positions;
  33697. vertexData.normals = normals;
  33698. vertexData.uvs = uvs;
  33699. return vertexData;
  33700. };
  33701. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33702. /**
  33703. * Creates the VertexData of the Polyhedron.
  33704. */
  33705. VertexData.CreatePolyhedron = function (options) {
  33706. // provided polyhedron types :
  33707. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33708. // 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)
  33709. var polyhedra = [];
  33710. 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]] };
  33711. 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]] };
  33712. polyhedra[2] = {
  33713. 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]],
  33714. 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]]
  33715. };
  33716. polyhedra[3] = {
  33717. 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]],
  33718. 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]]
  33719. };
  33720. polyhedra[4] = {
  33721. 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]],
  33722. 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]]
  33723. };
  33724. 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]] };
  33725. 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]] };
  33726. 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]] };
  33727. 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]] };
  33728. 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]] };
  33729. 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]] };
  33730. 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]] };
  33731. 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]] };
  33732. 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]] };
  33733. polyhedra[14] = {
  33734. 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]],
  33735. 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]]
  33736. };
  33737. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33738. var size = options.size;
  33739. var sizeX = options.sizeX || size || 1;
  33740. var sizeY = options.sizeY || size || 1;
  33741. var sizeZ = options.sizeZ || size || 1;
  33742. var data = options.custom || polyhedra[type];
  33743. var nbfaces = data.face.length;
  33744. var faceUV = options.faceUV || new Array(nbfaces);
  33745. var faceColors = options.faceColors;
  33746. var flat = (options.flat === undefined) ? true : options.flat;
  33747. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33748. var positions = new Array();
  33749. var indices = new Array();
  33750. var normals = new Array();
  33751. var uvs = new Array();
  33752. var colors = new Array();
  33753. var index = 0;
  33754. var faceIdx = 0; // face cursor in the array "indexes"
  33755. var indexes = new Array();
  33756. var i = 0;
  33757. var f = 0;
  33758. var u, v, ang, x, y, tmp;
  33759. // default face colors and UV if undefined
  33760. if (flat) {
  33761. for (f = 0; f < nbfaces; f++) {
  33762. if (faceColors && faceColors[f] === undefined) {
  33763. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33764. }
  33765. if (faceUV && faceUV[f] === undefined) {
  33766. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33767. }
  33768. }
  33769. }
  33770. if (!flat) {
  33771. for (i = 0; i < data.vertex.length; i++) {
  33772. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33773. uvs.push(0, 0);
  33774. }
  33775. for (f = 0; f < nbfaces; f++) {
  33776. for (i = 0; i < data.face[f].length - 2; i++) {
  33777. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33778. }
  33779. }
  33780. }
  33781. else {
  33782. for (f = 0; f < nbfaces; f++) {
  33783. var fl = data.face[f].length; // number of vertices of the current face
  33784. ang = 2 * Math.PI / fl;
  33785. x = 0.5 * Math.tan(ang / 2);
  33786. y = 0.5;
  33787. // positions, uvs, colors
  33788. for (i = 0; i < fl; i++) {
  33789. // positions
  33790. 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);
  33791. indexes.push(index);
  33792. index++;
  33793. // uvs
  33794. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33795. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33796. uvs.push(u, v);
  33797. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33798. y = x * Math.sin(ang) + y * Math.cos(ang);
  33799. x = tmp;
  33800. // colors
  33801. if (faceColors) {
  33802. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33803. }
  33804. }
  33805. // indices from indexes
  33806. for (i = 0; i < fl - 2; i++) {
  33807. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33808. }
  33809. faceIdx += fl;
  33810. }
  33811. }
  33812. VertexData.ComputeNormals(positions, indices, normals);
  33813. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33814. var vertexData = new VertexData();
  33815. vertexData.positions = positions;
  33816. vertexData.indices = indices;
  33817. vertexData.normals = normals;
  33818. vertexData.uvs = uvs;
  33819. if (faceColors && flat) {
  33820. vertexData.colors = colors;
  33821. }
  33822. return vertexData;
  33823. };
  33824. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33825. /**
  33826. * Creates the VertexData of the Torus Knot.
  33827. */
  33828. VertexData.CreateTorusKnot = function (options) {
  33829. var indices = new Array();
  33830. var positions = new Array();
  33831. var normals = new Array();
  33832. var uvs = new Array();
  33833. var radius = options.radius || 2;
  33834. var tube = options.tube || 0.5;
  33835. var radialSegments = options.radialSegments || 32;
  33836. var tubularSegments = options.tubularSegments || 32;
  33837. var p = options.p || 2;
  33838. var q = options.q || 3;
  33839. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33840. // Helper
  33841. var getPos = function (angle) {
  33842. var cu = Math.cos(angle);
  33843. var su = Math.sin(angle);
  33844. var quOverP = q / p * angle;
  33845. var cs = Math.cos(quOverP);
  33846. var tx = radius * (2 + cs) * 0.5 * cu;
  33847. var ty = radius * (2 + cs) * su * 0.5;
  33848. var tz = radius * Math.sin(quOverP) * 0.5;
  33849. return new BABYLON.Vector3(tx, ty, tz);
  33850. };
  33851. // Vertices
  33852. var i;
  33853. var j;
  33854. for (i = 0; i <= radialSegments; i++) {
  33855. var modI = i % radialSegments;
  33856. var u = modI / radialSegments * 2 * p * Math.PI;
  33857. var p1 = getPos(u);
  33858. var p2 = getPos(u + 0.01);
  33859. var tang = p2.subtract(p1);
  33860. var n = p2.add(p1);
  33861. var bitan = BABYLON.Vector3.Cross(tang, n);
  33862. n = BABYLON.Vector3.Cross(bitan, tang);
  33863. bitan.normalize();
  33864. n.normalize();
  33865. for (j = 0; j < tubularSegments; j++) {
  33866. var modJ = j % tubularSegments;
  33867. var v = modJ / tubularSegments * 2 * Math.PI;
  33868. var cx = -tube * Math.cos(v);
  33869. var cy = tube * Math.sin(v);
  33870. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33871. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33872. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33873. uvs.push(i / radialSegments);
  33874. uvs.push(j / tubularSegments);
  33875. }
  33876. }
  33877. for (i = 0; i < radialSegments; i++) {
  33878. for (j = 0; j < tubularSegments; j++) {
  33879. var jNext = (j + 1) % tubularSegments;
  33880. var a = i * tubularSegments + j;
  33881. var b = (i + 1) * tubularSegments + j;
  33882. var c = (i + 1) * tubularSegments + jNext;
  33883. var d = i * tubularSegments + jNext;
  33884. indices.push(d);
  33885. indices.push(b);
  33886. indices.push(a);
  33887. indices.push(d);
  33888. indices.push(c);
  33889. indices.push(b);
  33890. }
  33891. }
  33892. // Normals
  33893. VertexData.ComputeNormals(positions, indices, normals);
  33894. // Sides
  33895. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33896. // Result
  33897. var vertexData = new VertexData();
  33898. vertexData.indices = indices;
  33899. vertexData.positions = positions;
  33900. vertexData.normals = normals;
  33901. vertexData.uvs = uvs;
  33902. return vertexData;
  33903. };
  33904. // Tools
  33905. /**
  33906. * @param {any} - positions (number[] or Float32Array)
  33907. * @param {any} - indices (number[] or Uint16Array)
  33908. * @param {any} - normals (number[] or Float32Array)
  33909. * options (optional) :
  33910. * facetPositions : optional array of facet positions (vector3)
  33911. * facetNormals : optional array of facet normals (vector3)
  33912. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33913. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33914. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33915. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33916. * bInfo : optional bounding info, required for facetPartitioning computation
  33917. * useRightHandedSystem: optional boolean to for right handed system computation
  33918. * depthSort : optional boolean to enable the facet depth sort computation
  33919. * distanceTo : optional Vector3 to compute the facet depth from this location
  33920. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33921. */
  33922. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33923. // temporary scalar variables
  33924. var index = 0; // facet index
  33925. var p1p2x = 0.0; // p1p2 vector x coordinate
  33926. var p1p2y = 0.0; // p1p2 vector y coordinate
  33927. var p1p2z = 0.0; // p1p2 vector z coordinate
  33928. var p3p2x = 0.0; // p3p2 vector x coordinate
  33929. var p3p2y = 0.0; // p3p2 vector y coordinate
  33930. var p3p2z = 0.0; // p3p2 vector z coordinate
  33931. var faceNormalx = 0.0; // facet normal x coordinate
  33932. var faceNormaly = 0.0; // facet normal y coordinate
  33933. var faceNormalz = 0.0; // facet normal z coordinate
  33934. var length = 0.0; // facet normal length before normalization
  33935. var v1x = 0; // vector1 x index in the positions array
  33936. var v1y = 0; // vector1 y index in the positions array
  33937. var v1z = 0; // vector1 z index in the positions array
  33938. var v2x = 0; // vector2 x index in the positions array
  33939. var v2y = 0; // vector2 y index in the positions array
  33940. var v2z = 0; // vector2 z index in the positions array
  33941. var v3x = 0; // vector3 x index in the positions array
  33942. var v3y = 0; // vector3 y index in the positions array
  33943. var v3z = 0; // vector3 z index in the positions array
  33944. var computeFacetNormals = false;
  33945. var computeFacetPositions = false;
  33946. var computeFacetPartitioning = false;
  33947. var computeDepthSort = false;
  33948. var faceNormalSign = 1;
  33949. var ratio = 0;
  33950. var distanceTo = null;
  33951. if (options) {
  33952. computeFacetNormals = (options.facetNormals) ? true : false;
  33953. computeFacetPositions = (options.facetPositions) ? true : false;
  33954. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33955. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33956. ratio = options.ratio || 0;
  33957. computeDepthSort = (options.depthSort) ? true : false;
  33958. distanceTo = (options.distanceTo);
  33959. if (computeDepthSort) {
  33960. if (distanceTo === undefined) {
  33961. distanceTo = BABYLON.Vector3.Zero();
  33962. }
  33963. var depthSortedFacets = options.depthSortedFacets;
  33964. }
  33965. }
  33966. // facetPartitioning reinit if needed
  33967. var xSubRatio = 0;
  33968. var ySubRatio = 0;
  33969. var zSubRatio = 0;
  33970. var subSq = 0;
  33971. if (computeFacetPartitioning && options && options.bbSize) {
  33972. var ox = 0; // X partitioning index for facet position
  33973. var oy = 0; // Y partinioning index for facet position
  33974. var oz = 0; // Z partinioning index for facet position
  33975. var b1x = 0; // X partitioning index for facet v1 vertex
  33976. var b1y = 0; // Y partitioning index for facet v1 vertex
  33977. var b1z = 0; // z partitioning index for facet v1 vertex
  33978. var b2x = 0; // X partitioning index for facet v2 vertex
  33979. var b2y = 0; // Y partitioning index for facet v2 vertex
  33980. var b2z = 0; // Z partitioning index for facet v2 vertex
  33981. var b3x = 0; // X partitioning index for facet v3 vertex
  33982. var b3y = 0; // Y partitioning index for facet v3 vertex
  33983. var b3z = 0; // Z partitioning index for facet v3 vertex
  33984. var block_idx_o = 0; // facet barycenter block index
  33985. var block_idx_v1 = 0; // v1 vertex block index
  33986. var block_idx_v2 = 0; // v2 vertex block index
  33987. var block_idx_v3 = 0; // v3 vertex block index
  33988. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33989. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33990. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33991. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33992. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33993. subSq = options.subDiv.max * options.subDiv.max;
  33994. options.facetPartitioning.length = 0;
  33995. }
  33996. // reset the normals
  33997. for (index = 0; index < positions.length; index++) {
  33998. normals[index] = 0.0;
  33999. }
  34000. // Loop : 1 indice triplet = 1 facet
  34001. var nbFaces = (indices.length / 3) | 0;
  34002. for (index = 0; index < nbFaces; index++) {
  34003. // get the indexes of the coordinates of each vertex of the facet
  34004. v1x = indices[index * 3] * 3;
  34005. v1y = v1x + 1;
  34006. v1z = v1x + 2;
  34007. v2x = indices[index * 3 + 1] * 3;
  34008. v2y = v2x + 1;
  34009. v2z = v2x + 2;
  34010. v3x = indices[index * 3 + 2] * 3;
  34011. v3y = v3x + 1;
  34012. v3z = v3x + 2;
  34013. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34014. p1p2y = positions[v1y] - positions[v2y];
  34015. p1p2z = positions[v1z] - positions[v2z];
  34016. p3p2x = positions[v3x] - positions[v2x];
  34017. p3p2y = positions[v3y] - positions[v2y];
  34018. p3p2z = positions[v3z] - positions[v2z];
  34019. // compute the face normal with the cross product
  34020. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34021. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34022. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34023. // normalize this normal and store it in the array facetData
  34024. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34025. length = (length === 0) ? 1.0 : length;
  34026. faceNormalx /= length;
  34027. faceNormaly /= length;
  34028. faceNormalz /= length;
  34029. if (computeFacetNormals && options) {
  34030. options.facetNormals[index].x = faceNormalx;
  34031. options.facetNormals[index].y = faceNormaly;
  34032. options.facetNormals[index].z = faceNormalz;
  34033. }
  34034. if (computeFacetPositions && options) {
  34035. // compute and the facet barycenter coordinates in the array facetPositions
  34036. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34037. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34038. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34039. }
  34040. if (computeFacetPartitioning && options) {
  34041. // store the facet indexes in arrays in the main facetPartitioning array :
  34042. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34043. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34044. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34045. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34046. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34047. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34048. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34049. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34050. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34051. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34052. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34053. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34054. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34055. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34056. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34057. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34058. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34059. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34060. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34061. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34062. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34063. // push each facet index in each block containing the vertex
  34064. options.facetPartitioning[block_idx_v1].push(index);
  34065. if (block_idx_v2 != block_idx_v1) {
  34066. options.facetPartitioning[block_idx_v2].push(index);
  34067. }
  34068. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34069. options.facetPartitioning[block_idx_v3].push(index);
  34070. }
  34071. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34072. options.facetPartitioning[block_idx_o].push(index);
  34073. }
  34074. }
  34075. if (computeDepthSort && options && options.facetPositions) {
  34076. var dsf = depthSortedFacets[index];
  34077. dsf.ind = index * 3;
  34078. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34079. }
  34080. // compute the normals anyway
  34081. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34082. normals[v1y] += faceNormaly;
  34083. normals[v1z] += faceNormalz;
  34084. normals[v2x] += faceNormalx;
  34085. normals[v2y] += faceNormaly;
  34086. normals[v2z] += faceNormalz;
  34087. normals[v3x] += faceNormalx;
  34088. normals[v3y] += faceNormaly;
  34089. normals[v3z] += faceNormalz;
  34090. }
  34091. // last normalization of each normal
  34092. for (index = 0; index < normals.length / 3; index++) {
  34093. faceNormalx = normals[index * 3];
  34094. faceNormaly = normals[index * 3 + 1];
  34095. faceNormalz = normals[index * 3 + 2];
  34096. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34097. length = (length === 0) ? 1.0 : length;
  34098. faceNormalx /= length;
  34099. faceNormaly /= length;
  34100. faceNormalz /= length;
  34101. normals[index * 3] = faceNormalx;
  34102. normals[index * 3 + 1] = faceNormaly;
  34103. normals[index * 3 + 2] = faceNormalz;
  34104. }
  34105. };
  34106. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34107. var li = indices.length;
  34108. var ln = normals.length;
  34109. var i;
  34110. var n;
  34111. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34112. switch (sideOrientation) {
  34113. case BABYLON.Mesh.FRONTSIDE:
  34114. // nothing changed
  34115. break;
  34116. case BABYLON.Mesh.BACKSIDE:
  34117. var tmp;
  34118. // indices
  34119. for (i = 0; i < li; i += 3) {
  34120. tmp = indices[i];
  34121. indices[i] = indices[i + 2];
  34122. indices[i + 2] = tmp;
  34123. }
  34124. // normals
  34125. for (n = 0; n < ln; n++) {
  34126. normals[n] = -normals[n];
  34127. }
  34128. break;
  34129. case BABYLON.Mesh.DOUBLESIDE:
  34130. // positions
  34131. var lp = positions.length;
  34132. var l = lp / 3;
  34133. for (var p = 0; p < lp; p++) {
  34134. positions[lp + p] = positions[p];
  34135. }
  34136. // indices
  34137. for (i = 0; i < li; i += 3) {
  34138. indices[i + li] = indices[i + 2] + l;
  34139. indices[i + 1 + li] = indices[i + 1] + l;
  34140. indices[i + 2 + li] = indices[i] + l;
  34141. }
  34142. // normals
  34143. for (n = 0; n < ln; n++) {
  34144. normals[ln + n] = -normals[n];
  34145. }
  34146. // uvs
  34147. var lu = uvs.length;
  34148. var u = 0;
  34149. for (u = 0; u < lu; u++) {
  34150. uvs[u + lu] = uvs[u];
  34151. }
  34152. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34153. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34154. u = 0;
  34155. for (i = 0; i < lu / 2; i++) {
  34156. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34157. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34158. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34159. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34160. u += 2;
  34161. }
  34162. break;
  34163. }
  34164. };
  34165. /**
  34166. * Creates a new VertexData from the imported parameters.
  34167. */
  34168. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34169. var vertexData = new VertexData();
  34170. // positions
  34171. var positions = parsedVertexData.positions;
  34172. if (positions) {
  34173. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34174. }
  34175. // normals
  34176. var normals = parsedVertexData.normals;
  34177. if (normals) {
  34178. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34179. }
  34180. // tangents
  34181. var tangents = parsedVertexData.tangents;
  34182. if (tangents) {
  34183. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34184. }
  34185. // uvs
  34186. var uvs = parsedVertexData.uvs;
  34187. if (uvs) {
  34188. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34189. }
  34190. // uv2s
  34191. var uv2s = parsedVertexData.uv2s;
  34192. if (uv2s) {
  34193. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34194. }
  34195. // uv3s
  34196. var uv3s = parsedVertexData.uv3s;
  34197. if (uv3s) {
  34198. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34199. }
  34200. // uv4s
  34201. var uv4s = parsedVertexData.uv4s;
  34202. if (uv4s) {
  34203. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34204. }
  34205. // uv5s
  34206. var uv5s = parsedVertexData.uv5s;
  34207. if (uv5s) {
  34208. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34209. }
  34210. // uv6s
  34211. var uv6s = parsedVertexData.uv6s;
  34212. if (uv6s) {
  34213. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34214. }
  34215. // colors
  34216. var colors = parsedVertexData.colors;
  34217. if (colors) {
  34218. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34219. }
  34220. // matricesIndices
  34221. var matricesIndices = parsedVertexData.matricesIndices;
  34222. if (matricesIndices) {
  34223. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34224. }
  34225. // matricesWeights
  34226. var matricesWeights = parsedVertexData.matricesWeights;
  34227. if (matricesWeights) {
  34228. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34229. }
  34230. // indices
  34231. var indices = parsedVertexData.indices;
  34232. if (indices) {
  34233. vertexData.indices = indices;
  34234. }
  34235. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34236. };
  34237. return VertexData;
  34238. }());
  34239. BABYLON.VertexData = VertexData;
  34240. })(BABYLON || (BABYLON = {}));
  34241. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34242. var BABYLON;
  34243. (function (BABYLON) {
  34244. /**
  34245. * Class used to store geometry data (vertex buffers + index buffer)
  34246. */
  34247. var Geometry = /** @class */ (function () {
  34248. /**
  34249. * Creates a new geometry
  34250. * @param id defines the unique ID
  34251. * @param scene defines the hosting scene
  34252. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34253. * @param updatable defines if geometry must be updatable (false by default)
  34254. * @param mesh defines the mesh that will be associated with the geometry
  34255. */
  34256. function Geometry(id, scene, vertexData, updatable, mesh) {
  34257. if (updatable === void 0) { updatable = false; }
  34258. if (mesh === void 0) { mesh = null; }
  34259. /**
  34260. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34261. */
  34262. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34263. this._totalVertices = 0;
  34264. this._isDisposed = false;
  34265. this._indexBufferIsUpdatable = false;
  34266. this.id = id;
  34267. this._engine = scene.getEngine();
  34268. this._meshes = [];
  34269. this._scene = scene;
  34270. //Init vertex buffer cache
  34271. this._vertexBuffers = {};
  34272. this._indices = [];
  34273. this._updatable = updatable;
  34274. // vertexData
  34275. if (vertexData) {
  34276. this.setAllVerticesData(vertexData, updatable);
  34277. }
  34278. else {
  34279. this._totalVertices = 0;
  34280. this._indices = [];
  34281. }
  34282. if (this._engine.getCaps().vertexArrayObject) {
  34283. this._vertexArrayObjects = {};
  34284. }
  34285. // applyToMesh
  34286. if (mesh) {
  34287. if (mesh.getClassName() === "LinesMesh") {
  34288. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34289. this.updateExtend();
  34290. }
  34291. this.applyToMesh(mesh);
  34292. mesh.computeWorldMatrix(true);
  34293. }
  34294. }
  34295. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34296. /**
  34297. * 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
  34298. */
  34299. get: function () {
  34300. return this._boundingBias;
  34301. },
  34302. /**
  34303. * 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
  34304. */
  34305. set: function (value) {
  34306. if (this._boundingBias && this._boundingBias.equals(value)) {
  34307. return;
  34308. }
  34309. this._boundingBias = value.clone();
  34310. this.updateBoundingInfo(true, null);
  34311. },
  34312. enumerable: true,
  34313. configurable: true
  34314. });
  34315. /**
  34316. * Static function used to attach a new empty geometry to a mesh
  34317. * @param mesh defines the mesh to attach the geometry to
  34318. * @returns the new {BABYLON.Geometry}
  34319. */
  34320. Geometry.CreateGeometryForMesh = function (mesh) {
  34321. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34322. geometry.applyToMesh(mesh);
  34323. return geometry;
  34324. };
  34325. Object.defineProperty(Geometry.prototype, "extend", {
  34326. /**
  34327. * Gets the current extend of the geometry
  34328. */
  34329. get: function () {
  34330. return this._extend;
  34331. },
  34332. enumerable: true,
  34333. configurable: true
  34334. });
  34335. /**
  34336. * Gets the hosting scene
  34337. * @returns the hosting {BABYLON.Scene}
  34338. */
  34339. Geometry.prototype.getScene = function () {
  34340. return this._scene;
  34341. };
  34342. /**
  34343. * Gets the hosting engine
  34344. * @returns the hosting {BABYLON.Engine}
  34345. */
  34346. Geometry.prototype.getEngine = function () {
  34347. return this._engine;
  34348. };
  34349. /**
  34350. * Defines if the geometry is ready to use
  34351. * @returns true if the geometry is ready to be used
  34352. */
  34353. Geometry.prototype.isReady = function () {
  34354. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34355. };
  34356. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34357. /**
  34358. * Gets a value indicating that the geometry should not be serialized
  34359. */
  34360. get: function () {
  34361. for (var index = 0; index < this._meshes.length; index++) {
  34362. if (!this._meshes[index].doNotSerialize) {
  34363. return false;
  34364. }
  34365. }
  34366. return true;
  34367. },
  34368. enumerable: true,
  34369. configurable: true
  34370. });
  34371. /** @ignore */
  34372. Geometry.prototype._rebuild = function () {
  34373. if (this._vertexArrayObjects) {
  34374. this._vertexArrayObjects = {};
  34375. }
  34376. // Index buffer
  34377. if (this._meshes.length !== 0 && this._indices) {
  34378. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34379. }
  34380. // Vertex buffers
  34381. for (var key in this._vertexBuffers) {
  34382. var vertexBuffer = this._vertexBuffers[key];
  34383. vertexBuffer._rebuild();
  34384. }
  34385. };
  34386. /**
  34387. * Affects all gemetry data in one call
  34388. * @param vertexData defines the geometry data
  34389. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34390. */
  34391. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34392. vertexData.applyToGeometry(this, updatable);
  34393. this.notifyUpdate();
  34394. };
  34395. /**
  34396. * Set specific vertex data
  34397. * @param kind defines the data kind (Position, normal, etc...)
  34398. * @param data defines the vertex data to use
  34399. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34400. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34401. */
  34402. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34403. if (updatable === void 0) { updatable = false; }
  34404. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34405. this.setVerticesBuffer(buffer);
  34406. };
  34407. /**
  34408. * Removes a specific vertex data
  34409. * @param kind defines the data kind (Position, normal, etc...)
  34410. */
  34411. Geometry.prototype.removeVerticesData = function (kind) {
  34412. if (this._vertexBuffers[kind]) {
  34413. this._vertexBuffers[kind].dispose();
  34414. delete this._vertexBuffers[kind];
  34415. }
  34416. };
  34417. /**
  34418. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34419. * @param buffer defines the vertex buffer to use
  34420. */
  34421. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34422. var kind = buffer.getKind();
  34423. if (this._vertexBuffers[kind]) {
  34424. this._vertexBuffers[kind].dispose();
  34425. }
  34426. this._vertexBuffers[kind] = buffer;
  34427. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34428. var data = buffer.getData();
  34429. var stride = buffer.getStrideSize();
  34430. this._totalVertices = data.length / stride;
  34431. this.updateExtend(data, stride);
  34432. this._resetPointsArrayCache();
  34433. var meshes = this._meshes;
  34434. var numOfMeshes = meshes.length;
  34435. for (var index = 0; index < numOfMeshes; index++) {
  34436. var mesh = meshes[index];
  34437. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34438. mesh._createGlobalSubMesh(false);
  34439. mesh.computeWorldMatrix(true);
  34440. }
  34441. }
  34442. this.notifyUpdate(kind);
  34443. if (this._vertexArrayObjects) {
  34444. this._disposeVertexArrayObjects();
  34445. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34446. }
  34447. };
  34448. /**
  34449. * Update a specific vertex buffer
  34450. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34451. * It will do nothing if the buffer is not updatable
  34452. * @param kind defines the data kind (Position, normal, etc...)
  34453. * @param data defines the data to use
  34454. * @param offset defines the offset in the target buffer where to store the data
  34455. */
  34456. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34457. var vertexBuffer = this.getVertexBuffer(kind);
  34458. if (!vertexBuffer) {
  34459. return;
  34460. }
  34461. vertexBuffer.updateDirectly(data, offset);
  34462. this.notifyUpdate(kind);
  34463. };
  34464. /**
  34465. * Update a specific vertex buffer
  34466. * This function will create a new buffer if the current one is not updatable
  34467. * @param kind defines the data kind (Position, normal, etc...)
  34468. * @param data defines the data to use
  34469. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34470. */
  34471. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34472. if (updateExtends === void 0) { updateExtends = false; }
  34473. var vertexBuffer = this.getVertexBuffer(kind);
  34474. if (!vertexBuffer) {
  34475. return;
  34476. }
  34477. vertexBuffer.update(data);
  34478. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34479. var stride = vertexBuffer.getStrideSize();
  34480. this._totalVertices = data.length / stride;
  34481. this.updateBoundingInfo(updateExtends, data);
  34482. }
  34483. this.notifyUpdate(kind);
  34484. };
  34485. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34486. if (updateExtends) {
  34487. this.updateExtend(data);
  34488. }
  34489. var meshes = this._meshes;
  34490. var numOfMeshes = meshes.length;
  34491. this._resetPointsArrayCache();
  34492. for (var index = 0; index < numOfMeshes; index++) {
  34493. var mesh = meshes[index];
  34494. if (updateExtends) {
  34495. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34496. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34497. var subMesh = mesh.subMeshes[subIndex];
  34498. subMesh.refreshBoundingInfo();
  34499. }
  34500. }
  34501. }
  34502. };
  34503. /** @ignore */
  34504. Geometry.prototype._bind = function (effect, indexToBind) {
  34505. if (!effect) {
  34506. return;
  34507. }
  34508. if (indexToBind === undefined) {
  34509. indexToBind = this._indexBuffer;
  34510. }
  34511. var vbs = this.getVertexBuffers();
  34512. if (!vbs) {
  34513. return;
  34514. }
  34515. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34516. this._engine.bindBuffers(vbs, indexToBind, effect);
  34517. return;
  34518. }
  34519. // Using VAO
  34520. if (!this._vertexArrayObjects[effect.key]) {
  34521. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34522. }
  34523. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34524. };
  34525. /**
  34526. * Gets total number of vertices
  34527. * @returns the total number of vertices
  34528. */
  34529. Geometry.prototype.getTotalVertices = function () {
  34530. if (!this.isReady()) {
  34531. return 0;
  34532. }
  34533. return this._totalVertices;
  34534. };
  34535. /**
  34536. * Gets a specific vertex data attached to this geometry
  34537. * @param kind defines the data kind (Position, normal, etc...)
  34538. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34539. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34540. * @returns a float array containing vertex data
  34541. */
  34542. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34543. var vertexBuffer = this.getVertexBuffer(kind);
  34544. if (!vertexBuffer) {
  34545. return null;
  34546. }
  34547. var orig = vertexBuffer.getData();
  34548. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34549. return orig;
  34550. }
  34551. else {
  34552. var len = orig.length;
  34553. var copy = [];
  34554. for (var i = 0; i < len; i++) {
  34555. copy.push(orig[i]);
  34556. }
  34557. return copy;
  34558. }
  34559. };
  34560. /**
  34561. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34562. * @param kind defines the data kind (Position, normal, etc...)
  34563. * @returns true if the vertex buffer with the specified kind is updatable
  34564. */
  34565. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34566. var vb = this._vertexBuffers[kind];
  34567. if (!vb) {
  34568. return false;
  34569. }
  34570. return vb.isUpdatable();
  34571. };
  34572. /**
  34573. * Gets a specific vertex buffer
  34574. * @param kind defines the data kind (Position, normal, etc...)
  34575. * @returns a {BABYLON.VertexBuffer}
  34576. */
  34577. Geometry.prototype.getVertexBuffer = function (kind) {
  34578. if (!this.isReady()) {
  34579. return null;
  34580. }
  34581. return this._vertexBuffers[kind];
  34582. };
  34583. /**
  34584. * Returns all vertex buffers
  34585. * @return an object holding all vertex buffers indexed by kind
  34586. */
  34587. Geometry.prototype.getVertexBuffers = function () {
  34588. if (!this.isReady()) {
  34589. return null;
  34590. }
  34591. return this._vertexBuffers;
  34592. };
  34593. /**
  34594. * Gets a boolean indicating if specific vertex buffer is present
  34595. * @param kind defines the data kind (Position, normal, etc...)
  34596. * @returns true if data is present
  34597. */
  34598. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34599. if (!this._vertexBuffers) {
  34600. if (this._delayInfo) {
  34601. return this._delayInfo.indexOf(kind) !== -1;
  34602. }
  34603. return false;
  34604. }
  34605. return this._vertexBuffers[kind] !== undefined;
  34606. };
  34607. /**
  34608. * Gets a list of all attached data kinds (Position, normal, etc...)
  34609. * @returns a list of string containing all kinds
  34610. */
  34611. Geometry.prototype.getVerticesDataKinds = function () {
  34612. var result = [];
  34613. var kind;
  34614. if (!this._vertexBuffers && this._delayInfo) {
  34615. for (kind in this._delayInfo) {
  34616. result.push(kind);
  34617. }
  34618. }
  34619. else {
  34620. for (kind in this._vertexBuffers) {
  34621. result.push(kind);
  34622. }
  34623. }
  34624. return result;
  34625. };
  34626. /**
  34627. * Update index buffer
  34628. * @param indices defines the indices to store in the index buffer
  34629. * @param offset defines the offset in the target buffer where to store the data
  34630. */
  34631. Geometry.prototype.updateIndices = function (indices, offset) {
  34632. if (!this._indexBuffer) {
  34633. return;
  34634. }
  34635. if (!this._indexBufferIsUpdatable) {
  34636. this.setIndices(indices, null, true);
  34637. }
  34638. else {
  34639. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34640. }
  34641. };
  34642. /**
  34643. * Creates a new index buffer
  34644. * @param indices defines the indices to store in the index buffer
  34645. * @param totalVertices defines the total number of vertices (could be null)
  34646. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34647. */
  34648. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34649. if (totalVertices === void 0) { totalVertices = null; }
  34650. if (updatable === void 0) { updatable = false; }
  34651. if (this._indexBuffer) {
  34652. this._engine._releaseBuffer(this._indexBuffer);
  34653. }
  34654. this._disposeVertexArrayObjects();
  34655. this._indices = indices;
  34656. this._indexBufferIsUpdatable = updatable;
  34657. if (this._meshes.length !== 0 && this._indices) {
  34658. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34659. }
  34660. if (totalVertices != undefined) {
  34661. this._totalVertices = totalVertices;
  34662. }
  34663. var meshes = this._meshes;
  34664. var numOfMeshes = meshes.length;
  34665. for (var index = 0; index < numOfMeshes; index++) {
  34666. meshes[index]._createGlobalSubMesh(true);
  34667. }
  34668. this.notifyUpdate();
  34669. };
  34670. /**
  34671. * Return the total number of indices
  34672. * @returns the total number of indices
  34673. */
  34674. Geometry.prototype.getTotalIndices = function () {
  34675. if (!this.isReady()) {
  34676. return 0;
  34677. }
  34678. return this._indices.length;
  34679. };
  34680. /**
  34681. * Gets the index buffer array
  34682. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34683. * @returns the index buffer array
  34684. */
  34685. Geometry.prototype.getIndices = function (copyWhenShared) {
  34686. if (!this.isReady()) {
  34687. return null;
  34688. }
  34689. var orig = this._indices;
  34690. if (!copyWhenShared || this._meshes.length === 1) {
  34691. return orig;
  34692. }
  34693. else {
  34694. var len = orig.length;
  34695. var copy = [];
  34696. for (var i = 0; i < len; i++) {
  34697. copy.push(orig[i]);
  34698. }
  34699. return copy;
  34700. }
  34701. };
  34702. /**
  34703. * Gets the index buffer
  34704. * @return the index buffer
  34705. */
  34706. Geometry.prototype.getIndexBuffer = function () {
  34707. if (!this.isReady()) {
  34708. return null;
  34709. }
  34710. return this._indexBuffer;
  34711. };
  34712. /** @ignore */
  34713. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34714. if (effect === void 0) { effect = null; }
  34715. if (!effect || !this._vertexArrayObjects) {
  34716. return;
  34717. }
  34718. if (this._vertexArrayObjects[effect.key]) {
  34719. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34720. delete this._vertexArrayObjects[effect.key];
  34721. }
  34722. };
  34723. /**
  34724. * Release the associated resources for a specific mesh
  34725. * @param mesh defines the source mesh
  34726. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34727. */
  34728. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34729. var meshes = this._meshes;
  34730. var index = meshes.indexOf(mesh);
  34731. if (index === -1) {
  34732. return;
  34733. }
  34734. meshes.splice(index, 1);
  34735. mesh._geometry = null;
  34736. if (meshes.length === 0 && shouldDispose) {
  34737. this.dispose();
  34738. }
  34739. };
  34740. /**
  34741. * Apply current geometry to a given mesh
  34742. * @param mesh defines the mesh to apply geometry to
  34743. */
  34744. Geometry.prototype.applyToMesh = function (mesh) {
  34745. if (mesh._geometry === this) {
  34746. return;
  34747. }
  34748. var previousGeometry = mesh._geometry;
  34749. if (previousGeometry) {
  34750. previousGeometry.releaseForMesh(mesh);
  34751. }
  34752. var meshes = this._meshes;
  34753. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34754. mesh._geometry = this;
  34755. this._scene.pushGeometry(this);
  34756. meshes.push(mesh);
  34757. if (this.isReady()) {
  34758. this._applyToMesh(mesh);
  34759. }
  34760. else {
  34761. mesh._boundingInfo = this._boundingInfo;
  34762. }
  34763. };
  34764. Geometry.prototype.updateExtend = function (data, stride) {
  34765. if (data === void 0) { data = null; }
  34766. if (!data) {
  34767. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34768. }
  34769. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34770. };
  34771. Geometry.prototype._applyToMesh = function (mesh) {
  34772. var numOfMeshes = this._meshes.length;
  34773. // vertexBuffers
  34774. for (var kind in this._vertexBuffers) {
  34775. if (numOfMeshes === 1) {
  34776. this._vertexBuffers[kind].create();
  34777. }
  34778. var buffer = this._vertexBuffers[kind].getBuffer();
  34779. if (buffer)
  34780. buffer.references = numOfMeshes;
  34781. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34782. if (!this._extend) {
  34783. this.updateExtend(this._vertexBuffers[kind].getData());
  34784. }
  34785. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34786. mesh._createGlobalSubMesh(false);
  34787. //bounding info was just created again, world matrix should be applied again.
  34788. mesh._updateBoundingInfo();
  34789. }
  34790. }
  34791. // indexBuffer
  34792. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34793. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34794. }
  34795. if (this._indexBuffer) {
  34796. this._indexBuffer.references = numOfMeshes;
  34797. }
  34798. };
  34799. Geometry.prototype.notifyUpdate = function (kind) {
  34800. if (this.onGeometryUpdated) {
  34801. this.onGeometryUpdated(this, kind);
  34802. }
  34803. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34804. var mesh = _a[_i];
  34805. mesh._markSubMeshesAsAttributesDirty();
  34806. }
  34807. };
  34808. /**
  34809. * Load the geometry if it was flagged as delay loaded
  34810. * @param scene defines the hosting scene
  34811. * @param onLoaded defines a callback called when the geometry is loaded
  34812. */
  34813. Geometry.prototype.load = function (scene, onLoaded) {
  34814. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34815. return;
  34816. }
  34817. if (this.isReady()) {
  34818. if (onLoaded) {
  34819. onLoaded();
  34820. }
  34821. return;
  34822. }
  34823. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34824. this._queueLoad(scene, onLoaded);
  34825. };
  34826. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34827. var _this = this;
  34828. if (!this.delayLoadingFile) {
  34829. return;
  34830. }
  34831. scene._addPendingData(this);
  34832. scene._loadFile(this.delayLoadingFile, function (data) {
  34833. if (!_this._delayLoadingFunction) {
  34834. return;
  34835. }
  34836. _this._delayLoadingFunction(JSON.parse(data), _this);
  34837. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34838. _this._delayInfo = [];
  34839. scene._removePendingData(_this);
  34840. var meshes = _this._meshes;
  34841. var numOfMeshes = meshes.length;
  34842. for (var index = 0; index < numOfMeshes; index++) {
  34843. _this._applyToMesh(meshes[index]);
  34844. }
  34845. if (onLoaded) {
  34846. onLoaded();
  34847. }
  34848. }, undefined, true);
  34849. };
  34850. /**
  34851. * Invert the geometry to move from a right handed system to a left handed one.
  34852. */
  34853. Geometry.prototype.toLeftHanded = function () {
  34854. // Flip faces
  34855. var tIndices = this.getIndices(false);
  34856. if (tIndices != null && tIndices.length > 0) {
  34857. for (var i = 0; i < tIndices.length; i += 3) {
  34858. var tTemp = tIndices[i + 0];
  34859. tIndices[i + 0] = tIndices[i + 2];
  34860. tIndices[i + 2] = tTemp;
  34861. }
  34862. this.setIndices(tIndices);
  34863. }
  34864. // Negate position.z
  34865. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34866. if (tPositions != null && tPositions.length > 0) {
  34867. for (var i = 0; i < tPositions.length; i += 3) {
  34868. tPositions[i + 2] = -tPositions[i + 2];
  34869. }
  34870. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34871. }
  34872. // Negate normal.z
  34873. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34874. if (tNormals != null && tNormals.length > 0) {
  34875. for (var i = 0; i < tNormals.length; i += 3) {
  34876. tNormals[i + 2] = -tNormals[i + 2];
  34877. }
  34878. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34879. }
  34880. };
  34881. // Cache
  34882. /** @ignore */
  34883. Geometry.prototype._resetPointsArrayCache = function () {
  34884. this._positions = null;
  34885. };
  34886. /** @ignore */
  34887. Geometry.prototype._generatePointsArray = function () {
  34888. if (this._positions)
  34889. return true;
  34890. this._positions = [];
  34891. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34892. if (!data) {
  34893. return false;
  34894. }
  34895. for (var index = 0; index < data.length; index += 3) {
  34896. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34897. }
  34898. return true;
  34899. };
  34900. /**
  34901. * Gets a value indicating if the geometry is disposed
  34902. * @returns true if the geometry was disposed
  34903. */
  34904. Geometry.prototype.isDisposed = function () {
  34905. return this._isDisposed;
  34906. };
  34907. Geometry.prototype._disposeVertexArrayObjects = function () {
  34908. if (this._vertexArrayObjects) {
  34909. for (var kind in this._vertexArrayObjects) {
  34910. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34911. }
  34912. this._vertexArrayObjects = {};
  34913. }
  34914. };
  34915. /**
  34916. * Free all associated resources
  34917. */
  34918. Geometry.prototype.dispose = function () {
  34919. var meshes = this._meshes;
  34920. var numOfMeshes = meshes.length;
  34921. var index;
  34922. for (index = 0; index < numOfMeshes; index++) {
  34923. this.releaseForMesh(meshes[index]);
  34924. }
  34925. this._meshes = [];
  34926. this._disposeVertexArrayObjects();
  34927. for (var kind in this._vertexBuffers) {
  34928. this._vertexBuffers[kind].dispose();
  34929. }
  34930. this._vertexBuffers = {};
  34931. this._totalVertices = 0;
  34932. if (this._indexBuffer) {
  34933. this._engine._releaseBuffer(this._indexBuffer);
  34934. }
  34935. this._indexBuffer = null;
  34936. this._indices = [];
  34937. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34938. this.delayLoadingFile = null;
  34939. this._delayLoadingFunction = null;
  34940. this._delayInfo = [];
  34941. this._boundingInfo = null;
  34942. this._scene.removeGeometry(this);
  34943. this._isDisposed = true;
  34944. };
  34945. /**
  34946. * Clone the current geometry into a new geometry
  34947. * @param id defines the unique ID of the new geometry
  34948. * @returns a new geometry object
  34949. */
  34950. Geometry.prototype.copy = function (id) {
  34951. var vertexData = new BABYLON.VertexData();
  34952. vertexData.indices = [];
  34953. var indices = this.getIndices();
  34954. if (indices) {
  34955. for (var index = 0; index < indices.length; index++) {
  34956. vertexData.indices.push(indices[index]);
  34957. }
  34958. }
  34959. var updatable = false;
  34960. var stopChecking = false;
  34961. var kind;
  34962. for (kind in this._vertexBuffers) {
  34963. // using slice() to make a copy of the array and not just reference it
  34964. var data = this.getVerticesData(kind);
  34965. if (data instanceof Float32Array) {
  34966. vertexData.set(new Float32Array(data), kind);
  34967. }
  34968. else {
  34969. vertexData.set(data.slice(0), kind);
  34970. }
  34971. if (!stopChecking) {
  34972. var vb = this.getVertexBuffer(kind);
  34973. if (vb) {
  34974. updatable = vb.isUpdatable();
  34975. stopChecking = !updatable;
  34976. }
  34977. }
  34978. }
  34979. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34980. geometry.delayLoadState = this.delayLoadState;
  34981. geometry.delayLoadingFile = this.delayLoadingFile;
  34982. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34983. for (kind in this._delayInfo) {
  34984. geometry._delayInfo = geometry._delayInfo || [];
  34985. geometry._delayInfo.push(kind);
  34986. }
  34987. // Bounding info
  34988. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34989. return geometry;
  34990. };
  34991. /**
  34992. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34993. * @return a JSON representation of the current geometry data (without the vertices data)
  34994. */
  34995. Geometry.prototype.serialize = function () {
  34996. var serializationObject = {};
  34997. serializationObject.id = this.id;
  34998. serializationObject.updatable = this._updatable;
  34999. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35000. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35001. }
  35002. return serializationObject;
  35003. };
  35004. Geometry.prototype.toNumberArray = function (origin) {
  35005. if (Array.isArray(origin)) {
  35006. return origin;
  35007. }
  35008. else {
  35009. return Array.prototype.slice.call(origin);
  35010. }
  35011. };
  35012. /**
  35013. * Serialize all vertices data into a JSON oject
  35014. * @returns a JSON representation of the current geometry data
  35015. */
  35016. Geometry.prototype.serializeVerticeData = function () {
  35017. var serializationObject = this.serialize();
  35018. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35019. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35020. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35021. serializationObject.positions._updatable = true;
  35022. }
  35023. }
  35024. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35025. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35026. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35027. serializationObject.normals._updatable = true;
  35028. }
  35029. }
  35030. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35031. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35032. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35033. serializationObject.tangets._updatable = true;
  35034. }
  35035. }
  35036. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35037. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35038. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35039. serializationObject.uvs._updatable = true;
  35040. }
  35041. }
  35042. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35043. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35044. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35045. serializationObject.uv2s._updatable = true;
  35046. }
  35047. }
  35048. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35049. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35050. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35051. serializationObject.uv3s._updatable = true;
  35052. }
  35053. }
  35054. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35055. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35056. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35057. serializationObject.uv4s._updatable = true;
  35058. }
  35059. }
  35060. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35061. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35062. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35063. serializationObject.uv5s._updatable = true;
  35064. }
  35065. }
  35066. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35067. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35068. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35069. serializationObject.uv6s._updatable = true;
  35070. }
  35071. }
  35072. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35073. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35074. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35075. serializationObject.colors._updatable = true;
  35076. }
  35077. }
  35078. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35079. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35080. serializationObject.matricesIndices._isExpanded = true;
  35081. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35082. serializationObject.matricesIndices._updatable = true;
  35083. }
  35084. }
  35085. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35086. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35087. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35088. serializationObject.matricesWeights._updatable = true;
  35089. }
  35090. }
  35091. serializationObject.indices = this.toNumberArray(this.getIndices());
  35092. return serializationObject;
  35093. };
  35094. // Statics
  35095. /**
  35096. * Extracts a clone of a mesh geometry
  35097. * @param mesh defines the source mesh
  35098. * @param id defines the unique ID of the new geometry object
  35099. * @returns the new geometry object
  35100. */
  35101. Geometry.ExtractFromMesh = function (mesh, id) {
  35102. var geometry = mesh._geometry;
  35103. if (!geometry) {
  35104. return null;
  35105. }
  35106. return geometry.copy(id);
  35107. };
  35108. /**
  35109. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35110. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35111. * Be aware Math.random() could cause collisions, but:
  35112. * "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"
  35113. * @returns a string containing a new GUID
  35114. */
  35115. Geometry.RandomId = function () {
  35116. return BABYLON.Tools.RandomId();
  35117. };
  35118. /** @ignore */
  35119. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35120. var scene = mesh.getScene();
  35121. // Geometry
  35122. var geometryId = parsedGeometry.geometryId;
  35123. if (geometryId) {
  35124. var geometry = scene.getGeometryByID(geometryId);
  35125. if (geometry) {
  35126. geometry.applyToMesh(mesh);
  35127. }
  35128. }
  35129. else if (parsedGeometry instanceof ArrayBuffer) {
  35130. var binaryInfo = mesh._binaryInfo;
  35131. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35132. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35133. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35134. }
  35135. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35136. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35137. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35138. }
  35139. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35140. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35141. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35142. }
  35143. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35144. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35145. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35146. }
  35147. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35148. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35149. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35150. }
  35151. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35152. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35153. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35154. }
  35155. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35156. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35157. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35158. }
  35159. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35160. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35161. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35162. }
  35163. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35164. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35165. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35166. }
  35167. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35168. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35169. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35170. }
  35171. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35172. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35174. }
  35175. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35176. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35177. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35178. }
  35179. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35180. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35181. mesh.setIndices(indicesData, null);
  35182. }
  35183. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35184. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35185. mesh.subMeshes = [];
  35186. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35187. var materialIndex = subMeshesData[(i * 5) + 0];
  35188. var verticesStart = subMeshesData[(i * 5) + 1];
  35189. var verticesCount = subMeshesData[(i * 5) + 2];
  35190. var indexStart = subMeshesData[(i * 5) + 3];
  35191. var indexCount = subMeshesData[(i * 5) + 4];
  35192. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35193. }
  35194. }
  35195. }
  35196. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35197. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35198. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35199. if (parsedGeometry.tangents) {
  35200. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35201. }
  35202. if (parsedGeometry.uvs) {
  35203. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35204. }
  35205. if (parsedGeometry.uvs2) {
  35206. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35207. }
  35208. if (parsedGeometry.uvs3) {
  35209. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35210. }
  35211. if (parsedGeometry.uvs4) {
  35212. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35213. }
  35214. if (parsedGeometry.uvs5) {
  35215. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35216. }
  35217. if (parsedGeometry.uvs6) {
  35218. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35219. }
  35220. if (parsedGeometry.colors) {
  35221. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35222. }
  35223. if (parsedGeometry.matricesIndices) {
  35224. if (!parsedGeometry.matricesIndices._isExpanded) {
  35225. var floatIndices = [];
  35226. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35227. var matricesIndex = parsedGeometry.matricesIndices[i];
  35228. floatIndices.push(matricesIndex & 0x000000FF);
  35229. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35230. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35231. floatIndices.push(matricesIndex >> 24);
  35232. }
  35233. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35234. }
  35235. else {
  35236. delete parsedGeometry.matricesIndices._isExpanded;
  35237. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35238. }
  35239. }
  35240. if (parsedGeometry.matricesIndicesExtra) {
  35241. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35242. var floatIndices = [];
  35243. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35244. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35245. floatIndices.push(matricesIndex & 0x000000FF);
  35246. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35247. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35248. floatIndices.push(matricesIndex >> 24);
  35249. }
  35250. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35251. }
  35252. else {
  35253. delete parsedGeometry.matricesIndices._isExpanded;
  35254. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35255. }
  35256. }
  35257. if (parsedGeometry.matricesWeights) {
  35258. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35259. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35260. }
  35261. if (parsedGeometry.matricesWeightsExtra) {
  35262. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35263. }
  35264. mesh.setIndices(parsedGeometry.indices, null);
  35265. }
  35266. // SubMeshes
  35267. if (parsedGeometry.subMeshes) {
  35268. mesh.subMeshes = [];
  35269. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35270. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35271. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35272. }
  35273. }
  35274. // Flat shading
  35275. if (mesh._shouldGenerateFlatShading) {
  35276. mesh.convertToFlatShadedMesh();
  35277. delete mesh._shouldGenerateFlatShading;
  35278. }
  35279. // Update
  35280. mesh.computeWorldMatrix(true);
  35281. // Octree
  35282. var sceneOctree = scene.selectionOctree;
  35283. if (sceneOctree !== undefined && sceneOctree !== null) {
  35284. sceneOctree.addMesh(mesh);
  35285. }
  35286. };
  35287. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35288. var epsilon = 1e-3;
  35289. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35290. return;
  35291. }
  35292. var noInfluenceBoneIndex = 0.0;
  35293. if (parsedGeometry.skeletonId > -1) {
  35294. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35295. if (!skeleton) {
  35296. return;
  35297. }
  35298. noInfluenceBoneIndex = skeleton.bones.length;
  35299. }
  35300. else {
  35301. return;
  35302. }
  35303. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35304. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35305. var matricesWeights = parsedGeometry.matricesWeights;
  35306. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35307. var influencers = parsedGeometry.numBoneInfluencer;
  35308. var size = matricesWeights.length;
  35309. for (var i = 0; i < size; i += 4) {
  35310. var weight = 0.0;
  35311. var firstZeroWeight = -1;
  35312. for (var j = 0; j < 4; j++) {
  35313. var w = matricesWeights[i + j];
  35314. weight += w;
  35315. if (w < epsilon && firstZeroWeight < 0) {
  35316. firstZeroWeight = j;
  35317. }
  35318. }
  35319. if (matricesWeightsExtra) {
  35320. for (var j = 0; j < 4; j++) {
  35321. var w = matricesWeightsExtra[i + j];
  35322. weight += w;
  35323. if (w < epsilon && firstZeroWeight < 0) {
  35324. firstZeroWeight = j + 4;
  35325. }
  35326. }
  35327. }
  35328. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35329. firstZeroWeight = influencers - 1;
  35330. }
  35331. if (weight > epsilon) {
  35332. var mweight = 1.0 / weight;
  35333. for (var j = 0; j < 4; j++) {
  35334. matricesWeights[i + j] *= mweight;
  35335. }
  35336. if (matricesWeightsExtra) {
  35337. for (var j = 0; j < 4; j++) {
  35338. matricesWeightsExtra[i + j] *= mweight;
  35339. }
  35340. }
  35341. }
  35342. else {
  35343. if (firstZeroWeight >= 4) {
  35344. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35345. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35346. }
  35347. else {
  35348. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35349. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35350. }
  35351. }
  35352. }
  35353. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35354. if (parsedGeometry.matricesWeightsExtra) {
  35355. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35356. }
  35357. };
  35358. /**
  35359. * Create a new geometry from persisted data (Using .babylon file format)
  35360. * @param parsedVertexData defines the persisted data
  35361. * @param scene defines the hosting scene
  35362. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35363. * @returns the new geometry object
  35364. */
  35365. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35366. if (scene.getGeometryByID(parsedVertexData.id)) {
  35367. return null; // null since geometry could be something else than a box...
  35368. }
  35369. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35370. if (BABYLON.Tags) {
  35371. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35372. }
  35373. if (parsedVertexData.delayLoadingFile) {
  35374. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35375. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35376. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35377. geometry._delayInfo = [];
  35378. if (parsedVertexData.hasUVs) {
  35379. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35380. }
  35381. if (parsedVertexData.hasUVs2) {
  35382. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35383. }
  35384. if (parsedVertexData.hasUVs3) {
  35385. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35386. }
  35387. if (parsedVertexData.hasUVs4) {
  35388. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35389. }
  35390. if (parsedVertexData.hasUVs5) {
  35391. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35392. }
  35393. if (parsedVertexData.hasUVs6) {
  35394. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35395. }
  35396. if (parsedVertexData.hasColors) {
  35397. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35398. }
  35399. if (parsedVertexData.hasMatricesIndices) {
  35400. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35401. }
  35402. if (parsedVertexData.hasMatricesWeights) {
  35403. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35404. }
  35405. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35406. }
  35407. else {
  35408. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35409. }
  35410. scene.pushGeometry(geometry, true);
  35411. return geometry;
  35412. };
  35413. return Geometry;
  35414. }());
  35415. BABYLON.Geometry = Geometry;
  35416. // Primitives
  35417. /// Abstract class
  35418. /**
  35419. * Abstract class used to provide common services for all typed geometries
  35420. */
  35421. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35422. __extends(_PrimitiveGeometry, _super);
  35423. /**
  35424. * Creates a new typed geometry
  35425. * @param id defines the unique ID of the geometry
  35426. * @param scene defines the hosting scene
  35427. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35428. * @param mesh defines the hosting mesh (can be null)
  35429. */
  35430. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35431. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35432. if (mesh === void 0) { mesh = null; }
  35433. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35434. _this._canBeRegenerated = _canBeRegenerated;
  35435. _this._beingRegenerated = true;
  35436. _this.regenerate();
  35437. _this._beingRegenerated = false;
  35438. return _this;
  35439. }
  35440. /**
  35441. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35442. * @returns true if the geometry can be regenerated
  35443. */
  35444. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35445. return this._canBeRegenerated;
  35446. };
  35447. /**
  35448. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35449. */
  35450. _PrimitiveGeometry.prototype.regenerate = function () {
  35451. if (!this._canBeRegenerated) {
  35452. return;
  35453. }
  35454. this._beingRegenerated = true;
  35455. this.setAllVerticesData(this._regenerateVertexData(), false);
  35456. this._beingRegenerated = false;
  35457. };
  35458. /**
  35459. * Clone the geometry
  35460. * @param id defines the unique ID of the new geometry
  35461. * @returns the new geometry
  35462. */
  35463. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35464. return _super.prototype.copy.call(this, id);
  35465. };
  35466. // overrides
  35467. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35468. if (!this._beingRegenerated) {
  35469. return;
  35470. }
  35471. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35472. };
  35473. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35474. if (!this._beingRegenerated) {
  35475. return;
  35476. }
  35477. _super.prototype.setVerticesData.call(this, kind, data, false);
  35478. };
  35479. // to override
  35480. /** @ignore */
  35481. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35482. throw new Error("Abstract method");
  35483. };
  35484. _PrimitiveGeometry.prototype.copy = function (id) {
  35485. throw new Error("Must be overriden in sub-classes.");
  35486. };
  35487. _PrimitiveGeometry.prototype.serialize = function () {
  35488. var serializationObject = _super.prototype.serialize.call(this);
  35489. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35490. return serializationObject;
  35491. };
  35492. return _PrimitiveGeometry;
  35493. }(Geometry));
  35494. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35495. /**
  35496. * Creates a ribbon geometry
  35497. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35498. */
  35499. var RibbonGeometry = /** @class */ (function (_super) {
  35500. __extends(RibbonGeometry, _super);
  35501. /**
  35502. * Creates a ribbon geometry
  35503. * @param id defines the unique ID of the geometry
  35504. * @param scene defines the hosting scene
  35505. * @param pathArray defines the array of paths to use
  35506. * @param closeArray defines if the last path and the first path must be joined
  35507. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35508. * @param offset defines the offset between points
  35509. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35510. * @param mesh defines the hosting mesh (can be null)
  35511. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35512. */
  35513. function RibbonGeometry(id, scene,
  35514. /**
  35515. * Defines the array of paths to use
  35516. */
  35517. pathArray,
  35518. /**
  35519. * Defines if the last and first points of each path in your pathArray must be joined
  35520. */
  35521. closeArray,
  35522. /**
  35523. * Defines if the last and first points of each path in your pathArray must be joined
  35524. */
  35525. closePath,
  35526. /**
  35527. * Defines the offset between points
  35528. */
  35529. offset, canBeRegenerated, mesh,
  35530. /**
  35531. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35532. */
  35533. side) {
  35534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35536. _this.pathArray = pathArray;
  35537. _this.closeArray = closeArray;
  35538. _this.closePath = closePath;
  35539. _this.offset = offset;
  35540. _this.side = side;
  35541. return _this;
  35542. }
  35543. /** @ignore */
  35544. RibbonGeometry.prototype._regenerateVertexData = function () {
  35545. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35546. };
  35547. RibbonGeometry.prototype.copy = function (id) {
  35548. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35549. };
  35550. return RibbonGeometry;
  35551. }(_PrimitiveGeometry));
  35552. BABYLON.RibbonGeometry = RibbonGeometry;
  35553. /**
  35554. * Creates a box geometry
  35555. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35556. */
  35557. var BoxGeometry = /** @class */ (function (_super) {
  35558. __extends(BoxGeometry, _super);
  35559. /**
  35560. * Creates a box geometry
  35561. * @param id defines the unique ID of the geometry
  35562. * @param scene defines the hosting scene
  35563. * @param size defines the zise of the box (width, height and depth are the same)
  35564. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35565. * @param mesh defines the hosting mesh (can be null)
  35566. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35567. */
  35568. function BoxGeometry(id, scene,
  35569. /**
  35570. * Defines the zise of the box (width, height and depth are the same)
  35571. */
  35572. size, canBeRegenerated, mesh,
  35573. /**
  35574. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35575. */
  35576. side) {
  35577. if (mesh === void 0) { mesh = null; }
  35578. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35579. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35580. _this.size = size;
  35581. _this.side = side;
  35582. return _this;
  35583. }
  35584. BoxGeometry.prototype._regenerateVertexData = function () {
  35585. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35586. };
  35587. BoxGeometry.prototype.copy = function (id) {
  35588. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35589. };
  35590. BoxGeometry.prototype.serialize = function () {
  35591. var serializationObject = _super.prototype.serialize.call(this);
  35592. serializationObject.size = this.size;
  35593. return serializationObject;
  35594. };
  35595. BoxGeometry.Parse = function (parsedBox, scene) {
  35596. if (scene.getGeometryByID(parsedBox.id)) {
  35597. return null; // null since geometry could be something else than a box...
  35598. }
  35599. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35600. if (BABYLON.Tags) {
  35601. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35602. }
  35603. scene.pushGeometry(box, true);
  35604. return box;
  35605. };
  35606. return BoxGeometry;
  35607. }(_PrimitiveGeometry));
  35608. BABYLON.BoxGeometry = BoxGeometry;
  35609. /**
  35610. * Creates a sphere geometry
  35611. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35612. */
  35613. var SphereGeometry = /** @class */ (function (_super) {
  35614. __extends(SphereGeometry, _super);
  35615. /**
  35616. * Create a new sphere geometry
  35617. * @param id defines the unique ID of the geometry
  35618. * @param scene defines the hosting scene
  35619. * @param segments defines the number of segments to use to create the sphere
  35620. * @param diameter defines the diameter of the sphere
  35621. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35622. * @param mesh defines the hosting mesh (can be null)
  35623. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35624. */
  35625. function SphereGeometry(id, scene,
  35626. /**
  35627. * Defines the number of segments to use to create the sphere
  35628. */
  35629. segments,
  35630. /**
  35631. * Defines the diameter of the sphere
  35632. */
  35633. diameter, canBeRegenerated, mesh,
  35634. /**
  35635. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35636. */
  35637. side) {
  35638. if (mesh === void 0) { mesh = null; }
  35639. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35640. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35641. _this.segments = segments;
  35642. _this.diameter = diameter;
  35643. _this.side = side;
  35644. return _this;
  35645. }
  35646. SphereGeometry.prototype._regenerateVertexData = function () {
  35647. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35648. };
  35649. SphereGeometry.prototype.copy = function (id) {
  35650. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35651. };
  35652. SphereGeometry.prototype.serialize = function () {
  35653. var serializationObject = _super.prototype.serialize.call(this);
  35654. serializationObject.segments = this.segments;
  35655. serializationObject.diameter = this.diameter;
  35656. return serializationObject;
  35657. };
  35658. SphereGeometry.Parse = function (parsedSphere, scene) {
  35659. if (scene.getGeometryByID(parsedSphere.id)) {
  35660. return null; // null since geometry could be something else than a sphere...
  35661. }
  35662. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35663. if (BABYLON.Tags) {
  35664. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35665. }
  35666. scene.pushGeometry(sphere, true);
  35667. return sphere;
  35668. };
  35669. return SphereGeometry;
  35670. }(_PrimitiveGeometry));
  35671. BABYLON.SphereGeometry = SphereGeometry;
  35672. /**
  35673. * Creates a disc geometry
  35674. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35675. */
  35676. var DiscGeometry = /** @class */ (function (_super) {
  35677. __extends(DiscGeometry, _super);
  35678. /**
  35679. * Creates a new disc geometry
  35680. * @param id defines the unique ID of the geometry
  35681. * @param scene defines the hosting scene
  35682. * @param radius defines the radius of the disc
  35683. * @param tessellation defines the tesselation factor to apply to the disc
  35684. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35685. * @param mesh defines the hosting mesh (can be null)
  35686. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35687. */
  35688. function DiscGeometry(id, scene,
  35689. /**
  35690. * Defines the radius of the disc
  35691. */
  35692. radius,
  35693. /**
  35694. * Defines the tesselation factor to apply to the disc
  35695. */
  35696. tessellation, canBeRegenerated, mesh,
  35697. /**
  35698. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35699. */
  35700. side) {
  35701. if (mesh === void 0) { mesh = null; }
  35702. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35703. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35704. _this.radius = radius;
  35705. _this.tessellation = tessellation;
  35706. _this.side = side;
  35707. return _this;
  35708. }
  35709. DiscGeometry.prototype._regenerateVertexData = function () {
  35710. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35711. };
  35712. DiscGeometry.prototype.copy = function (id) {
  35713. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35714. };
  35715. return DiscGeometry;
  35716. }(_PrimitiveGeometry));
  35717. BABYLON.DiscGeometry = DiscGeometry;
  35718. /**
  35719. * Creates a new cylinder geometry
  35720. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35721. */
  35722. var CylinderGeometry = /** @class */ (function (_super) {
  35723. __extends(CylinderGeometry, _super);
  35724. /**
  35725. * Creates a new cylinder geometry
  35726. * @param id defines the unique ID of the geometry
  35727. * @param scene defines the hosting scene
  35728. * @param height defines the height of the cylinder
  35729. * @param diameterTop defines the diameter of the cylinder's top cap
  35730. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35731. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35732. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35733. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35734. * @param mesh defines the hosting mesh (can be null)
  35735. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35736. */
  35737. function CylinderGeometry(id, scene,
  35738. /**
  35739. * Defines the height of the cylinder
  35740. */
  35741. height,
  35742. /**
  35743. * Defines the diameter of the cylinder's top cap
  35744. */
  35745. diameterTop,
  35746. /**
  35747. * Defines the diameter of the cylinder's bottom cap
  35748. */
  35749. diameterBottom,
  35750. /**
  35751. * Defines the tessellation factor to apply to the cylinder
  35752. */
  35753. tessellation,
  35754. /**
  35755. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35756. */
  35757. subdivisions, canBeRegenerated, mesh,
  35758. /**
  35759. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35760. */
  35761. side) {
  35762. if (subdivisions === void 0) { subdivisions = 1; }
  35763. if (mesh === void 0) { mesh = null; }
  35764. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35765. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35766. _this.height = height;
  35767. _this.diameterTop = diameterTop;
  35768. _this.diameterBottom = diameterBottom;
  35769. _this.tessellation = tessellation;
  35770. _this.subdivisions = subdivisions;
  35771. _this.side = side;
  35772. return _this;
  35773. }
  35774. CylinderGeometry.prototype._regenerateVertexData = function () {
  35775. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35776. };
  35777. CylinderGeometry.prototype.copy = function (id) {
  35778. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35779. };
  35780. CylinderGeometry.prototype.serialize = function () {
  35781. var serializationObject = _super.prototype.serialize.call(this);
  35782. serializationObject.height = this.height;
  35783. serializationObject.diameterTop = this.diameterTop;
  35784. serializationObject.diameterBottom = this.diameterBottom;
  35785. serializationObject.tessellation = this.tessellation;
  35786. return serializationObject;
  35787. };
  35788. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35789. if (scene.getGeometryByID(parsedCylinder.id)) {
  35790. return null; // null since geometry could be something else than a cylinder...
  35791. }
  35792. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35793. if (BABYLON.Tags) {
  35794. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35795. }
  35796. scene.pushGeometry(cylinder, true);
  35797. return cylinder;
  35798. };
  35799. return CylinderGeometry;
  35800. }(_PrimitiveGeometry));
  35801. BABYLON.CylinderGeometry = CylinderGeometry;
  35802. /**
  35803. * Creates a new torus geometry
  35804. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35805. */
  35806. var TorusGeometry = /** @class */ (function (_super) {
  35807. __extends(TorusGeometry, _super);
  35808. /**
  35809. * Creates a new torus geometry
  35810. * @param id defines the unique ID of the geometry
  35811. * @param scene defines the hosting scene
  35812. * @param diameter defines the diameter of the torus
  35813. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35814. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35815. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35816. * @param mesh defines the hosting mesh (can be null)
  35817. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35818. */
  35819. function TorusGeometry(id, scene,
  35820. /**
  35821. * Defines the diameter of the torus
  35822. */
  35823. diameter,
  35824. /**
  35825. * Defines the thickness of the torus (ie. internal diameter)
  35826. */
  35827. thickness,
  35828. /**
  35829. * Defines the tesselation factor to apply to the torus
  35830. */
  35831. tessellation, canBeRegenerated, mesh,
  35832. /**
  35833. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35834. */
  35835. side) {
  35836. if (mesh === void 0) { mesh = null; }
  35837. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35838. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35839. _this.diameter = diameter;
  35840. _this.thickness = thickness;
  35841. _this.tessellation = tessellation;
  35842. _this.side = side;
  35843. return _this;
  35844. }
  35845. TorusGeometry.prototype._regenerateVertexData = function () {
  35846. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35847. };
  35848. TorusGeometry.prototype.copy = function (id) {
  35849. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35850. };
  35851. TorusGeometry.prototype.serialize = function () {
  35852. var serializationObject = _super.prototype.serialize.call(this);
  35853. serializationObject.diameter = this.diameter;
  35854. serializationObject.thickness = this.thickness;
  35855. serializationObject.tessellation = this.tessellation;
  35856. return serializationObject;
  35857. };
  35858. TorusGeometry.Parse = function (parsedTorus, scene) {
  35859. if (scene.getGeometryByID(parsedTorus.id)) {
  35860. return null; // null since geometry could be something else than a torus...
  35861. }
  35862. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35863. if (BABYLON.Tags) {
  35864. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35865. }
  35866. scene.pushGeometry(torus, true);
  35867. return torus;
  35868. };
  35869. return TorusGeometry;
  35870. }(_PrimitiveGeometry));
  35871. BABYLON.TorusGeometry = TorusGeometry;
  35872. /**
  35873. * Creates a new ground geometry
  35874. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35875. */
  35876. var GroundGeometry = /** @class */ (function (_super) {
  35877. __extends(GroundGeometry, _super);
  35878. /**
  35879. * Creates a new ground geometry
  35880. * @param id defines the unique ID of the geometry
  35881. * @param scene defines the hosting scene
  35882. * @param width defines the width of the ground
  35883. * @param height defines the height of the ground
  35884. * @param subdivisions defines the subdivisions to apply to the ground
  35885. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35886. * @param mesh defines the hosting mesh (can be null)
  35887. */
  35888. function GroundGeometry(id, scene,
  35889. /**
  35890. * Defines the width of the ground
  35891. */
  35892. width,
  35893. /**
  35894. * Defines the height of the ground
  35895. */
  35896. height,
  35897. /**
  35898. * Defines the subdivisions to apply to the ground
  35899. */
  35900. subdivisions, canBeRegenerated, mesh) {
  35901. if (mesh === void 0) { mesh = null; }
  35902. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35903. _this.width = width;
  35904. _this.height = height;
  35905. _this.subdivisions = subdivisions;
  35906. return _this;
  35907. }
  35908. GroundGeometry.prototype._regenerateVertexData = function () {
  35909. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35910. };
  35911. GroundGeometry.prototype.copy = function (id) {
  35912. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35913. };
  35914. GroundGeometry.prototype.serialize = function () {
  35915. var serializationObject = _super.prototype.serialize.call(this);
  35916. serializationObject.width = this.width;
  35917. serializationObject.height = this.height;
  35918. serializationObject.subdivisions = this.subdivisions;
  35919. return serializationObject;
  35920. };
  35921. GroundGeometry.Parse = function (parsedGround, scene) {
  35922. if (scene.getGeometryByID(parsedGround.id)) {
  35923. return null; // null since geometry could be something else than a ground...
  35924. }
  35925. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35926. if (BABYLON.Tags) {
  35927. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35928. }
  35929. scene.pushGeometry(ground, true);
  35930. return ground;
  35931. };
  35932. return GroundGeometry;
  35933. }(_PrimitiveGeometry));
  35934. BABYLON.GroundGeometry = GroundGeometry;
  35935. /**
  35936. * Creates a tiled ground geometry
  35937. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35938. */
  35939. var TiledGroundGeometry = /** @class */ (function (_super) {
  35940. __extends(TiledGroundGeometry, _super);
  35941. /**
  35942. * Creates a tiled ground geometry
  35943. * @param id defines the unique ID of the geometry
  35944. * @param scene defines the hosting scene
  35945. * @param xmin defines the minimum value on X axis
  35946. * @param zmin defines the minimum value on Z axis
  35947. * @param xmax defines the maximum value on X axis
  35948. * @param zmax defines the maximum value on Z axis
  35949. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35950. * @param precision defines the precision to use when computing the tiles
  35951. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35952. * @param mesh defines the hosting mesh (can be null)
  35953. */
  35954. function TiledGroundGeometry(id, scene,
  35955. /**
  35956. * Defines the minimum value on X axis
  35957. */
  35958. xmin,
  35959. /**
  35960. * Defines the minimum value on Z axis
  35961. */
  35962. zmin,
  35963. /**
  35964. * Defines the maximum value on X axis
  35965. */
  35966. xmax,
  35967. /**
  35968. * Defines the maximum value on Z axis
  35969. */
  35970. zmax,
  35971. /**
  35972. * Defines the subdivisions to apply to the ground
  35973. */
  35974. subdivisions,
  35975. /**
  35976. * Defines the precision to use when computing the tiles
  35977. */
  35978. precision, canBeRegenerated, mesh) {
  35979. if (mesh === void 0) { mesh = null; }
  35980. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35981. _this.xmin = xmin;
  35982. _this.zmin = zmin;
  35983. _this.xmax = xmax;
  35984. _this.zmax = zmax;
  35985. _this.subdivisions = subdivisions;
  35986. _this.precision = precision;
  35987. return _this;
  35988. }
  35989. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35990. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35991. };
  35992. TiledGroundGeometry.prototype.copy = function (id) {
  35993. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35994. };
  35995. return TiledGroundGeometry;
  35996. }(_PrimitiveGeometry));
  35997. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35998. /**
  35999. * Creates a plane geometry
  36000. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36001. */
  36002. var PlaneGeometry = /** @class */ (function (_super) {
  36003. __extends(PlaneGeometry, _super);
  36004. /**
  36005. * Creates a plane geometry
  36006. * @param id defines the unique ID of the geometry
  36007. * @param scene defines the hosting scene
  36008. * @param size defines the size of the plane (width === height)
  36009. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36010. * @param mesh defines the hosting mesh (can be null)
  36011. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36012. */
  36013. function PlaneGeometry(id, scene,
  36014. /**
  36015. * Defines the size of the plane (width === height)
  36016. */
  36017. size, canBeRegenerated, mesh,
  36018. /**
  36019. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36020. */
  36021. side) {
  36022. if (mesh === void 0) { mesh = null; }
  36023. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36024. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36025. _this.size = size;
  36026. _this.side = side;
  36027. return _this;
  36028. }
  36029. PlaneGeometry.prototype._regenerateVertexData = function () {
  36030. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36031. };
  36032. PlaneGeometry.prototype.copy = function (id) {
  36033. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36034. };
  36035. PlaneGeometry.prototype.serialize = function () {
  36036. var serializationObject = _super.prototype.serialize.call(this);
  36037. serializationObject.size = this.size;
  36038. return serializationObject;
  36039. };
  36040. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36041. if (scene.getGeometryByID(parsedPlane.id)) {
  36042. return null; // null since geometry could be something else than a ground...
  36043. }
  36044. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36045. if (BABYLON.Tags) {
  36046. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36047. }
  36048. scene.pushGeometry(plane, true);
  36049. return plane;
  36050. };
  36051. return PlaneGeometry;
  36052. }(_PrimitiveGeometry));
  36053. BABYLON.PlaneGeometry = PlaneGeometry;
  36054. /**
  36055. * Creates a torus knot geometry
  36056. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36057. */
  36058. var TorusKnotGeometry = /** @class */ (function (_super) {
  36059. __extends(TorusKnotGeometry, _super);
  36060. /**
  36061. * Creates a torus knot geometry
  36062. * @param id defines the unique ID of the geometry
  36063. * @param scene defines the hosting scene
  36064. * @param radius defines the radius of the torus knot
  36065. * @param tube defines the thickness of the torus knot tube
  36066. * @param radialSegments defines the number of radial segments
  36067. * @param tubularSegments defines the number of tubular segments
  36068. * @param p defines the first number of windings
  36069. * @param q defines the second number of windings
  36070. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36071. * @param mesh defines the hosting mesh (can be null)
  36072. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36073. */
  36074. function TorusKnotGeometry(id, scene,
  36075. /**
  36076. * Defines the radius of the torus knot
  36077. */
  36078. radius,
  36079. /**
  36080. * Defines the thickness of the torus knot tube
  36081. */
  36082. tube,
  36083. /**
  36084. * Defines the number of radial segments
  36085. */
  36086. radialSegments,
  36087. /**
  36088. * Defines the number of tubular segments
  36089. */
  36090. tubularSegments,
  36091. /**
  36092. * Defines the first number of windings
  36093. */
  36094. p,
  36095. /**
  36096. * Defines the second number of windings
  36097. */
  36098. q, canBeRegenerated, mesh,
  36099. /**
  36100. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36101. */
  36102. side) {
  36103. if (mesh === void 0) { mesh = null; }
  36104. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36105. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36106. _this.radius = radius;
  36107. _this.tube = tube;
  36108. _this.radialSegments = radialSegments;
  36109. _this.tubularSegments = tubularSegments;
  36110. _this.p = p;
  36111. _this.q = q;
  36112. _this.side = side;
  36113. return _this;
  36114. }
  36115. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36116. 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 });
  36117. };
  36118. TorusKnotGeometry.prototype.copy = function (id) {
  36119. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36120. };
  36121. TorusKnotGeometry.prototype.serialize = function () {
  36122. var serializationObject = _super.prototype.serialize.call(this);
  36123. serializationObject.radius = this.radius;
  36124. serializationObject.tube = this.tube;
  36125. serializationObject.radialSegments = this.radialSegments;
  36126. serializationObject.tubularSegments = this.tubularSegments;
  36127. serializationObject.p = this.p;
  36128. serializationObject.q = this.q;
  36129. return serializationObject;
  36130. };
  36131. ;
  36132. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36133. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36134. return null; // null since geometry could be something else than a ground...
  36135. }
  36136. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36137. if (BABYLON.Tags) {
  36138. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36139. }
  36140. scene.pushGeometry(torusKnot, true);
  36141. return torusKnot;
  36142. };
  36143. return TorusKnotGeometry;
  36144. }(_PrimitiveGeometry));
  36145. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36146. //}
  36147. })(BABYLON || (BABYLON = {}));
  36148. //# sourceMappingURL=babylon.geometry.js.map
  36149. var BABYLON;
  36150. (function (BABYLON) {
  36151. /**
  36152. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36153. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36154. */
  36155. var PostProcessManager = /** @class */ (function () {
  36156. /**
  36157. * Creates a new instance of @see PostProcess
  36158. * @param scene The scene that the post process is associated with.
  36159. */
  36160. function PostProcessManager(scene) {
  36161. this._vertexBuffers = {};
  36162. this._scene = scene;
  36163. }
  36164. PostProcessManager.prototype._prepareBuffers = function () {
  36165. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36166. return;
  36167. }
  36168. // VBO
  36169. var vertices = [];
  36170. vertices.push(1, 1);
  36171. vertices.push(-1, 1);
  36172. vertices.push(-1, -1);
  36173. vertices.push(1, -1);
  36174. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36175. this._buildIndexBuffer();
  36176. };
  36177. PostProcessManager.prototype._buildIndexBuffer = function () {
  36178. // Indices
  36179. var indices = [];
  36180. indices.push(0);
  36181. indices.push(1);
  36182. indices.push(2);
  36183. indices.push(0);
  36184. indices.push(2);
  36185. indices.push(3);
  36186. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36187. };
  36188. /**
  36189. * Rebuilds the vertex buffers of the manager.
  36190. */
  36191. PostProcessManager.prototype._rebuild = function () {
  36192. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36193. if (!vb) {
  36194. return;
  36195. }
  36196. vb._rebuild();
  36197. this._buildIndexBuffer();
  36198. };
  36199. // Methods
  36200. /**
  36201. * Prepares a frame to be run through a post process.
  36202. * @param sourceTexture The input texture to the post procesess. (default: null)
  36203. * @param postProcesses An array of post processes to be run. (default: null)
  36204. * @returns True if the post processes were able to be run.
  36205. */
  36206. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36207. if (sourceTexture === void 0) { sourceTexture = null; }
  36208. if (postProcesses === void 0) { postProcesses = null; }
  36209. var camera = this._scene.activeCamera;
  36210. if (!camera) {
  36211. return false;
  36212. }
  36213. var postProcesses = postProcesses || camera._postProcesses;
  36214. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36215. return false;
  36216. }
  36217. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36218. return true;
  36219. };
  36220. /**
  36221. * Manually render a set of post processes to a texture.
  36222. * @param postProcesses An array of post processes to be run.
  36223. * @param targetTexture The target texture to render to.
  36224. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36225. */
  36226. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36227. if (targetTexture === void 0) { targetTexture = null; }
  36228. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36229. var engine = this._scene.getEngine();
  36230. for (var index = 0; index < postProcesses.length; index++) {
  36231. if (index < postProcesses.length - 1) {
  36232. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36233. }
  36234. else {
  36235. if (targetTexture) {
  36236. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36237. }
  36238. else {
  36239. engine.restoreDefaultFramebuffer();
  36240. }
  36241. }
  36242. var pp = postProcesses[index];
  36243. var effect = pp.apply();
  36244. if (effect) {
  36245. pp.onBeforeRenderObservable.notifyObservers(effect);
  36246. // VBOs
  36247. this._prepareBuffers();
  36248. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36249. // Draw order
  36250. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36251. pp.onAfterRenderObservable.notifyObservers(effect);
  36252. }
  36253. }
  36254. // Restore depth buffer
  36255. engine.setDepthBuffer(true);
  36256. engine.setDepthWrite(true);
  36257. };
  36258. /**
  36259. * Finalize the result of the output of the postprocesses.
  36260. * @param doNotPresent If true the result will not be displayed to the screen.
  36261. * @param targetTexture The target texture to render to.
  36262. * @param faceIndex The index of the face to bind the target texture to.
  36263. * @param postProcesses The array of post processes to render.
  36264. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36265. */
  36266. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36267. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36268. var camera = this._scene.activeCamera;
  36269. if (!camera) {
  36270. return;
  36271. }
  36272. postProcesses = postProcesses || camera._postProcesses;
  36273. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36274. return;
  36275. }
  36276. var engine = this._scene.getEngine();
  36277. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36278. if (index < len - 1) {
  36279. postProcesses[index + 1].activate(camera, targetTexture);
  36280. }
  36281. else {
  36282. if (targetTexture) {
  36283. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36284. }
  36285. else {
  36286. engine.restoreDefaultFramebuffer();
  36287. }
  36288. }
  36289. if (doNotPresent) {
  36290. break;
  36291. }
  36292. var pp = postProcesses[index];
  36293. var effect = pp.apply();
  36294. if (effect) {
  36295. pp.onBeforeRenderObservable.notifyObservers(effect);
  36296. // VBOs
  36297. this._prepareBuffers();
  36298. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36299. // Draw order
  36300. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36301. pp.onAfterRenderObservable.notifyObservers(effect);
  36302. }
  36303. }
  36304. // Restore states
  36305. engine.setDepthBuffer(true);
  36306. engine.setDepthWrite(true);
  36307. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36308. };
  36309. /**
  36310. * Disposes of the post process manager.
  36311. */
  36312. PostProcessManager.prototype.dispose = function () {
  36313. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36314. if (buffer) {
  36315. buffer.dispose();
  36316. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36317. }
  36318. if (this._indexBuffer) {
  36319. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36320. this._indexBuffer = null;
  36321. }
  36322. };
  36323. return PostProcessManager;
  36324. }());
  36325. BABYLON.PostProcessManager = PostProcessManager;
  36326. })(BABYLON || (BABYLON = {}));
  36327. //# sourceMappingURL=babylon.postProcessManager.js.map
  36328. var BABYLON;
  36329. (function (BABYLON) {
  36330. /**
  36331. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36332. */
  36333. var PerformanceMonitor = /** @class */ (function () {
  36334. /**
  36335. * constructor
  36336. * @param frameSampleSize The number of samples required to saturate the sliding window
  36337. */
  36338. function PerformanceMonitor(frameSampleSize) {
  36339. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36340. this._enabled = true;
  36341. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36342. }
  36343. /**
  36344. * Samples current frame
  36345. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36346. */
  36347. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36348. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36349. if (!this._enabled)
  36350. return;
  36351. if (this._lastFrameTimeMs != null) {
  36352. var dt = timeMs - this._lastFrameTimeMs;
  36353. this._rollingFrameTime.add(dt);
  36354. }
  36355. this._lastFrameTimeMs = timeMs;
  36356. };
  36357. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36358. /**
  36359. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36360. * @return Average frame time in milliseconds
  36361. */
  36362. get: function () {
  36363. return this._rollingFrameTime.average;
  36364. },
  36365. enumerable: true,
  36366. configurable: true
  36367. });
  36368. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36369. /**
  36370. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36371. * @return Frame time variance in milliseconds squared
  36372. */
  36373. get: function () {
  36374. return this._rollingFrameTime.variance;
  36375. },
  36376. enumerable: true,
  36377. configurable: true
  36378. });
  36379. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36380. /**
  36381. * Returns the frame time of the most recent frame
  36382. * @return Frame time in milliseconds
  36383. */
  36384. get: function () {
  36385. return this._rollingFrameTime.history(0);
  36386. },
  36387. enumerable: true,
  36388. configurable: true
  36389. });
  36390. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36391. /**
  36392. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36393. * @return Framerate in frames per second
  36394. */
  36395. get: function () {
  36396. return 1000.0 / this._rollingFrameTime.average;
  36397. },
  36398. enumerable: true,
  36399. configurable: true
  36400. });
  36401. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36402. /**
  36403. * Returns the average framerate in frames per second using the most recent frame time
  36404. * @return Framerate in frames per second
  36405. */
  36406. get: function () {
  36407. var history = this._rollingFrameTime.history(0);
  36408. if (history === 0) {
  36409. return 0;
  36410. }
  36411. return 1000.0 / history;
  36412. },
  36413. enumerable: true,
  36414. configurable: true
  36415. });
  36416. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36417. /**
  36418. * Returns true if enough samples have been taken to completely fill the sliding window
  36419. * @return true if saturated
  36420. */
  36421. get: function () {
  36422. return this._rollingFrameTime.isSaturated();
  36423. },
  36424. enumerable: true,
  36425. configurable: true
  36426. });
  36427. /**
  36428. * Enables contributions to the sliding window sample set
  36429. */
  36430. PerformanceMonitor.prototype.enable = function () {
  36431. this._enabled = true;
  36432. };
  36433. /**
  36434. * Disables contributions to the sliding window sample set
  36435. * Samples will not be interpolated over the disabled period
  36436. */
  36437. PerformanceMonitor.prototype.disable = function () {
  36438. this._enabled = false;
  36439. //clear last sample to avoid interpolating over the disabled period when next enabled
  36440. this._lastFrameTimeMs = null;
  36441. };
  36442. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36443. /**
  36444. * Returns true if sampling is enabled
  36445. * @return true if enabled
  36446. */
  36447. get: function () {
  36448. return this._enabled;
  36449. },
  36450. enumerable: true,
  36451. configurable: true
  36452. });
  36453. /**
  36454. * Resets performance monitor
  36455. */
  36456. PerformanceMonitor.prototype.reset = function () {
  36457. //clear last sample to avoid interpolating over the disabled period when next enabled
  36458. this._lastFrameTimeMs = null;
  36459. //wipe record
  36460. this._rollingFrameTime.reset();
  36461. };
  36462. return PerformanceMonitor;
  36463. }());
  36464. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36465. /**
  36466. * RollingAverage
  36467. *
  36468. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36469. */
  36470. var RollingAverage = /** @class */ (function () {
  36471. /**
  36472. * constructor
  36473. * @param length The number of samples required to saturate the sliding window
  36474. */
  36475. function RollingAverage(length) {
  36476. this._samples = new Array(length);
  36477. this.reset();
  36478. }
  36479. /**
  36480. * Adds a sample to the sample set
  36481. * @param v The sample value
  36482. */
  36483. RollingAverage.prototype.add = function (v) {
  36484. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36485. var delta;
  36486. //we need to check if we've already wrapped round
  36487. if (this.isSaturated()) {
  36488. //remove bottom of stack from mean
  36489. var bottomValue = this._samples[this._pos];
  36490. delta = bottomValue - this.average;
  36491. this.average -= delta / (this._sampleCount - 1);
  36492. this._m2 -= delta * (bottomValue - this.average);
  36493. }
  36494. else {
  36495. this._sampleCount++;
  36496. }
  36497. //add new value to mean
  36498. delta = v - this.average;
  36499. this.average += delta / (this._sampleCount);
  36500. this._m2 += delta * (v - this.average);
  36501. //set the new variance
  36502. this.variance = this._m2 / (this._sampleCount - 1);
  36503. this._samples[this._pos] = v;
  36504. this._pos++;
  36505. this._pos %= this._samples.length; //positive wrap around
  36506. };
  36507. /**
  36508. * Returns previously added values or null if outside of history or outside the sliding window domain
  36509. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36510. * @return Value previously recorded with add() or null if outside of range
  36511. */
  36512. RollingAverage.prototype.history = function (i) {
  36513. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36514. return 0;
  36515. }
  36516. var i0 = this._wrapPosition(this._pos - 1.0);
  36517. return this._samples[this._wrapPosition(i0 - i)];
  36518. };
  36519. /**
  36520. * Returns true if enough samples have been taken to completely fill the sliding window
  36521. * @return true if sample-set saturated
  36522. */
  36523. RollingAverage.prototype.isSaturated = function () {
  36524. return this._sampleCount >= this._samples.length;
  36525. };
  36526. /**
  36527. * Resets the rolling average (equivalent to 0 samples taken so far)
  36528. */
  36529. RollingAverage.prototype.reset = function () {
  36530. this.average = 0;
  36531. this.variance = 0;
  36532. this._sampleCount = 0;
  36533. this._pos = 0;
  36534. this._m2 = 0;
  36535. };
  36536. /**
  36537. * Wraps a value around the sample range boundaries
  36538. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36539. * @return Wrapped position in sample range
  36540. */
  36541. RollingAverage.prototype._wrapPosition = function (i) {
  36542. var max = this._samples.length;
  36543. return ((i % max) + max) % max;
  36544. };
  36545. return RollingAverage;
  36546. }());
  36547. BABYLON.RollingAverage = RollingAverage;
  36548. })(BABYLON || (BABYLON = {}));
  36549. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36550. var BABYLON;
  36551. (function (BABYLON) {
  36552. /**
  36553. * This groups together the common properties used for image processing either in direct forward pass
  36554. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36555. * or not.
  36556. */
  36557. var ImageProcessingConfiguration = /** @class */ (function () {
  36558. function ImageProcessingConfiguration() {
  36559. /**
  36560. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36561. */
  36562. this.colorCurves = new BABYLON.ColorCurves();
  36563. this._colorCurvesEnabled = false;
  36564. this._colorGradingEnabled = false;
  36565. this._colorGradingWithGreenDepth = true;
  36566. this._colorGradingBGR = true;
  36567. this._exposure = 1.0;
  36568. this._toneMappingEnabled = false;
  36569. this._contrast = 1.0;
  36570. /**
  36571. * Vignette stretch size.
  36572. */
  36573. this.vignetteStretch = 0;
  36574. /**
  36575. * Vignette centre X Offset.
  36576. */
  36577. this.vignetteCentreX = 0;
  36578. /**
  36579. * Vignette centre Y Offset.
  36580. */
  36581. this.vignetteCentreY = 0;
  36582. /**
  36583. * Vignette weight or intensity of the vignette effect.
  36584. */
  36585. this.vignetteWeight = 1.5;
  36586. /**
  36587. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36588. * if vignetteEnabled is set to true.
  36589. */
  36590. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36591. /**
  36592. * Camera field of view used by the Vignette effect.
  36593. */
  36594. this.vignetteCameraFov = 0.5;
  36595. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36596. this._vignetteEnabled = false;
  36597. this._applyByPostProcess = false;
  36598. this._isEnabled = true;
  36599. /**
  36600. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36601. * @type {BABYLON.Observable}
  36602. */
  36603. this.onUpdateParameters = new BABYLON.Observable();
  36604. }
  36605. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36606. /**
  36607. * Gets wether the color curves effect is enabled.
  36608. */
  36609. get: function () {
  36610. return this._colorCurvesEnabled;
  36611. },
  36612. /**
  36613. * Sets wether the color curves effect is enabled.
  36614. */
  36615. set: function (value) {
  36616. if (this._colorCurvesEnabled === value) {
  36617. return;
  36618. }
  36619. this._colorCurvesEnabled = value;
  36620. this._updateParameters();
  36621. },
  36622. enumerable: true,
  36623. configurable: true
  36624. });
  36625. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36626. /**
  36627. * Gets wether the color grading effect is enabled.
  36628. */
  36629. get: function () {
  36630. return this._colorGradingEnabled;
  36631. },
  36632. /**
  36633. * Sets wether the color grading effect is enabled.
  36634. */
  36635. set: function (value) {
  36636. if (this._colorGradingEnabled === value) {
  36637. return;
  36638. }
  36639. this._colorGradingEnabled = value;
  36640. this._updateParameters();
  36641. },
  36642. enumerable: true,
  36643. configurable: true
  36644. });
  36645. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36646. /**
  36647. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36648. */
  36649. get: function () {
  36650. return this._colorGradingWithGreenDepth;
  36651. },
  36652. /**
  36653. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36654. */
  36655. set: function (value) {
  36656. if (this._colorGradingWithGreenDepth === value) {
  36657. return;
  36658. }
  36659. this._colorGradingWithGreenDepth = value;
  36660. this._updateParameters();
  36661. },
  36662. enumerable: true,
  36663. configurable: true
  36664. });
  36665. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36666. /**
  36667. * Gets wether the color grading texture contains BGR values.
  36668. */
  36669. get: function () {
  36670. return this._colorGradingBGR;
  36671. },
  36672. /**
  36673. * Sets wether the color grading texture contains BGR values.
  36674. */
  36675. set: function (value) {
  36676. if (this._colorGradingBGR === value) {
  36677. return;
  36678. }
  36679. this._colorGradingBGR = value;
  36680. this._updateParameters();
  36681. },
  36682. enumerable: true,
  36683. configurable: true
  36684. });
  36685. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36686. /**
  36687. * Gets the Exposure used in the effect.
  36688. */
  36689. get: function () {
  36690. return this._exposure;
  36691. },
  36692. /**
  36693. * Sets the Exposure used in the effect.
  36694. */
  36695. set: function (value) {
  36696. if (this._exposure === value) {
  36697. return;
  36698. }
  36699. this._exposure = value;
  36700. this._updateParameters();
  36701. },
  36702. enumerable: true,
  36703. configurable: true
  36704. });
  36705. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36706. /**
  36707. * Gets wether the tone mapping effect is enabled.
  36708. */
  36709. get: function () {
  36710. return this._toneMappingEnabled;
  36711. },
  36712. /**
  36713. * Sets wether the tone mapping effect is enabled.
  36714. */
  36715. set: function (value) {
  36716. if (this._toneMappingEnabled === value) {
  36717. return;
  36718. }
  36719. this._toneMappingEnabled = value;
  36720. this._updateParameters();
  36721. },
  36722. enumerable: true,
  36723. configurable: true
  36724. });
  36725. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36726. /**
  36727. * Gets the contrast used in the effect.
  36728. */
  36729. get: function () {
  36730. return this._contrast;
  36731. },
  36732. /**
  36733. * Sets the contrast used in the effect.
  36734. */
  36735. set: function (value) {
  36736. if (this._contrast === value) {
  36737. return;
  36738. }
  36739. this._contrast = value;
  36740. this._updateParameters();
  36741. },
  36742. enumerable: true,
  36743. configurable: true
  36744. });
  36745. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36746. /**
  36747. * Gets the vignette blend mode allowing different kind of effect.
  36748. */
  36749. get: function () {
  36750. return this._vignetteBlendMode;
  36751. },
  36752. /**
  36753. * Sets the vignette blend mode allowing different kind of effect.
  36754. */
  36755. set: function (value) {
  36756. if (this._vignetteBlendMode === value) {
  36757. return;
  36758. }
  36759. this._vignetteBlendMode = value;
  36760. this._updateParameters();
  36761. },
  36762. enumerable: true,
  36763. configurable: true
  36764. });
  36765. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36766. /**
  36767. * Gets wether the vignette effect is enabled.
  36768. */
  36769. get: function () {
  36770. return this._vignetteEnabled;
  36771. },
  36772. /**
  36773. * Sets wether the vignette effect is enabled.
  36774. */
  36775. set: function (value) {
  36776. if (this._vignetteEnabled === value) {
  36777. return;
  36778. }
  36779. this._vignetteEnabled = value;
  36780. this._updateParameters();
  36781. },
  36782. enumerable: true,
  36783. configurable: true
  36784. });
  36785. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36786. /**
  36787. * Gets wether the image processing is applied through a post process or not.
  36788. */
  36789. get: function () {
  36790. return this._applyByPostProcess;
  36791. },
  36792. /**
  36793. * Sets wether the image processing is applied through a post process or not.
  36794. */
  36795. set: function (value) {
  36796. if (this._applyByPostProcess === value) {
  36797. return;
  36798. }
  36799. this._applyByPostProcess = value;
  36800. this._updateParameters();
  36801. },
  36802. enumerable: true,
  36803. configurable: true
  36804. });
  36805. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36806. /**
  36807. * Gets wether the image processing is enabled or not.
  36808. */
  36809. get: function () {
  36810. return this._isEnabled;
  36811. },
  36812. /**
  36813. * Sets wether the image processing is enabled or not.
  36814. */
  36815. set: function (value) {
  36816. if (this._isEnabled === value) {
  36817. return;
  36818. }
  36819. this._isEnabled = value;
  36820. this._updateParameters();
  36821. },
  36822. enumerable: true,
  36823. configurable: true
  36824. });
  36825. /**
  36826. * Method called each time the image processing information changes requires to recompile the effect.
  36827. */
  36828. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36829. this.onUpdateParameters.notifyObservers(this);
  36830. };
  36831. ImageProcessingConfiguration.prototype.getClassName = function () {
  36832. return "ImageProcessingConfiguration";
  36833. };
  36834. /**
  36835. * Prepare the list of uniforms associated with the Image Processing effects.
  36836. * @param uniformsList The list of uniforms used in the effect
  36837. * @param defines the list of defines currently in use
  36838. */
  36839. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36840. if (defines.EXPOSURE) {
  36841. uniforms.push("exposureLinear");
  36842. }
  36843. if (defines.CONTRAST) {
  36844. uniforms.push("contrast");
  36845. }
  36846. if (defines.COLORGRADING) {
  36847. uniforms.push("colorTransformSettings");
  36848. }
  36849. if (defines.VIGNETTE) {
  36850. uniforms.push("vInverseScreenSize");
  36851. uniforms.push("vignetteSettings1");
  36852. uniforms.push("vignetteSettings2");
  36853. }
  36854. if (defines.COLORCURVES) {
  36855. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36856. }
  36857. };
  36858. /**
  36859. * Prepare the list of samplers associated with the Image Processing effects.
  36860. * @param uniformsList The list of uniforms used in the effect
  36861. * @param defines the list of defines currently in use
  36862. */
  36863. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36864. if (defines.COLORGRADING) {
  36865. samplersList.push("txColorTransform");
  36866. }
  36867. };
  36868. /**
  36869. * Prepare the list of defines associated to the shader.
  36870. * @param defines the list of defines to complete
  36871. */
  36872. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36873. if (forPostProcess === void 0) { forPostProcess = false; }
  36874. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36875. defines.VIGNETTE = false;
  36876. defines.TONEMAPPING = false;
  36877. defines.CONTRAST = false;
  36878. defines.EXPOSURE = false;
  36879. defines.COLORCURVES = false;
  36880. defines.COLORGRADING = false;
  36881. defines.COLORGRADING3D = false;
  36882. defines.IMAGEPROCESSING = false;
  36883. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36884. return;
  36885. }
  36886. defines.VIGNETTE = this.vignetteEnabled;
  36887. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36888. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36889. defines.TONEMAPPING = this.toneMappingEnabled;
  36890. defines.CONTRAST = (this.contrast !== 1.0);
  36891. defines.EXPOSURE = (this.exposure !== 1.0);
  36892. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36893. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36894. if (defines.COLORGRADING) {
  36895. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36896. }
  36897. else {
  36898. defines.COLORGRADING3D = false;
  36899. }
  36900. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36901. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36902. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36903. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36904. };
  36905. /**
  36906. * Returns true if all the image processing information are ready.
  36907. */
  36908. ImageProcessingConfiguration.prototype.isReady = function () {
  36909. // Color Grading texure can not be none blocking.
  36910. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36911. };
  36912. /**
  36913. * Binds the image processing to the shader.
  36914. * @param effect The effect to bind to
  36915. */
  36916. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36917. if (aspectRatio === void 0) { aspectRatio = 1; }
  36918. // Color Curves
  36919. if (this._colorCurvesEnabled && this.colorCurves) {
  36920. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36921. }
  36922. // Vignette
  36923. if (this._vignetteEnabled) {
  36924. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36925. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36926. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36927. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36928. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36929. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36930. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36931. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36932. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36933. var vignettePower = -2.0 * this.vignetteWeight;
  36934. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36935. }
  36936. // Exposure
  36937. effect.setFloat("exposureLinear", this.exposure);
  36938. // Contrast
  36939. effect.setFloat("contrast", this.contrast);
  36940. // Color transform settings
  36941. if (this.colorGradingTexture) {
  36942. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36943. var textureSize = this.colorGradingTexture.getSize().height;
  36944. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36945. 0.5 / textureSize, // textureOffset
  36946. textureSize, // textureSize
  36947. this.colorGradingTexture.level // weight
  36948. );
  36949. }
  36950. };
  36951. /**
  36952. * Clones the current image processing instance.
  36953. * @return The cloned image processing
  36954. */
  36955. ImageProcessingConfiguration.prototype.clone = function () {
  36956. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36957. };
  36958. /**
  36959. * Serializes the current image processing instance to a json representation.
  36960. * @return a JSON representation
  36961. */
  36962. ImageProcessingConfiguration.prototype.serialize = function () {
  36963. return BABYLON.SerializationHelper.Serialize(this);
  36964. };
  36965. /**
  36966. * Parses the image processing from a json representation.
  36967. * @param source the JSON source to parse
  36968. * @return The parsed image processing
  36969. */
  36970. ImageProcessingConfiguration.Parse = function (source) {
  36971. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36972. };
  36973. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36974. /**
  36975. * Used to apply the vignette as a mix with the pixel color.
  36976. */
  36977. get: function () {
  36978. return this._VIGNETTEMODE_MULTIPLY;
  36979. },
  36980. enumerable: true,
  36981. configurable: true
  36982. });
  36983. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36984. /**
  36985. * Used to apply the vignette as a replacement of the pixel color.
  36986. */
  36987. get: function () {
  36988. return this._VIGNETTEMODE_OPAQUE;
  36989. },
  36990. enumerable: true,
  36991. configurable: true
  36992. });
  36993. // Static constants associated to the image processing.
  36994. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36995. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36996. __decorate([
  36997. BABYLON.serializeAsColorCurves()
  36998. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36999. __decorate([
  37000. BABYLON.serialize()
  37001. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37002. __decorate([
  37003. BABYLON.serializeAsTexture()
  37004. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37005. __decorate([
  37006. BABYLON.serialize()
  37007. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37008. __decorate([
  37009. BABYLON.serialize()
  37010. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37011. __decorate([
  37012. BABYLON.serialize()
  37013. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37014. __decorate([
  37015. BABYLON.serialize()
  37016. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37017. __decorate([
  37018. BABYLON.serialize()
  37019. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37020. __decorate([
  37021. BABYLON.serialize()
  37022. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37023. __decorate([
  37024. BABYLON.serialize()
  37025. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37026. __decorate([
  37027. BABYLON.serialize()
  37028. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37029. __decorate([
  37030. BABYLON.serialize()
  37031. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37032. __decorate([
  37033. BABYLON.serialize()
  37034. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37035. __decorate([
  37036. BABYLON.serializeAsColor4()
  37037. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37038. __decorate([
  37039. BABYLON.serialize()
  37040. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37041. __decorate([
  37042. BABYLON.serialize()
  37043. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37044. __decorate([
  37045. BABYLON.serialize()
  37046. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  37047. __decorate([
  37048. BABYLON.serialize()
  37049. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  37050. __decorate([
  37051. BABYLON.serialize()
  37052. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  37053. return ImageProcessingConfiguration;
  37054. }());
  37055. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  37056. })(BABYLON || (BABYLON = {}));
  37057. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  37058. var BABYLON;
  37059. (function (BABYLON) {
  37060. /**
  37061. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  37062. * It can help converting any input color in a desired output one. This can then be used to create effects
  37063. * from sepia, black and white to sixties or futuristic rendering...
  37064. *
  37065. * The only supported format is currently 3dl.
  37066. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  37067. */
  37068. var ColorGradingTexture = /** @class */ (function (_super) {
  37069. __extends(ColorGradingTexture, _super);
  37070. /**
  37071. * Instantiates a ColorGradingTexture from the following parameters.
  37072. *
  37073. * @param url The location of the color gradind data (currently only supporting 3dl)
  37074. * @param scene The scene the texture will be used in
  37075. */
  37076. function ColorGradingTexture(url, scene) {
  37077. var _this = _super.call(this, scene) || this;
  37078. if (!url) {
  37079. return _this;
  37080. }
  37081. _this._engine = scene.getEngine();
  37082. _this._textureMatrix = BABYLON.Matrix.Identity();
  37083. _this.name = url;
  37084. _this.url = url;
  37085. _this.hasAlpha = false;
  37086. _this.isCube = false;
  37087. _this.is3D = _this._engine.webGLVersion > 1;
  37088. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37089. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37090. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37091. _this.anisotropicFilteringLevel = 1;
  37092. _this._texture = _this._getFromCache(url, true);
  37093. if (!_this._texture) {
  37094. if (!scene.useDelayedTextureLoading) {
  37095. _this.loadTexture();
  37096. }
  37097. else {
  37098. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37099. }
  37100. }
  37101. return _this;
  37102. }
  37103. /**
  37104. * Returns the texture matrix used in most of the material.
  37105. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37106. */
  37107. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37108. return this._textureMatrix;
  37109. };
  37110. /**
  37111. * Occurs when the file being loaded is a .3dl LUT file.
  37112. */
  37113. ColorGradingTexture.prototype.load3dlTexture = function () {
  37114. var engine = this._engine;
  37115. var texture;
  37116. if (engine.webGLVersion === 1) {
  37117. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37118. }
  37119. else {
  37120. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37121. }
  37122. this._texture = texture;
  37123. var callback = function (text) {
  37124. if (typeof text !== "string") {
  37125. return;
  37126. }
  37127. var data = null;
  37128. var tempData = null;
  37129. var line;
  37130. var lines = text.split('\n');
  37131. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37132. var maxColor = 0;
  37133. for (var i = 0; i < lines.length; i++) {
  37134. line = lines[i];
  37135. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37136. continue;
  37137. if (line.indexOf('#') === 0)
  37138. continue;
  37139. var words = line.split(" ");
  37140. if (size === 0) {
  37141. // Number of space + one
  37142. size = words.length;
  37143. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37144. tempData = new Float32Array(size * size * size * 4);
  37145. continue;
  37146. }
  37147. if (size != 0) {
  37148. var r = Math.max(parseInt(words[0]), 0);
  37149. var g = Math.max(parseInt(words[1]), 0);
  37150. var b = Math.max(parseInt(words[2]), 0);
  37151. maxColor = Math.max(r, maxColor);
  37152. maxColor = Math.max(g, maxColor);
  37153. maxColor = Math.max(b, maxColor);
  37154. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37155. if (tempData) {
  37156. tempData[pixelStorageIndex + 0] = r;
  37157. tempData[pixelStorageIndex + 1] = g;
  37158. tempData[pixelStorageIndex + 2] = b;
  37159. }
  37160. pixelIndexSlice++;
  37161. if (pixelIndexSlice % size == 0) {
  37162. pixelIndexH++;
  37163. pixelIndexSlice = 0;
  37164. if (pixelIndexH % size == 0) {
  37165. pixelIndexW++;
  37166. pixelIndexH = 0;
  37167. }
  37168. }
  37169. }
  37170. }
  37171. if (tempData && data) {
  37172. for (var i = 0; i < tempData.length; i++) {
  37173. if (i > 0 && (i + 1) % 4 === 0) {
  37174. data[i] = 255;
  37175. }
  37176. else {
  37177. var value = tempData[i];
  37178. data[i] = (value / maxColor * 255);
  37179. }
  37180. }
  37181. }
  37182. if (texture.is3D) {
  37183. texture.updateSize(size, size, size);
  37184. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37185. }
  37186. else {
  37187. texture.updateSize(size * size, size);
  37188. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37189. }
  37190. };
  37191. var scene = this.getScene();
  37192. if (scene) {
  37193. scene._loadFile(this.url, callback);
  37194. }
  37195. else {
  37196. this._engine._loadFile(this.url, callback);
  37197. }
  37198. return this._texture;
  37199. };
  37200. /**
  37201. * Starts the loading process of the texture.
  37202. */
  37203. ColorGradingTexture.prototype.loadTexture = function () {
  37204. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37205. this.load3dlTexture();
  37206. }
  37207. };
  37208. /**
  37209. * Clones the color gradind texture.
  37210. */
  37211. ColorGradingTexture.prototype.clone = function () {
  37212. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37213. // Base texture
  37214. newTexture.level = this.level;
  37215. return newTexture;
  37216. };
  37217. /**
  37218. * Called during delayed load for textures.
  37219. */
  37220. ColorGradingTexture.prototype.delayLoad = function () {
  37221. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37222. return;
  37223. }
  37224. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37225. this._texture = this._getFromCache(this.url, true);
  37226. if (!this._texture) {
  37227. this.loadTexture();
  37228. }
  37229. };
  37230. /**
  37231. * Parses a color grading texture serialized by Babylon.
  37232. * @param parsedTexture The texture information being parsedTexture
  37233. * @param scene The scene to load the texture in
  37234. * @param rootUrl The root url of the data assets to load
  37235. * @return A color gradind texture
  37236. */
  37237. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37238. var texture = null;
  37239. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37240. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37241. texture.name = parsedTexture.name;
  37242. texture.level = parsedTexture.level;
  37243. }
  37244. return texture;
  37245. };
  37246. /**
  37247. * Serializes the LUT texture to json format.
  37248. */
  37249. ColorGradingTexture.prototype.serialize = function () {
  37250. if (!this.name) {
  37251. return null;
  37252. }
  37253. var serializationObject = {};
  37254. serializationObject.name = this.name;
  37255. serializationObject.level = this.level;
  37256. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37257. return serializationObject;
  37258. };
  37259. /**
  37260. * Empty line regex stored for GC.
  37261. */
  37262. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37263. return ColorGradingTexture;
  37264. }(BABYLON.BaseTexture));
  37265. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37266. })(BABYLON || (BABYLON = {}));
  37267. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37268. var BABYLON;
  37269. (function (BABYLON) {
  37270. /**
  37271. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37272. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37273. * 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;
  37274. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37275. */
  37276. var ColorCurves = /** @class */ (function () {
  37277. function ColorCurves() {
  37278. this._dirty = true;
  37279. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37280. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37281. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37282. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37283. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37284. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37285. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37286. this._globalHue = 30;
  37287. this._globalDensity = 0;
  37288. this._globalSaturation = 0;
  37289. this._globalExposure = 0;
  37290. this._highlightsHue = 30;
  37291. this._highlightsDensity = 0;
  37292. this._highlightsSaturation = 0;
  37293. this._highlightsExposure = 0;
  37294. this._midtonesHue = 30;
  37295. this._midtonesDensity = 0;
  37296. this._midtonesSaturation = 0;
  37297. this._midtonesExposure = 0;
  37298. this._shadowsHue = 30;
  37299. this._shadowsDensity = 0;
  37300. this._shadowsSaturation = 0;
  37301. this._shadowsExposure = 0;
  37302. }
  37303. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37304. /**
  37305. * Gets the global Hue value.
  37306. * 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).
  37307. */
  37308. get: function () {
  37309. return this._globalHue;
  37310. },
  37311. /**
  37312. * Sets the global Hue value.
  37313. * 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).
  37314. */
  37315. set: function (value) {
  37316. this._globalHue = value;
  37317. this._dirty = true;
  37318. },
  37319. enumerable: true,
  37320. configurable: true
  37321. });
  37322. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37323. /**
  37324. * Gets the global Density value.
  37325. * 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.
  37326. * Values less than zero provide a filter of opposite hue.
  37327. */
  37328. get: function () {
  37329. return this._globalDensity;
  37330. },
  37331. /**
  37332. * Sets the global Density value.
  37333. * 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.
  37334. * Values less than zero provide a filter of opposite hue.
  37335. */
  37336. set: function (value) {
  37337. this._globalDensity = value;
  37338. this._dirty = true;
  37339. },
  37340. enumerable: true,
  37341. configurable: true
  37342. });
  37343. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37344. /**
  37345. * Gets the global Saturation value.
  37346. * 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.
  37347. */
  37348. get: function () {
  37349. return this._globalSaturation;
  37350. },
  37351. /**
  37352. * Sets the global Saturation value.
  37353. * 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.
  37354. */
  37355. set: function (value) {
  37356. this._globalSaturation = value;
  37357. this._dirty = true;
  37358. },
  37359. enumerable: true,
  37360. configurable: true
  37361. });
  37362. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37363. /**
  37364. * Gets the highlights Hue value.
  37365. * 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).
  37366. */
  37367. get: function () {
  37368. return this._highlightsHue;
  37369. },
  37370. /**
  37371. * Sets the highlights Hue value.
  37372. * 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).
  37373. */
  37374. set: function (value) {
  37375. this._highlightsHue = value;
  37376. this._dirty = true;
  37377. },
  37378. enumerable: true,
  37379. configurable: true
  37380. });
  37381. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37382. /**
  37383. * Gets the highlights Density value.
  37384. * 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.
  37385. * Values less than zero provide a filter of opposite hue.
  37386. */
  37387. get: function () {
  37388. return this._highlightsDensity;
  37389. },
  37390. /**
  37391. * Sets the highlights Density value.
  37392. * 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.
  37393. * Values less than zero provide a filter of opposite hue.
  37394. */
  37395. set: function (value) {
  37396. this._highlightsDensity = value;
  37397. this._dirty = true;
  37398. },
  37399. enumerable: true,
  37400. configurable: true
  37401. });
  37402. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37403. /**
  37404. * Gets the highlights Saturation value.
  37405. * 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.
  37406. */
  37407. get: function () {
  37408. return this._highlightsSaturation;
  37409. },
  37410. /**
  37411. * Sets the highlights Saturation value.
  37412. * 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.
  37413. */
  37414. set: function (value) {
  37415. this._highlightsSaturation = value;
  37416. this._dirty = true;
  37417. },
  37418. enumerable: true,
  37419. configurable: true
  37420. });
  37421. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37422. /**
  37423. * Gets the highlights Exposure value.
  37424. * 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.
  37425. */
  37426. get: function () {
  37427. return this._highlightsExposure;
  37428. },
  37429. /**
  37430. * Sets the highlights Exposure value.
  37431. * 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.
  37432. */
  37433. set: function (value) {
  37434. this._highlightsExposure = value;
  37435. this._dirty = true;
  37436. },
  37437. enumerable: true,
  37438. configurable: true
  37439. });
  37440. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37441. /**
  37442. * Gets the midtones Hue value.
  37443. * 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).
  37444. */
  37445. get: function () {
  37446. return this._midtonesHue;
  37447. },
  37448. /**
  37449. * Sets the midtones Hue value.
  37450. * 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).
  37451. */
  37452. set: function (value) {
  37453. this._midtonesHue = value;
  37454. this._dirty = true;
  37455. },
  37456. enumerable: true,
  37457. configurable: true
  37458. });
  37459. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37460. /**
  37461. * Gets the midtones Density value.
  37462. * 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.
  37463. * Values less than zero provide a filter of opposite hue.
  37464. */
  37465. get: function () {
  37466. return this._midtonesDensity;
  37467. },
  37468. /**
  37469. * Sets the midtones Density value.
  37470. * 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.
  37471. * Values less than zero provide a filter of opposite hue.
  37472. */
  37473. set: function (value) {
  37474. this._midtonesDensity = value;
  37475. this._dirty = true;
  37476. },
  37477. enumerable: true,
  37478. configurable: true
  37479. });
  37480. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37481. /**
  37482. * Gets the midtones Saturation value.
  37483. * 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.
  37484. */
  37485. get: function () {
  37486. return this._midtonesSaturation;
  37487. },
  37488. /**
  37489. * Sets the midtones Saturation value.
  37490. * 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.
  37491. */
  37492. set: function (value) {
  37493. this._midtonesSaturation = value;
  37494. this._dirty = true;
  37495. },
  37496. enumerable: true,
  37497. configurable: true
  37498. });
  37499. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37500. /**
  37501. * Gets the midtones Exposure value.
  37502. * 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.
  37503. */
  37504. get: function () {
  37505. return this._midtonesExposure;
  37506. },
  37507. /**
  37508. * Sets the midtones Exposure value.
  37509. * 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.
  37510. */
  37511. set: function (value) {
  37512. this._midtonesExposure = value;
  37513. this._dirty = true;
  37514. },
  37515. enumerable: true,
  37516. configurable: true
  37517. });
  37518. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37519. /**
  37520. * Gets the shadows Hue value.
  37521. * 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).
  37522. */
  37523. get: function () {
  37524. return this._shadowsHue;
  37525. },
  37526. /**
  37527. * Sets the shadows Hue value.
  37528. * 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).
  37529. */
  37530. set: function (value) {
  37531. this._shadowsHue = value;
  37532. this._dirty = true;
  37533. },
  37534. enumerable: true,
  37535. configurable: true
  37536. });
  37537. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37538. /**
  37539. * Gets the shadows Density value.
  37540. * 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.
  37541. * Values less than zero provide a filter of opposite hue.
  37542. */
  37543. get: function () {
  37544. return this._shadowsDensity;
  37545. },
  37546. /**
  37547. * Sets the shadows Density value.
  37548. * 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.
  37549. * Values less than zero provide a filter of opposite hue.
  37550. */
  37551. set: function (value) {
  37552. this._shadowsDensity = value;
  37553. this._dirty = true;
  37554. },
  37555. enumerable: true,
  37556. configurable: true
  37557. });
  37558. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37559. /**
  37560. * Gets the shadows Saturation value.
  37561. * 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.
  37562. */
  37563. get: function () {
  37564. return this._shadowsSaturation;
  37565. },
  37566. /**
  37567. * Sets the shadows Saturation value.
  37568. * 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.
  37569. */
  37570. set: function (value) {
  37571. this._shadowsSaturation = value;
  37572. this._dirty = true;
  37573. },
  37574. enumerable: true,
  37575. configurable: true
  37576. });
  37577. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37578. /**
  37579. * Gets the shadows Exposure value.
  37580. * 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.
  37581. */
  37582. get: function () {
  37583. return this._shadowsExposure;
  37584. },
  37585. /**
  37586. * Sets the shadows Exposure value.
  37587. * 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.
  37588. */
  37589. set: function (value) {
  37590. this._shadowsExposure = value;
  37591. this._dirty = true;
  37592. },
  37593. enumerable: true,
  37594. configurable: true
  37595. });
  37596. ColorCurves.prototype.getClassName = function () {
  37597. return "ColorCurves";
  37598. };
  37599. /**
  37600. * Binds the color curves to the shader.
  37601. * @param colorCurves The color curve to bind
  37602. * @param effect The effect to bind to
  37603. */
  37604. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37605. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37606. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37607. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37608. if (colorCurves._dirty) {
  37609. colorCurves._dirty = false;
  37610. // Fill in global info.
  37611. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37612. // Compute highlights info.
  37613. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37614. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37615. // Compute midtones info.
  37616. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37617. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37618. // Compute shadows info.
  37619. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37620. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37621. // Compute deltas (neutral is midtones).
  37622. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37623. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37624. }
  37625. if (effect) {
  37626. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37627. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37628. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37629. }
  37630. };
  37631. /**
  37632. * Prepare the list of uniforms associated with the ColorCurves effects.
  37633. * @param uniformsList The list of uniforms used in the effect
  37634. */
  37635. ColorCurves.PrepareUniforms = function (uniformsList) {
  37636. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37637. };
  37638. /**
  37639. * Returns color grading data based on a hue, density, saturation and exposure value.
  37640. * @param filterHue The hue of the color filter.
  37641. * @param filterDensity The density of the color filter.
  37642. * @param saturation The saturation.
  37643. * @param exposure The exposure.
  37644. * @param result The result data container.
  37645. */
  37646. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37647. if (hue == null) {
  37648. return;
  37649. }
  37650. hue = ColorCurves.clamp(hue, 0, 360);
  37651. density = ColorCurves.clamp(density, -100, 100);
  37652. saturation = ColorCurves.clamp(saturation, -100, 100);
  37653. exposure = ColorCurves.clamp(exposure, -100, 100);
  37654. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37655. // so that the maximum filter density is only 50% control. This provides fine control
  37656. // for small values and reasonable range.
  37657. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37658. density *= 0.5;
  37659. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37660. if (density < 0) {
  37661. density *= -1;
  37662. hue = (hue + 180) % 360;
  37663. }
  37664. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37665. result.scaleToRef(2, result);
  37666. result.a = 1 + 0.01 * saturation;
  37667. };
  37668. /**
  37669. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37670. * @param value The input slider value in range [-100,100].
  37671. * @returns Adjusted value.
  37672. */
  37673. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37674. value /= 100;
  37675. var x = Math.abs(value);
  37676. x = Math.pow(x, 2);
  37677. if (value < 0) {
  37678. x *= -1;
  37679. }
  37680. x *= 100;
  37681. return x;
  37682. };
  37683. /**
  37684. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37685. * @param hue The hue (H) input.
  37686. * @param saturation The saturation (S) input.
  37687. * @param brightness The brightness (B) input.
  37688. * @result An RGBA color represented as Vector4.
  37689. */
  37690. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37691. var h = ColorCurves.clamp(hue, 0, 360);
  37692. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37693. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37694. if (s === 0) {
  37695. result.r = v;
  37696. result.g = v;
  37697. result.b = v;
  37698. }
  37699. else {
  37700. // sector 0 to 5
  37701. h /= 60;
  37702. var i = Math.floor(h);
  37703. // fractional part of h
  37704. var f = h - i;
  37705. var p = v * (1 - s);
  37706. var q = v * (1 - s * f);
  37707. var t = v * (1 - s * (1 - f));
  37708. switch (i) {
  37709. case 0:
  37710. result.r = v;
  37711. result.g = t;
  37712. result.b = p;
  37713. break;
  37714. case 1:
  37715. result.r = q;
  37716. result.g = v;
  37717. result.b = p;
  37718. break;
  37719. case 2:
  37720. result.r = p;
  37721. result.g = v;
  37722. result.b = t;
  37723. break;
  37724. case 3:
  37725. result.r = p;
  37726. result.g = q;
  37727. result.b = v;
  37728. break;
  37729. case 4:
  37730. result.r = t;
  37731. result.g = p;
  37732. result.b = v;
  37733. break;
  37734. default:// case 5:
  37735. result.r = v;
  37736. result.g = p;
  37737. result.b = q;
  37738. break;
  37739. }
  37740. }
  37741. result.a = 1;
  37742. };
  37743. /**
  37744. * Returns a value clamped between min and max
  37745. * @param value The value to clamp
  37746. * @param min The minimum of value
  37747. * @param max The maximum of value
  37748. * @returns The clamped value.
  37749. */
  37750. ColorCurves.clamp = function (value, min, max) {
  37751. return Math.min(Math.max(value, min), max);
  37752. };
  37753. /**
  37754. * Clones the current color curve instance.
  37755. * @return The cloned curves
  37756. */
  37757. ColorCurves.prototype.clone = function () {
  37758. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37759. };
  37760. /**
  37761. * Serializes the current color curve instance to a json representation.
  37762. * @return a JSON representation
  37763. */
  37764. ColorCurves.prototype.serialize = function () {
  37765. return BABYLON.SerializationHelper.Serialize(this);
  37766. };
  37767. /**
  37768. * Parses the color curve from a json representation.
  37769. * @param source the JSON source to parse
  37770. * @return The parsed curves
  37771. */
  37772. ColorCurves.Parse = function (source) {
  37773. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37774. };
  37775. __decorate([
  37776. BABYLON.serialize()
  37777. ], ColorCurves.prototype, "_globalHue", void 0);
  37778. __decorate([
  37779. BABYLON.serialize()
  37780. ], ColorCurves.prototype, "_globalDensity", void 0);
  37781. __decorate([
  37782. BABYLON.serialize()
  37783. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37784. __decorate([
  37785. BABYLON.serialize()
  37786. ], ColorCurves.prototype, "_globalExposure", void 0);
  37787. __decorate([
  37788. BABYLON.serialize()
  37789. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37790. __decorate([
  37791. BABYLON.serialize()
  37792. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37793. __decorate([
  37794. BABYLON.serialize()
  37795. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37796. __decorate([
  37797. BABYLON.serialize()
  37798. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37799. __decorate([
  37800. BABYLON.serialize()
  37801. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37802. __decorate([
  37803. BABYLON.serialize()
  37804. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37805. __decorate([
  37806. BABYLON.serialize()
  37807. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37808. __decorate([
  37809. BABYLON.serialize()
  37810. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37811. return ColorCurves;
  37812. }());
  37813. BABYLON.ColorCurves = ColorCurves;
  37814. })(BABYLON || (BABYLON = {}));
  37815. //# sourceMappingURL=babylon.colorCurves.js.map
  37816. //# sourceMappingURL=babylon.behavior.js.map
  37817. var BABYLON;
  37818. (function (BABYLON) {
  37819. /**
  37820. * "Static Class" containing the most commonly used helper while dealing with material for
  37821. * rendering purpose.
  37822. *
  37823. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37824. *
  37825. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37826. */
  37827. var MaterialHelper = /** @class */ (function () {
  37828. function MaterialHelper() {
  37829. }
  37830. /**
  37831. * Bind the current view position to an effect.
  37832. * @param effect The effect to be bound
  37833. * @param scene The scene the eyes position is used from
  37834. */
  37835. MaterialHelper.BindEyePosition = function (effect, scene) {
  37836. if (scene._forcedViewPosition) {
  37837. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37838. return;
  37839. }
  37840. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37841. };
  37842. /**
  37843. * Helps preparing the defines values about the UVs in used in the effect.
  37844. * UVs are shared as much as we can accross chanels in the shaders.
  37845. * @param texture The texture we are preparing the UVs for
  37846. * @param defines The defines to update
  37847. * @param key The chanel key "diffuse", "specular"... used in the shader
  37848. */
  37849. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37850. defines._needUVs = true;
  37851. defines[key] = true;
  37852. if (texture.getTextureMatrix().isIdentity(true)) {
  37853. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37854. if (texture.coordinatesIndex === 0) {
  37855. defines["MAINUV1"] = true;
  37856. }
  37857. else {
  37858. defines["MAINUV2"] = true;
  37859. }
  37860. }
  37861. else {
  37862. defines[key + "DIRECTUV"] = 0;
  37863. }
  37864. };
  37865. /**
  37866. * Binds a texture matrix value to its corrsponding uniform
  37867. * @param texture The texture to bind the matrix for
  37868. * @param uniformBuffer The uniform buffer receivin the data
  37869. * @param key The chanel key "diffuse", "specular"... used in the shader
  37870. */
  37871. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37872. var matrix = texture.getTextureMatrix();
  37873. if (!matrix.isIdentity(true)) {
  37874. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37875. }
  37876. };
  37877. /**
  37878. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37879. * @param mesh defines the current mesh
  37880. * @param scene defines the current scene
  37881. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37882. * @param pointsCloud defines if point cloud rendering has to be turned on
  37883. * @param fogEnabled defines if fog has to be turned on
  37884. * @param alphaTest defines if alpha testing has to be turned on
  37885. * @param defines defines the current list of defines
  37886. */
  37887. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37888. if (defines._areMiscDirty) {
  37889. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37890. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37891. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37892. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37893. defines["ALPHATEST"] = alphaTest;
  37894. }
  37895. };
  37896. /**
  37897. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37898. * @param scene defines the current scene
  37899. * @param engine defines the current engine
  37900. * @param defines specifies the list of active defines
  37901. * @param useInstances defines if instances have to be turned on
  37902. * @param useClipPlane defines if clip plane have to be turned on
  37903. */
  37904. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37905. if (useClipPlane === void 0) { useClipPlane = null; }
  37906. var changed = false;
  37907. if (useClipPlane == null) {
  37908. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37909. }
  37910. if (defines["CLIPPLANE"] !== useClipPlane) {
  37911. defines["CLIPPLANE"] = useClipPlane;
  37912. changed = true;
  37913. }
  37914. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37915. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37916. changed = true;
  37917. }
  37918. if (defines["INSTANCES"] !== useInstances) {
  37919. defines["INSTANCES"] = useInstances;
  37920. changed = true;
  37921. }
  37922. if (changed) {
  37923. defines.markAsUnprocessed();
  37924. }
  37925. };
  37926. /**
  37927. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37928. * @param mesh The mesh containing the geometry data we will draw
  37929. * @param defines The defines to update
  37930. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37931. * @param useBones Precise whether bones should be used or not (override mesh info)
  37932. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37933. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37934. * @returns false if defines are considered not dirty and have not been checked
  37935. */
  37936. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37937. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37938. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37939. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37940. return false;
  37941. }
  37942. defines._normals = defines._needNormals;
  37943. defines._uvs = defines._needUVs;
  37944. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37945. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37946. defines["TANGENT"] = true;
  37947. }
  37948. if (defines._needUVs) {
  37949. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37950. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37951. }
  37952. else {
  37953. defines["UV1"] = false;
  37954. defines["UV2"] = false;
  37955. }
  37956. if (useVertexColor) {
  37957. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37958. defines["VERTEXCOLOR"] = hasVertexColors;
  37959. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37960. }
  37961. if (useBones) {
  37962. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37963. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37964. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37965. }
  37966. else {
  37967. defines["NUM_BONE_INFLUENCERS"] = 0;
  37968. defines["BonesPerMesh"] = 0;
  37969. }
  37970. }
  37971. if (useMorphTargets) {
  37972. var manager = mesh.morphTargetManager;
  37973. if (manager) {
  37974. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37975. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37976. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37977. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37978. }
  37979. else {
  37980. defines["MORPHTARGETS_TANGENT"] = false;
  37981. defines["MORPHTARGETS_NORMAL"] = false;
  37982. defines["MORPHTARGETS"] = false;
  37983. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37984. }
  37985. }
  37986. return true;
  37987. };
  37988. /**
  37989. * Prepares the defines related to the light information passed in parameter
  37990. * @param scene The scene we are intending to draw
  37991. * @param mesh The mesh the effect is compiling for
  37992. * @param defines The defines to update
  37993. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37994. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37995. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37996. * @returns true if normals will be required for the rest of the effect
  37997. */
  37998. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37999. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38000. if (disableLighting === void 0) { disableLighting = false; }
  38001. if (!defines._areLightsDirty) {
  38002. return defines._needNormals;
  38003. }
  38004. var lightIndex = 0;
  38005. var needNormals = false;
  38006. var needRebuild = false;
  38007. var lightmapMode = false;
  38008. var shadowEnabled = false;
  38009. var specularEnabled = false;
  38010. if (scene.lightsEnabled && !disableLighting) {
  38011. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38012. var light = _a[_i];
  38013. needNormals = true;
  38014. if (defines["LIGHT" + lightIndex] === undefined) {
  38015. needRebuild = true;
  38016. }
  38017. defines["LIGHT" + lightIndex] = true;
  38018. defines["SPOTLIGHT" + lightIndex] = false;
  38019. defines["HEMILIGHT" + lightIndex] = false;
  38020. defines["POINTLIGHT" + lightIndex] = false;
  38021. defines["DIRLIGHT" + lightIndex] = false;
  38022. var type;
  38023. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38024. type = "SPOTLIGHT" + lightIndex;
  38025. var spotLight = light;
  38026. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38027. }
  38028. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38029. type = "HEMILIGHT" + lightIndex;
  38030. }
  38031. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38032. type = "POINTLIGHT" + lightIndex;
  38033. }
  38034. else {
  38035. type = "DIRLIGHT" + lightIndex;
  38036. }
  38037. defines[type] = true;
  38038. // Specular
  38039. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38040. specularEnabled = true;
  38041. }
  38042. // Shadows
  38043. defines["SHADOW" + lightIndex] = false;
  38044. defines["SHADOWPCF" + lightIndex] = false;
  38045. defines["SHADOWESM" + lightIndex] = false;
  38046. defines["SHADOWCUBE" + lightIndex] = false;
  38047. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  38048. var shadowGenerator = light.getShadowGenerator();
  38049. if (shadowGenerator) {
  38050. shadowEnabled = true;
  38051. shadowGenerator.prepareDefines(defines, lightIndex);
  38052. }
  38053. }
  38054. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  38055. lightmapMode = true;
  38056. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  38057. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  38058. }
  38059. else {
  38060. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  38061. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  38062. }
  38063. lightIndex++;
  38064. if (lightIndex === maxSimultaneousLights)
  38065. break;
  38066. }
  38067. }
  38068. defines["SPECULARTERM"] = specularEnabled;
  38069. defines["SHADOWS"] = shadowEnabled;
  38070. // Resetting all other lights if any
  38071. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  38072. if (defines["LIGHT" + index] !== undefined) {
  38073. defines["LIGHT" + index] = false;
  38074. defines["HEMILIGHT" + lightIndex] = false;
  38075. defines["POINTLIGHT" + lightIndex] = false;
  38076. defines["DIRLIGHT" + lightIndex] = false;
  38077. defines["SPOTLIGHT" + lightIndex] = false;
  38078. defines["SHADOW" + lightIndex] = false;
  38079. }
  38080. }
  38081. var caps = scene.getEngine().getCaps();
  38082. if (defines["SHADOWFLOAT"] === undefined) {
  38083. needRebuild = true;
  38084. }
  38085. defines["SHADOWFLOAT"] = shadowEnabled &&
  38086. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38087. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38088. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38089. if (needRebuild) {
  38090. defines.rebuild();
  38091. }
  38092. return needNormals;
  38093. };
  38094. /**
  38095. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38096. * that won t be acctive due to defines being turned off.
  38097. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38098. * @param samplersList The samplers list
  38099. * @param defines The defines helping in the list generation
  38100. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38101. */
  38102. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38103. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38104. var uniformsList;
  38105. var uniformBuffersList = null;
  38106. if (uniformsListOrOptions.uniformsNames) {
  38107. var options = uniformsListOrOptions;
  38108. uniformsList = options.uniformsNames;
  38109. uniformBuffersList = options.uniformBuffersNames;
  38110. samplersList = options.samplers;
  38111. defines = options.defines;
  38112. maxSimultaneousLights = options.maxSimultaneousLights;
  38113. }
  38114. else {
  38115. uniformsList = uniformsListOrOptions;
  38116. if (!samplersList) {
  38117. samplersList = [];
  38118. }
  38119. }
  38120. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38121. if (!defines["LIGHT" + lightIndex]) {
  38122. break;
  38123. }
  38124. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38125. if (uniformBuffersList) {
  38126. uniformBuffersList.push("Light" + lightIndex);
  38127. }
  38128. samplersList.push("shadowSampler" + lightIndex);
  38129. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38130. samplersList.push("projectionLightSampler" + lightIndex);
  38131. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38132. }
  38133. }
  38134. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38135. uniformsList.push("morphTargetInfluences");
  38136. }
  38137. };
  38138. /**
  38139. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38140. * @param defines The defines to update while falling back
  38141. * @param fallbacks The authorized effect fallbacks
  38142. * @param maxSimultaneousLights The maximum number of lights allowed
  38143. * @param rank the current rank of the Effect
  38144. * @returns The newly affected rank
  38145. */
  38146. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38147. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38148. if (rank === void 0) { rank = 0; }
  38149. var lightFallbackRank = 0;
  38150. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38151. if (!defines["LIGHT" + lightIndex]) {
  38152. break;
  38153. }
  38154. if (lightIndex > 0) {
  38155. lightFallbackRank = rank + lightIndex;
  38156. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38157. }
  38158. if (!defines["SHADOWS"]) {
  38159. if (defines["SHADOW" + lightIndex]) {
  38160. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38161. }
  38162. if (defines["SHADOWPCF" + lightIndex]) {
  38163. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38164. }
  38165. if (defines["SHADOWESM" + lightIndex]) {
  38166. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38167. }
  38168. }
  38169. }
  38170. return lightFallbackRank++;
  38171. };
  38172. /**
  38173. * Prepares the list of attributes required for morph targets according to the effect defines.
  38174. * @param attribs The current list of supported attribs
  38175. * @param mesh The mesh to prepare the morph targets attributes for
  38176. * @param defines The current Defines of the effect
  38177. */
  38178. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38179. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38180. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38181. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38182. var manager = mesh.morphTargetManager;
  38183. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38184. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38185. for (var index = 0; index < influencers; index++) {
  38186. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38187. if (normal) {
  38188. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38189. }
  38190. if (tangent) {
  38191. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38192. }
  38193. if (attribs.length > maxAttributesCount) {
  38194. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38195. }
  38196. }
  38197. }
  38198. };
  38199. /**
  38200. * Prepares the list of attributes required for bones according to the effect defines.
  38201. * @param attribs The current list of supported attribs
  38202. * @param mesh The mesh to prepare the bones attributes for
  38203. * @param defines The current Defines of the effect
  38204. * @param fallbacks The current efffect fallback strategy
  38205. */
  38206. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38207. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38208. fallbacks.addCPUSkinningFallback(0, mesh);
  38209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38211. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38212. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38213. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38214. }
  38215. }
  38216. };
  38217. /**
  38218. * Prepares the list of attributes required for instances according to the effect defines.
  38219. * @param attribs The current list of supported attribs
  38220. * @param defines The current Defines of the effect
  38221. */
  38222. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38223. if (defines["INSTANCES"]) {
  38224. attribs.push("world0");
  38225. attribs.push("world1");
  38226. attribs.push("world2");
  38227. attribs.push("world3");
  38228. }
  38229. };
  38230. /**
  38231. * Binds the light shadow information to the effect for the given mesh.
  38232. * @param light The light containing the generator
  38233. * @param scene The scene the lights belongs to
  38234. * @param mesh The mesh we are binding the information to render
  38235. * @param lightIndex The light index in the effect used to render the mesh
  38236. * @param effect The effect we are binding the data to
  38237. */
  38238. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38239. if (light.shadowEnabled && mesh.receiveShadows) {
  38240. var shadowGenerator = light.getShadowGenerator();
  38241. if (shadowGenerator) {
  38242. shadowGenerator.bindShadowLight(lightIndex, effect);
  38243. }
  38244. }
  38245. };
  38246. /**
  38247. * Binds the light information to the effect.
  38248. * @param light The light containing the generator
  38249. * @param effect The effect we are binding the data to
  38250. * @param lightIndex The light index in the effect used to render
  38251. */
  38252. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38253. light.transferToEffect(effect, lightIndex + "");
  38254. };
  38255. /**
  38256. * Binds the lights information from the scene to the effect for the given mesh.
  38257. * @param scene The scene the lights belongs to
  38258. * @param mesh The mesh we are binding the information to render
  38259. * @param effect The effect we are binding the data to
  38260. * @param defines The generated defines for the effect
  38261. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38262. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38263. */
  38264. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38265. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38266. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38267. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38268. for (var i = 0; i < len; i++) {
  38269. var light = mesh._lightSources[i];
  38270. var iAsString = i.toString();
  38271. var scaledIntensity = light.getScaledIntensity();
  38272. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38273. MaterialHelper.BindLightProperties(light, effect, i);
  38274. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38275. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38276. if (defines["SPECULARTERM"]) {
  38277. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38278. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38279. }
  38280. // Shadows
  38281. if (scene.shadowsEnabled) {
  38282. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38283. }
  38284. light._uniformBuffer.update();
  38285. }
  38286. };
  38287. /**
  38288. * Binds the fog information from the scene to the effect for the given mesh.
  38289. * @param scene The scene the lights belongs to
  38290. * @param mesh The mesh we are binding the information to render
  38291. * @param effect The effect we are binding the data to
  38292. */
  38293. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38294. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38295. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38296. effect.setColor3("vFogColor", scene.fogColor);
  38297. }
  38298. };
  38299. /**
  38300. * Binds the bones information from the mesh to the effect.
  38301. * @param mesh The mesh we are binding the information to render
  38302. * @param effect The effect we are binding the data to
  38303. */
  38304. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38305. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38306. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38307. if (matrices && effect) {
  38308. effect.setMatrices("mBones", matrices);
  38309. }
  38310. }
  38311. };
  38312. /**
  38313. * Binds the morph targets information from the mesh to the effect.
  38314. * @param abstractMesh The mesh we are binding the information to render
  38315. * @param effect The effect we are binding the data to
  38316. */
  38317. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38318. var manager = abstractMesh.morphTargetManager;
  38319. if (!abstractMesh || !manager) {
  38320. return;
  38321. }
  38322. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38323. };
  38324. /**
  38325. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38326. * @param defines The generated defines used in the effect
  38327. * @param effect The effect we are binding the data to
  38328. * @param scene The scene we are willing to render with logarithmic scale for
  38329. */
  38330. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38331. if (defines["LOGARITHMICDEPTH"]) {
  38332. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38333. }
  38334. };
  38335. /**
  38336. * Binds the clip plane information from the scene to the effect.
  38337. * @param scene The scene the clip plane information are extracted from
  38338. * @param effect The effect we are binding the data to
  38339. */
  38340. MaterialHelper.BindClipPlane = function (effect, scene) {
  38341. if (scene.clipPlane) {
  38342. var clipPlane = scene.clipPlane;
  38343. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38344. }
  38345. };
  38346. return MaterialHelper;
  38347. }());
  38348. BABYLON.MaterialHelper = MaterialHelper;
  38349. })(BABYLON || (BABYLON = {}));
  38350. //# sourceMappingURL=babylon.materialHelper.js.map
  38351. var BABYLON;
  38352. (function (BABYLON) {
  38353. var PushMaterial = /** @class */ (function (_super) {
  38354. __extends(PushMaterial, _super);
  38355. function PushMaterial(name, scene) {
  38356. var _this = _super.call(this, name, scene) || this;
  38357. _this._normalMatrix = new BABYLON.Matrix();
  38358. _this.storeEffectOnSubMeshes = true;
  38359. return _this;
  38360. }
  38361. PushMaterial.prototype.getEffect = function () {
  38362. return this._activeEffect;
  38363. };
  38364. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38365. if (!mesh) {
  38366. return false;
  38367. }
  38368. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38369. return true;
  38370. }
  38371. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38372. };
  38373. /**
  38374. * Binds the given world matrix to the active effect
  38375. *
  38376. * @param world the matrix to bind
  38377. */
  38378. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38379. this._activeEffect.setMatrix("world", world);
  38380. };
  38381. /**
  38382. * Binds the given normal matrix to the active effect
  38383. *
  38384. * @param normalMatrix the matrix to bind
  38385. */
  38386. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38387. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38388. };
  38389. PushMaterial.prototype.bind = function (world, mesh) {
  38390. if (!mesh) {
  38391. return;
  38392. }
  38393. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38394. };
  38395. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38396. if (effect === void 0) { effect = null; }
  38397. _super.prototype._afterBind.call(this, mesh);
  38398. this.getScene()._cachedEffect = effect;
  38399. };
  38400. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38401. if (visibility === void 0) { visibility = 1; }
  38402. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38403. };
  38404. return PushMaterial;
  38405. }(BABYLON.Material));
  38406. BABYLON.PushMaterial = PushMaterial;
  38407. })(BABYLON || (BABYLON = {}));
  38408. //# sourceMappingURL=babylon.pushMaterial.js.map
  38409. var BABYLON;
  38410. (function (BABYLON) {
  38411. /** @ignore */
  38412. var StandardMaterialDefines = /** @class */ (function (_super) {
  38413. __extends(StandardMaterialDefines, _super);
  38414. function StandardMaterialDefines() {
  38415. var _this = _super.call(this) || this;
  38416. _this.MAINUV1 = false;
  38417. _this.MAINUV2 = false;
  38418. _this.DIFFUSE = false;
  38419. _this.DIFFUSEDIRECTUV = 0;
  38420. _this.AMBIENT = false;
  38421. _this.AMBIENTDIRECTUV = 0;
  38422. _this.OPACITY = false;
  38423. _this.OPACITYDIRECTUV = 0;
  38424. _this.OPACITYRGB = false;
  38425. _this.REFLECTION = false;
  38426. _this.EMISSIVE = false;
  38427. _this.EMISSIVEDIRECTUV = 0;
  38428. _this.SPECULAR = false;
  38429. _this.SPECULARDIRECTUV = 0;
  38430. _this.BUMP = false;
  38431. _this.BUMPDIRECTUV = 0;
  38432. _this.PARALLAX = false;
  38433. _this.PARALLAXOCCLUSION = false;
  38434. _this.SPECULAROVERALPHA = false;
  38435. _this.CLIPPLANE = false;
  38436. _this.ALPHATEST = false;
  38437. _this.DEPTHPREPASS = false;
  38438. _this.ALPHAFROMDIFFUSE = false;
  38439. _this.POINTSIZE = false;
  38440. _this.FOG = false;
  38441. _this.SPECULARTERM = false;
  38442. _this.DIFFUSEFRESNEL = false;
  38443. _this.OPACITYFRESNEL = false;
  38444. _this.REFLECTIONFRESNEL = false;
  38445. _this.REFRACTIONFRESNEL = false;
  38446. _this.EMISSIVEFRESNEL = false;
  38447. _this.FRESNEL = false;
  38448. _this.NORMAL = false;
  38449. _this.UV1 = false;
  38450. _this.UV2 = false;
  38451. _this.VERTEXCOLOR = false;
  38452. _this.VERTEXALPHA = false;
  38453. _this.NUM_BONE_INFLUENCERS = 0;
  38454. _this.BonesPerMesh = 0;
  38455. _this.INSTANCES = false;
  38456. _this.GLOSSINESS = false;
  38457. _this.ROUGHNESS = false;
  38458. _this.EMISSIVEASILLUMINATION = false;
  38459. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38460. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38461. _this.LIGHTMAP = false;
  38462. _this.LIGHTMAPDIRECTUV = 0;
  38463. _this.OBJECTSPACE_NORMALMAP = false;
  38464. _this.USELIGHTMAPASSHADOWMAP = false;
  38465. _this.REFLECTIONMAP_3D = false;
  38466. _this.REFLECTIONMAP_SPHERICAL = false;
  38467. _this.REFLECTIONMAP_PLANAR = false;
  38468. _this.REFLECTIONMAP_CUBIC = false;
  38469. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38470. _this.REFLECTIONMAP_PROJECTION = false;
  38471. _this.REFLECTIONMAP_SKYBOX = false;
  38472. _this.REFLECTIONMAP_EXPLICIT = false;
  38473. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38474. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38475. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38476. _this.INVERTCUBICMAP = false;
  38477. _this.LOGARITHMICDEPTH = false;
  38478. _this.REFRACTION = false;
  38479. _this.REFRACTIONMAP_3D = false;
  38480. _this.REFLECTIONOVERALPHA = false;
  38481. _this.TWOSIDEDLIGHTING = false;
  38482. _this.SHADOWFLOAT = false;
  38483. _this.MORPHTARGETS = false;
  38484. _this.MORPHTARGETS_NORMAL = false;
  38485. _this.MORPHTARGETS_TANGENT = false;
  38486. _this.NUM_MORPH_INFLUENCERS = 0;
  38487. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38488. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38489. _this.IMAGEPROCESSING = false;
  38490. _this.VIGNETTE = false;
  38491. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38492. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38493. _this.TONEMAPPING = false;
  38494. _this.CONTRAST = false;
  38495. _this.COLORCURVES = false;
  38496. _this.COLORGRADING = false;
  38497. _this.COLORGRADING3D = false;
  38498. _this.SAMPLER3DGREENDEPTH = false;
  38499. _this.SAMPLER3DBGRMAP = false;
  38500. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38501. _this.EXPOSURE = false;
  38502. _this.rebuild();
  38503. return _this;
  38504. }
  38505. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38506. var modes = [
  38507. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38508. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38509. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38510. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38511. ];
  38512. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38513. var mode = modes_1[_i];
  38514. this[mode] = (mode === modeToEnable);
  38515. }
  38516. };
  38517. return StandardMaterialDefines;
  38518. }(BABYLON.MaterialDefines));
  38519. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38520. var StandardMaterial = /** @class */ (function (_super) {
  38521. __extends(StandardMaterial, _super);
  38522. function StandardMaterial(name, scene) {
  38523. var _this = _super.call(this, name, scene) || this;
  38524. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38525. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38526. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38527. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38528. _this.specularPower = 64;
  38529. _this._useAlphaFromDiffuseTexture = false;
  38530. _this._useEmissiveAsIllumination = false;
  38531. _this._linkEmissiveWithDiffuse = false;
  38532. _this._useSpecularOverAlpha = false;
  38533. _this._useReflectionOverAlpha = false;
  38534. _this._disableLighting = false;
  38535. _this._useObjectSpaceNormalMap = false;
  38536. _this._useParallax = false;
  38537. _this._useParallaxOcclusion = false;
  38538. _this.parallaxScaleBias = 0.05;
  38539. _this._roughness = 0;
  38540. _this.indexOfRefraction = 0.98;
  38541. _this.invertRefractionY = true;
  38542. _this._useLightmapAsShadowmap = false;
  38543. _this._useReflectionFresnelFromSpecular = false;
  38544. _this._useGlossinessFromSpecularMapAlpha = false;
  38545. _this._maxSimultaneousLights = 4;
  38546. /**
  38547. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38548. */
  38549. _this._invertNormalMapX = false;
  38550. /**
  38551. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38552. */
  38553. _this._invertNormalMapY = false;
  38554. /**
  38555. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38556. */
  38557. _this._twoSidedLighting = false;
  38558. _this._renderTargets = new BABYLON.SmartArray(16);
  38559. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38560. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38561. // Setup the default processing configuration to the scene.
  38562. _this._attachImageProcessingConfiguration(null);
  38563. _this.getRenderTargetTextures = function () {
  38564. _this._renderTargets.reset();
  38565. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38566. _this._renderTargets.push(_this._reflectionTexture);
  38567. }
  38568. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38569. _this._renderTargets.push(_this._refractionTexture);
  38570. }
  38571. return _this._renderTargets;
  38572. };
  38573. return _this;
  38574. }
  38575. ;
  38576. ;
  38577. ;
  38578. ;
  38579. ;
  38580. ;
  38581. ;
  38582. ;
  38583. ;
  38584. ;
  38585. ;
  38586. ;
  38587. ;
  38588. ;
  38589. ;
  38590. ;
  38591. ;
  38592. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38593. /**
  38594. * Gets the image processing configuration used either in this material.
  38595. */
  38596. get: function () {
  38597. return this._imageProcessingConfiguration;
  38598. },
  38599. /**
  38600. * Sets the Default image processing configuration used either in the this material.
  38601. *
  38602. * If sets to null, the scene one is in use.
  38603. */
  38604. set: function (value) {
  38605. this._attachImageProcessingConfiguration(value);
  38606. // Ensure the effect will be rebuilt.
  38607. this._markAllSubMeshesAsTexturesDirty();
  38608. },
  38609. enumerable: true,
  38610. configurable: true
  38611. });
  38612. /**
  38613. * Attaches a new image processing configuration to the Standard Material.
  38614. * @param configuration
  38615. */
  38616. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38617. var _this = this;
  38618. if (configuration === this._imageProcessingConfiguration) {
  38619. return;
  38620. }
  38621. // Detaches observer.
  38622. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38623. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38624. }
  38625. // Pick the scene configuration if needed.
  38626. if (!configuration) {
  38627. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38628. }
  38629. else {
  38630. this._imageProcessingConfiguration = configuration;
  38631. }
  38632. // Attaches observer.
  38633. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38634. _this._markAllSubMeshesAsImageProcessingDirty();
  38635. });
  38636. };
  38637. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38638. /**
  38639. * Gets wether the color curves effect is enabled.
  38640. */
  38641. get: function () {
  38642. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38643. },
  38644. /**
  38645. * Sets wether the color curves effect is enabled.
  38646. */
  38647. set: function (value) {
  38648. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38649. },
  38650. enumerable: true,
  38651. configurable: true
  38652. });
  38653. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38654. /**
  38655. * Gets wether the color grading effect is enabled.
  38656. */
  38657. get: function () {
  38658. return this.imageProcessingConfiguration.colorGradingEnabled;
  38659. },
  38660. /**
  38661. * Gets wether the color grading effect is enabled.
  38662. */
  38663. set: function (value) {
  38664. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38665. },
  38666. enumerable: true,
  38667. configurable: true
  38668. });
  38669. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38670. /**
  38671. * Gets wether tonemapping is enabled or not.
  38672. */
  38673. get: function () {
  38674. return this._imageProcessingConfiguration.toneMappingEnabled;
  38675. },
  38676. /**
  38677. * Sets wether tonemapping is enabled or not
  38678. */
  38679. set: function (value) {
  38680. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38681. },
  38682. enumerable: true,
  38683. configurable: true
  38684. });
  38685. ;
  38686. ;
  38687. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38688. /**
  38689. * The camera exposure used on this material.
  38690. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38691. * This corresponds to a photographic exposure.
  38692. */
  38693. get: function () {
  38694. return this._imageProcessingConfiguration.exposure;
  38695. },
  38696. /**
  38697. * The camera exposure used on this material.
  38698. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38699. * This corresponds to a photographic exposure.
  38700. */
  38701. set: function (value) {
  38702. this._imageProcessingConfiguration.exposure = value;
  38703. },
  38704. enumerable: true,
  38705. configurable: true
  38706. });
  38707. ;
  38708. ;
  38709. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38710. /**
  38711. * Gets The camera contrast used on this material.
  38712. */
  38713. get: function () {
  38714. return this._imageProcessingConfiguration.contrast;
  38715. },
  38716. /**
  38717. * Sets The camera contrast used on this material.
  38718. */
  38719. set: function (value) {
  38720. this._imageProcessingConfiguration.contrast = value;
  38721. },
  38722. enumerable: true,
  38723. configurable: true
  38724. });
  38725. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38726. /**
  38727. * Gets the Color Grading 2D Lookup Texture.
  38728. */
  38729. get: function () {
  38730. return this._imageProcessingConfiguration.colorGradingTexture;
  38731. },
  38732. /**
  38733. * Sets the Color Grading 2D Lookup Texture.
  38734. */
  38735. set: function (value) {
  38736. this._imageProcessingConfiguration.colorGradingTexture = value;
  38737. },
  38738. enumerable: true,
  38739. configurable: true
  38740. });
  38741. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38742. /**
  38743. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38744. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38745. * 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;
  38746. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38747. */
  38748. get: function () {
  38749. return this._imageProcessingConfiguration.colorCurves;
  38750. },
  38751. /**
  38752. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38753. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38754. * 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;
  38755. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38756. */
  38757. set: function (value) {
  38758. this._imageProcessingConfiguration.colorCurves = value;
  38759. },
  38760. enumerable: true,
  38761. configurable: true
  38762. });
  38763. StandardMaterial.prototype.getClassName = function () {
  38764. return "StandardMaterial";
  38765. };
  38766. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38767. get: function () {
  38768. return this._useLogarithmicDepth;
  38769. },
  38770. set: function (value) {
  38771. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38772. this._markAllSubMeshesAsMiscDirty();
  38773. },
  38774. enumerable: true,
  38775. configurable: true
  38776. });
  38777. StandardMaterial.prototype.needAlphaBlending = function () {
  38778. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38779. };
  38780. StandardMaterial.prototype.needAlphaTesting = function () {
  38781. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38782. };
  38783. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38784. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38785. };
  38786. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38787. return this._diffuseTexture;
  38788. };
  38789. /**
  38790. * Child classes can use it to update shaders
  38791. */
  38792. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38793. if (useInstances === void 0) { useInstances = false; }
  38794. if (subMesh.effect && this.isFrozen) {
  38795. if (this._wasPreviouslyReady && subMesh.effect) {
  38796. return true;
  38797. }
  38798. }
  38799. if (!subMesh._materialDefines) {
  38800. subMesh._materialDefines = new StandardMaterialDefines();
  38801. }
  38802. var scene = this.getScene();
  38803. var defines = subMesh._materialDefines;
  38804. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38805. if (defines._renderId === scene.getRenderId()) {
  38806. return true;
  38807. }
  38808. }
  38809. var engine = scene.getEngine();
  38810. // Lights
  38811. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38812. // Textures
  38813. if (defines._areTexturesDirty) {
  38814. defines._needUVs = false;
  38815. defines.MAINUV1 = false;
  38816. defines.MAINUV2 = false;
  38817. if (scene.texturesEnabled) {
  38818. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38819. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38820. return false;
  38821. }
  38822. else {
  38823. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38824. }
  38825. }
  38826. else {
  38827. defines.DIFFUSE = false;
  38828. }
  38829. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38830. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38831. return false;
  38832. }
  38833. else {
  38834. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38835. }
  38836. }
  38837. else {
  38838. defines.AMBIENT = false;
  38839. }
  38840. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38841. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38842. return false;
  38843. }
  38844. else {
  38845. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38846. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38847. }
  38848. }
  38849. else {
  38850. defines.OPACITY = false;
  38851. }
  38852. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38853. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38854. return false;
  38855. }
  38856. else {
  38857. defines._needNormals = true;
  38858. defines.REFLECTION = true;
  38859. defines.ROUGHNESS = (this._roughness > 0);
  38860. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38861. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38862. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38863. switch (this._reflectionTexture.coordinatesMode) {
  38864. case BABYLON.Texture.CUBIC_MODE:
  38865. case BABYLON.Texture.INVCUBIC_MODE:
  38866. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38867. break;
  38868. case BABYLON.Texture.EXPLICIT_MODE:
  38869. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38870. break;
  38871. case BABYLON.Texture.PLANAR_MODE:
  38872. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38873. break;
  38874. case BABYLON.Texture.PROJECTION_MODE:
  38875. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38876. break;
  38877. case BABYLON.Texture.SKYBOX_MODE:
  38878. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38879. break;
  38880. case BABYLON.Texture.SPHERICAL_MODE:
  38881. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38882. break;
  38883. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38884. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38885. break;
  38886. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38887. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38888. break;
  38889. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38890. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38891. break;
  38892. }
  38893. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38894. }
  38895. }
  38896. else {
  38897. defines.REFLECTION = false;
  38898. }
  38899. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38900. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38901. return false;
  38902. }
  38903. else {
  38904. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38905. }
  38906. }
  38907. else {
  38908. defines.EMISSIVE = false;
  38909. }
  38910. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38911. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38912. return false;
  38913. }
  38914. else {
  38915. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38916. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38917. }
  38918. }
  38919. else {
  38920. defines.LIGHTMAP = false;
  38921. }
  38922. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38923. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38924. return false;
  38925. }
  38926. else {
  38927. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38928. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38929. }
  38930. }
  38931. else {
  38932. defines.SPECULAR = false;
  38933. }
  38934. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38935. // Bump texure can not be not blocking.
  38936. if (!this._bumpTexture.isReady()) {
  38937. return false;
  38938. }
  38939. else {
  38940. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38941. defines.PARALLAX = this._useParallax;
  38942. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38943. }
  38944. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38945. }
  38946. else {
  38947. defines.BUMP = false;
  38948. }
  38949. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38950. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38951. return false;
  38952. }
  38953. else {
  38954. defines._needUVs = true;
  38955. defines.REFRACTION = true;
  38956. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38957. }
  38958. }
  38959. else {
  38960. defines.REFRACTION = false;
  38961. }
  38962. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38963. }
  38964. else {
  38965. defines.DIFFUSE = false;
  38966. defines.AMBIENT = false;
  38967. defines.OPACITY = false;
  38968. defines.REFLECTION = false;
  38969. defines.EMISSIVE = false;
  38970. defines.LIGHTMAP = false;
  38971. defines.BUMP = false;
  38972. defines.REFRACTION = false;
  38973. }
  38974. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38975. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38976. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38977. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38978. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38979. }
  38980. if (defines._areImageProcessingDirty) {
  38981. if (!this._imageProcessingConfiguration.isReady()) {
  38982. return false;
  38983. }
  38984. this._imageProcessingConfiguration.prepareDefines(defines);
  38985. }
  38986. if (defines._areFresnelDirty) {
  38987. if (StandardMaterial.FresnelEnabled) {
  38988. // Fresnel
  38989. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38990. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38991. this._reflectionFresnelParameters) {
  38992. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38993. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38994. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38995. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38996. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38997. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38998. defines._needNormals = true;
  38999. defines.FRESNEL = true;
  39000. }
  39001. }
  39002. else {
  39003. defines.FRESNEL = false;
  39004. }
  39005. }
  39006. // Misc.
  39007. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39008. // Attribs
  39009. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39010. // Values that need to be evaluated on every frame
  39011. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39012. // Get correct effect
  39013. if (defines.isDirty) {
  39014. defines.markAsProcessed();
  39015. scene.resetCachedMaterial();
  39016. // Fallbacks
  39017. var fallbacks = new BABYLON.EffectFallbacks();
  39018. if (defines.REFLECTION) {
  39019. fallbacks.addFallback(0, "REFLECTION");
  39020. }
  39021. if (defines.SPECULAR) {
  39022. fallbacks.addFallback(0, "SPECULAR");
  39023. }
  39024. if (defines.BUMP) {
  39025. fallbacks.addFallback(0, "BUMP");
  39026. }
  39027. if (defines.PARALLAX) {
  39028. fallbacks.addFallback(1, "PARALLAX");
  39029. }
  39030. if (defines.PARALLAXOCCLUSION) {
  39031. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  39032. }
  39033. if (defines.SPECULAROVERALPHA) {
  39034. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  39035. }
  39036. if (defines.FOG) {
  39037. fallbacks.addFallback(1, "FOG");
  39038. }
  39039. if (defines.POINTSIZE) {
  39040. fallbacks.addFallback(0, "POINTSIZE");
  39041. }
  39042. if (defines.LOGARITHMICDEPTH) {
  39043. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  39044. }
  39045. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  39046. if (defines.SPECULARTERM) {
  39047. fallbacks.addFallback(0, "SPECULARTERM");
  39048. }
  39049. if (defines.DIFFUSEFRESNEL) {
  39050. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  39051. }
  39052. if (defines.OPACITYFRESNEL) {
  39053. fallbacks.addFallback(2, "OPACITYFRESNEL");
  39054. }
  39055. if (defines.REFLECTIONFRESNEL) {
  39056. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  39057. }
  39058. if (defines.EMISSIVEFRESNEL) {
  39059. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  39060. }
  39061. if (defines.FRESNEL) {
  39062. fallbacks.addFallback(4, "FRESNEL");
  39063. }
  39064. //Attributes
  39065. var attribs = [BABYLON.VertexBuffer.PositionKind];
  39066. if (defines.NORMAL) {
  39067. attribs.push(BABYLON.VertexBuffer.NormalKind);
  39068. }
  39069. if (defines.UV1) {
  39070. attribs.push(BABYLON.VertexBuffer.UVKind);
  39071. }
  39072. if (defines.UV2) {
  39073. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  39074. }
  39075. if (defines.VERTEXCOLOR) {
  39076. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39077. }
  39078. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39079. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39080. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39081. var shaderName = "default";
  39082. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39083. "vFogInfos", "vFogColor", "pointSize",
  39084. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39085. "mBones",
  39086. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39087. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39088. "vReflectionPosition", "vReflectionSize",
  39089. "logarithmicDepthConstant", "vTangentSpaceParams"
  39090. ];
  39091. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39092. var uniformBuffers = ["Material", "Scene"];
  39093. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39094. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39095. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39096. uniformsNames: uniforms,
  39097. uniformBuffersNames: uniformBuffers,
  39098. samplers: samplers,
  39099. defines: defines,
  39100. maxSimultaneousLights: this._maxSimultaneousLights
  39101. });
  39102. if (this.customShaderNameResolve) {
  39103. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39104. }
  39105. var join = defines.toString();
  39106. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39107. attributes: attribs,
  39108. uniformsNames: uniforms,
  39109. uniformBuffersNames: uniformBuffers,
  39110. samplers: samplers,
  39111. defines: join,
  39112. fallbacks: fallbacks,
  39113. onCompiled: this.onCompiled,
  39114. onError: this.onError,
  39115. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39116. }, engine), defines);
  39117. this.buildUniformLayout();
  39118. }
  39119. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39120. return false;
  39121. }
  39122. defines._renderId = scene.getRenderId();
  39123. this._wasPreviouslyReady = true;
  39124. return true;
  39125. };
  39126. StandardMaterial.prototype.buildUniformLayout = function () {
  39127. // Order is important !
  39128. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39129. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39130. this._uniformBuffer.addUniform("opacityParts", 4);
  39131. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39132. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39133. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39134. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39135. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39136. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39137. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39138. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39139. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39140. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39141. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39142. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39143. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39144. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39145. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39146. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39147. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39148. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39149. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39150. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39151. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39152. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39153. this._uniformBuffer.addUniform("specularMatrix", 16);
  39154. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39155. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39156. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39157. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39158. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39159. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39160. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39161. this._uniformBuffer.addUniform("pointSize", 1);
  39162. this._uniformBuffer.create();
  39163. };
  39164. StandardMaterial.prototype.unbind = function () {
  39165. if (this._activeEffect) {
  39166. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39167. this._activeEffect.setTexture("reflection2DSampler", null);
  39168. }
  39169. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39170. this._activeEffect.setTexture("refraction2DSampler", null);
  39171. }
  39172. }
  39173. _super.prototype.unbind.call(this);
  39174. };
  39175. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39176. var scene = this.getScene();
  39177. var defines = subMesh._materialDefines;
  39178. if (!defines) {
  39179. return;
  39180. }
  39181. var effect = subMesh.effect;
  39182. if (!effect) {
  39183. return;
  39184. }
  39185. this._activeEffect = effect;
  39186. // Matrices
  39187. this.bindOnlyWorldMatrix(world);
  39188. // Normal Matrix
  39189. if (defines.OBJECTSPACE_NORMALMAP) {
  39190. world.toNormalMatrix(this._normalMatrix);
  39191. this.bindOnlyNormalMatrix(this._normalMatrix);
  39192. }
  39193. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39194. // Bones
  39195. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39196. if (mustRebind) {
  39197. this._uniformBuffer.bindToEffect(effect, "Material");
  39198. this.bindViewProjection(effect);
  39199. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39200. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39201. // Fresnel
  39202. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39203. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39204. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39205. }
  39206. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39207. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39208. }
  39209. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39210. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39211. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39212. }
  39213. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39214. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39215. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39216. }
  39217. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39218. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39219. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39220. }
  39221. }
  39222. // Textures
  39223. if (scene.texturesEnabled) {
  39224. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39225. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39226. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39227. }
  39228. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39229. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39230. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39231. }
  39232. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39233. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39234. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39235. }
  39236. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39237. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39238. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39239. if (this._reflectionTexture.boundingBoxSize) {
  39240. var cubeTexture = this._reflectionTexture;
  39241. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39242. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39243. }
  39244. }
  39245. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39246. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39247. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39248. }
  39249. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39250. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39251. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39252. }
  39253. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39254. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39255. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39256. }
  39257. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39258. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39259. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39260. if (scene._mirroredCameraPosition) {
  39261. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39262. }
  39263. else {
  39264. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39265. }
  39266. }
  39267. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39268. var depth = 1.0;
  39269. if (!this._refractionTexture.isCube) {
  39270. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39271. if (this._refractionTexture.depth) {
  39272. depth = this._refractionTexture.depth;
  39273. }
  39274. }
  39275. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39276. }
  39277. }
  39278. // Point size
  39279. if (this.pointsCloud) {
  39280. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39281. }
  39282. if (defines.SPECULARTERM) {
  39283. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39284. }
  39285. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39286. // Diffuse
  39287. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39288. }
  39289. // Textures
  39290. if (scene.texturesEnabled) {
  39291. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39292. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39293. }
  39294. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39295. effect.setTexture("ambientSampler", this._ambientTexture);
  39296. }
  39297. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39298. effect.setTexture("opacitySampler", this._opacityTexture);
  39299. }
  39300. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39301. if (this._reflectionTexture.isCube) {
  39302. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39303. }
  39304. else {
  39305. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39306. }
  39307. }
  39308. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39309. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39310. }
  39311. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39312. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39313. }
  39314. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39315. effect.setTexture("specularSampler", this._specularTexture);
  39316. }
  39317. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39318. effect.setTexture("bumpSampler", this._bumpTexture);
  39319. }
  39320. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39321. var depth = 1.0;
  39322. if (this._refractionTexture.isCube) {
  39323. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39324. }
  39325. else {
  39326. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39327. }
  39328. }
  39329. }
  39330. // Clip plane
  39331. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39332. // Colors
  39333. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39334. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39335. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39336. }
  39337. if (mustRebind || !this.isFrozen) {
  39338. // Lights
  39339. if (scene.lightsEnabled && !this._disableLighting) {
  39340. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39341. }
  39342. // View
  39343. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39344. this.bindView(effect);
  39345. }
  39346. // Fog
  39347. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39348. // Morph targets
  39349. if (defines.NUM_MORPH_INFLUENCERS) {
  39350. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39351. }
  39352. // Log. depth
  39353. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39354. // image processing
  39355. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39356. this._imageProcessingConfiguration.bind(this._activeEffect);
  39357. }
  39358. }
  39359. this._uniformBuffer.update();
  39360. this._afterBind(mesh, this._activeEffect);
  39361. };
  39362. StandardMaterial.prototype.getAnimatables = function () {
  39363. var results = [];
  39364. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39365. results.push(this._diffuseTexture);
  39366. }
  39367. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39368. results.push(this._ambientTexture);
  39369. }
  39370. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39371. results.push(this._opacityTexture);
  39372. }
  39373. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39374. results.push(this._reflectionTexture);
  39375. }
  39376. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39377. results.push(this._emissiveTexture);
  39378. }
  39379. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39380. results.push(this._specularTexture);
  39381. }
  39382. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39383. results.push(this._bumpTexture);
  39384. }
  39385. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39386. results.push(this._lightmapTexture);
  39387. }
  39388. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39389. results.push(this._refractionTexture);
  39390. }
  39391. return results;
  39392. };
  39393. StandardMaterial.prototype.getActiveTextures = function () {
  39394. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39395. if (this._diffuseTexture) {
  39396. activeTextures.push(this._diffuseTexture);
  39397. }
  39398. if (this._ambientTexture) {
  39399. activeTextures.push(this._ambientTexture);
  39400. }
  39401. if (this._opacityTexture) {
  39402. activeTextures.push(this._opacityTexture);
  39403. }
  39404. if (this._reflectionTexture) {
  39405. activeTextures.push(this._reflectionTexture);
  39406. }
  39407. if (this._emissiveTexture) {
  39408. activeTextures.push(this._emissiveTexture);
  39409. }
  39410. if (this._specularTexture) {
  39411. activeTextures.push(this._specularTexture);
  39412. }
  39413. if (this._bumpTexture) {
  39414. activeTextures.push(this._bumpTexture);
  39415. }
  39416. if (this._lightmapTexture) {
  39417. activeTextures.push(this._lightmapTexture);
  39418. }
  39419. if (this._refractionTexture) {
  39420. activeTextures.push(this._refractionTexture);
  39421. }
  39422. return activeTextures;
  39423. };
  39424. StandardMaterial.prototype.hasTexture = function (texture) {
  39425. if (_super.prototype.hasTexture.call(this, texture)) {
  39426. return true;
  39427. }
  39428. if (this._diffuseTexture === texture) {
  39429. return true;
  39430. }
  39431. if (this._ambientTexture === texture) {
  39432. return true;
  39433. }
  39434. if (this._opacityTexture === texture) {
  39435. return true;
  39436. }
  39437. if (this._reflectionTexture === texture) {
  39438. return true;
  39439. }
  39440. if (this._emissiveTexture === texture) {
  39441. return true;
  39442. }
  39443. if (this._specularTexture === texture) {
  39444. return true;
  39445. }
  39446. if (this._bumpTexture === texture) {
  39447. return true;
  39448. }
  39449. if (this._lightmapTexture === texture) {
  39450. return true;
  39451. }
  39452. if (this._refractionTexture === texture) {
  39453. return true;
  39454. }
  39455. return false;
  39456. };
  39457. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39458. if (forceDisposeTextures) {
  39459. if (this._diffuseTexture) {
  39460. this._diffuseTexture.dispose();
  39461. }
  39462. if (this._ambientTexture) {
  39463. this._ambientTexture.dispose();
  39464. }
  39465. if (this._opacityTexture) {
  39466. this._opacityTexture.dispose();
  39467. }
  39468. if (this._reflectionTexture) {
  39469. this._reflectionTexture.dispose();
  39470. }
  39471. if (this._emissiveTexture) {
  39472. this._emissiveTexture.dispose();
  39473. }
  39474. if (this._specularTexture) {
  39475. this._specularTexture.dispose();
  39476. }
  39477. if (this._bumpTexture) {
  39478. this._bumpTexture.dispose();
  39479. }
  39480. if (this._lightmapTexture) {
  39481. this._lightmapTexture.dispose();
  39482. }
  39483. if (this._refractionTexture) {
  39484. this._refractionTexture.dispose();
  39485. }
  39486. }
  39487. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39488. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39489. }
  39490. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39491. };
  39492. StandardMaterial.prototype.clone = function (name) {
  39493. var _this = this;
  39494. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39495. result.name = name;
  39496. result.id = name;
  39497. return result;
  39498. };
  39499. StandardMaterial.prototype.serialize = function () {
  39500. return BABYLON.SerializationHelper.Serialize(this);
  39501. };
  39502. // Statics
  39503. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39504. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39505. };
  39506. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39507. get: function () {
  39508. return StandardMaterial._DiffuseTextureEnabled;
  39509. },
  39510. set: function (value) {
  39511. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39512. return;
  39513. }
  39514. StandardMaterial._DiffuseTextureEnabled = value;
  39515. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39516. },
  39517. enumerable: true,
  39518. configurable: true
  39519. });
  39520. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39521. get: function () {
  39522. return StandardMaterial._AmbientTextureEnabled;
  39523. },
  39524. set: function (value) {
  39525. if (StandardMaterial._AmbientTextureEnabled === value) {
  39526. return;
  39527. }
  39528. StandardMaterial._AmbientTextureEnabled = value;
  39529. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39530. },
  39531. enumerable: true,
  39532. configurable: true
  39533. });
  39534. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39535. get: function () {
  39536. return StandardMaterial._OpacityTextureEnabled;
  39537. },
  39538. set: function (value) {
  39539. if (StandardMaterial._OpacityTextureEnabled === value) {
  39540. return;
  39541. }
  39542. StandardMaterial._OpacityTextureEnabled = value;
  39543. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39544. },
  39545. enumerable: true,
  39546. configurable: true
  39547. });
  39548. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39549. get: function () {
  39550. return StandardMaterial._ReflectionTextureEnabled;
  39551. },
  39552. set: function (value) {
  39553. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39554. return;
  39555. }
  39556. StandardMaterial._ReflectionTextureEnabled = value;
  39557. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39558. },
  39559. enumerable: true,
  39560. configurable: true
  39561. });
  39562. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39563. get: function () {
  39564. return StandardMaterial._EmissiveTextureEnabled;
  39565. },
  39566. set: function (value) {
  39567. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39568. return;
  39569. }
  39570. StandardMaterial._EmissiveTextureEnabled = value;
  39571. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39572. },
  39573. enumerable: true,
  39574. configurable: true
  39575. });
  39576. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39577. get: function () {
  39578. return StandardMaterial._SpecularTextureEnabled;
  39579. },
  39580. set: function (value) {
  39581. if (StandardMaterial._SpecularTextureEnabled === value) {
  39582. return;
  39583. }
  39584. StandardMaterial._SpecularTextureEnabled = value;
  39585. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39586. },
  39587. enumerable: true,
  39588. configurable: true
  39589. });
  39590. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39591. get: function () {
  39592. return StandardMaterial._BumpTextureEnabled;
  39593. },
  39594. set: function (value) {
  39595. if (StandardMaterial._BumpTextureEnabled === value) {
  39596. return;
  39597. }
  39598. StandardMaterial._BumpTextureEnabled = value;
  39599. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39600. },
  39601. enumerable: true,
  39602. configurable: true
  39603. });
  39604. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39605. get: function () {
  39606. return StandardMaterial._LightmapTextureEnabled;
  39607. },
  39608. set: function (value) {
  39609. if (StandardMaterial._LightmapTextureEnabled === value) {
  39610. return;
  39611. }
  39612. StandardMaterial._LightmapTextureEnabled = value;
  39613. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39614. },
  39615. enumerable: true,
  39616. configurable: true
  39617. });
  39618. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39619. get: function () {
  39620. return StandardMaterial._RefractionTextureEnabled;
  39621. },
  39622. set: function (value) {
  39623. if (StandardMaterial._RefractionTextureEnabled === value) {
  39624. return;
  39625. }
  39626. StandardMaterial._RefractionTextureEnabled = value;
  39627. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39628. },
  39629. enumerable: true,
  39630. configurable: true
  39631. });
  39632. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39633. get: function () {
  39634. return StandardMaterial._ColorGradingTextureEnabled;
  39635. },
  39636. set: function (value) {
  39637. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39638. return;
  39639. }
  39640. StandardMaterial._ColorGradingTextureEnabled = value;
  39641. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39642. },
  39643. enumerable: true,
  39644. configurable: true
  39645. });
  39646. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39647. get: function () {
  39648. return StandardMaterial._FresnelEnabled;
  39649. },
  39650. set: function (value) {
  39651. if (StandardMaterial._FresnelEnabled === value) {
  39652. return;
  39653. }
  39654. StandardMaterial._FresnelEnabled = value;
  39655. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39656. },
  39657. enumerable: true,
  39658. configurable: true
  39659. });
  39660. // Flags used to enable or disable a type of texture for all Standard Materials
  39661. StandardMaterial._DiffuseTextureEnabled = true;
  39662. StandardMaterial._AmbientTextureEnabled = true;
  39663. StandardMaterial._OpacityTextureEnabled = true;
  39664. StandardMaterial._ReflectionTextureEnabled = true;
  39665. StandardMaterial._EmissiveTextureEnabled = true;
  39666. StandardMaterial._SpecularTextureEnabled = true;
  39667. StandardMaterial._BumpTextureEnabled = true;
  39668. StandardMaterial._LightmapTextureEnabled = true;
  39669. StandardMaterial._RefractionTextureEnabled = true;
  39670. StandardMaterial._ColorGradingTextureEnabled = true;
  39671. StandardMaterial._FresnelEnabled = true;
  39672. __decorate([
  39673. BABYLON.serializeAsTexture("diffuseTexture")
  39674. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39675. __decorate([
  39676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39677. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39678. __decorate([
  39679. BABYLON.serializeAsTexture("ambientTexture")
  39680. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39681. __decorate([
  39682. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39683. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39684. __decorate([
  39685. BABYLON.serializeAsTexture("opacityTexture")
  39686. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39687. __decorate([
  39688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39689. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39690. __decorate([
  39691. BABYLON.serializeAsTexture("reflectionTexture")
  39692. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39693. __decorate([
  39694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39695. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39696. __decorate([
  39697. BABYLON.serializeAsTexture("emissiveTexture")
  39698. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39699. __decorate([
  39700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39701. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39702. __decorate([
  39703. BABYLON.serializeAsTexture("specularTexture")
  39704. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39705. __decorate([
  39706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39707. ], StandardMaterial.prototype, "specularTexture", void 0);
  39708. __decorate([
  39709. BABYLON.serializeAsTexture("bumpTexture")
  39710. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39711. __decorate([
  39712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39713. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39714. __decorate([
  39715. BABYLON.serializeAsTexture("lightmapTexture")
  39716. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39717. __decorate([
  39718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39719. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39720. __decorate([
  39721. BABYLON.serializeAsTexture("refractionTexture")
  39722. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39723. __decorate([
  39724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39725. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39726. __decorate([
  39727. BABYLON.serializeAsColor3("ambient")
  39728. ], StandardMaterial.prototype, "ambientColor", void 0);
  39729. __decorate([
  39730. BABYLON.serializeAsColor3("diffuse")
  39731. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39732. __decorate([
  39733. BABYLON.serializeAsColor3("specular")
  39734. ], StandardMaterial.prototype, "specularColor", void 0);
  39735. __decorate([
  39736. BABYLON.serializeAsColor3("emissive")
  39737. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39738. __decorate([
  39739. BABYLON.serialize()
  39740. ], StandardMaterial.prototype, "specularPower", void 0);
  39741. __decorate([
  39742. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39743. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39744. __decorate([
  39745. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39746. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39747. __decorate([
  39748. BABYLON.serialize("useEmissiveAsIllumination")
  39749. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39750. __decorate([
  39751. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39752. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39753. __decorate([
  39754. BABYLON.serialize("linkEmissiveWithDiffuse")
  39755. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39756. __decorate([
  39757. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39758. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39759. __decorate([
  39760. BABYLON.serialize("useSpecularOverAlpha")
  39761. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39762. __decorate([
  39763. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39764. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39765. __decorate([
  39766. BABYLON.serialize("useReflectionOverAlpha")
  39767. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39768. __decorate([
  39769. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39770. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39771. __decorate([
  39772. BABYLON.serialize("disableLighting")
  39773. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39774. __decorate([
  39775. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39776. ], StandardMaterial.prototype, "disableLighting", void 0);
  39777. __decorate([
  39778. BABYLON.serialize("useObjectSpaceNormalMap")
  39779. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39780. __decorate([
  39781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39782. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39783. __decorate([
  39784. BABYLON.serialize("useParallax")
  39785. ], StandardMaterial.prototype, "_useParallax", void 0);
  39786. __decorate([
  39787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39788. ], StandardMaterial.prototype, "useParallax", void 0);
  39789. __decorate([
  39790. BABYLON.serialize("useParallaxOcclusion")
  39791. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39792. __decorate([
  39793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39794. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39795. __decorate([
  39796. BABYLON.serialize()
  39797. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39798. __decorate([
  39799. BABYLON.serialize("roughness")
  39800. ], StandardMaterial.prototype, "_roughness", void 0);
  39801. __decorate([
  39802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39803. ], StandardMaterial.prototype, "roughness", void 0);
  39804. __decorate([
  39805. BABYLON.serialize()
  39806. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39807. __decorate([
  39808. BABYLON.serialize()
  39809. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39810. __decorate([
  39811. BABYLON.serialize("useLightmapAsShadowmap")
  39812. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39813. __decorate([
  39814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39815. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39816. __decorate([
  39817. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39818. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39819. __decorate([
  39820. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39821. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39822. __decorate([
  39823. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39824. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39825. __decorate([
  39826. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39827. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39828. __decorate([
  39829. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39830. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39831. __decorate([
  39832. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39833. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39834. __decorate([
  39835. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39836. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39837. __decorate([
  39838. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39839. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39840. __decorate([
  39841. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39842. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39843. __decorate([
  39844. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39845. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39846. __decorate([
  39847. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39848. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39849. __decorate([
  39850. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39851. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39852. __decorate([
  39853. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39854. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39855. __decorate([
  39856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39857. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39858. __decorate([
  39859. BABYLON.serialize("maxSimultaneousLights")
  39860. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39861. __decorate([
  39862. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39863. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39864. __decorate([
  39865. BABYLON.serialize("invertNormalMapX")
  39866. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39867. __decorate([
  39868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39869. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39870. __decorate([
  39871. BABYLON.serialize("invertNormalMapY")
  39872. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39873. __decorate([
  39874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39875. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39876. __decorate([
  39877. BABYLON.serialize("twoSidedLighting")
  39878. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39879. __decorate([
  39880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39881. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39882. __decorate([
  39883. BABYLON.serialize()
  39884. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39885. return StandardMaterial;
  39886. }(BABYLON.PushMaterial));
  39887. BABYLON.StandardMaterial = StandardMaterial;
  39888. })(BABYLON || (BABYLON = {}));
  39889. //# sourceMappingURL=babylon.standardMaterial.js.map
  39890. var BABYLON;
  39891. (function (BABYLON) {
  39892. /**
  39893. * Manages the defines for the PBR Material.
  39894. */
  39895. var PBRMaterialDefines = /** @class */ (function (_super) {
  39896. __extends(PBRMaterialDefines, _super);
  39897. /**
  39898. * Initializes the PBR Material defines.
  39899. */
  39900. function PBRMaterialDefines() {
  39901. var _this = _super.call(this) || this;
  39902. _this.PBR = true;
  39903. _this.MAINUV1 = false;
  39904. _this.MAINUV2 = false;
  39905. _this.UV1 = false;
  39906. _this.UV2 = false;
  39907. _this.ALBEDO = false;
  39908. _this.ALBEDODIRECTUV = 0;
  39909. _this.VERTEXCOLOR = false;
  39910. _this.AMBIENT = false;
  39911. _this.AMBIENTDIRECTUV = 0;
  39912. _this.AMBIENTINGRAYSCALE = false;
  39913. _this.OPACITY = false;
  39914. _this.VERTEXALPHA = false;
  39915. _this.OPACITYDIRECTUV = 0;
  39916. _this.OPACITYRGB = false;
  39917. _this.ALPHATEST = false;
  39918. _this.DEPTHPREPASS = false;
  39919. _this.ALPHABLEND = false;
  39920. _this.ALPHAFROMALBEDO = false;
  39921. _this.ALPHATESTVALUE = 0.5;
  39922. _this.SPECULAROVERALPHA = false;
  39923. _this.RADIANCEOVERALPHA = false;
  39924. _this.ALPHAFRESNEL = false;
  39925. _this.LINEARALPHAFRESNEL = false;
  39926. _this.PREMULTIPLYALPHA = false;
  39927. _this.EMISSIVE = false;
  39928. _this.EMISSIVEDIRECTUV = 0;
  39929. _this.REFLECTIVITY = false;
  39930. _this.REFLECTIVITYDIRECTUV = 0;
  39931. _this.SPECULARTERM = false;
  39932. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39933. _this.MICROSURFACEAUTOMATIC = false;
  39934. _this.LODBASEDMICROSFURACE = false;
  39935. _this.MICROSURFACEMAP = false;
  39936. _this.MICROSURFACEMAPDIRECTUV = 0;
  39937. _this.METALLICWORKFLOW = false;
  39938. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39939. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39940. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39941. _this.AOSTOREINMETALMAPRED = false;
  39942. _this.ENVIRONMENTBRDF = false;
  39943. _this.NORMAL = false;
  39944. _this.TANGENT = false;
  39945. _this.BUMP = false;
  39946. _this.BUMPDIRECTUV = 0;
  39947. _this.OBJECTSPACE_NORMALMAP = false;
  39948. _this.PARALLAX = false;
  39949. _this.PARALLAXOCCLUSION = false;
  39950. _this.NORMALXYSCALE = true;
  39951. _this.LIGHTMAP = false;
  39952. _this.LIGHTMAPDIRECTUV = 0;
  39953. _this.USELIGHTMAPASSHADOWMAP = false;
  39954. _this.REFLECTION = false;
  39955. _this.REFLECTIONMAP_3D = false;
  39956. _this.REFLECTIONMAP_SPHERICAL = false;
  39957. _this.REFLECTIONMAP_PLANAR = false;
  39958. _this.REFLECTIONMAP_CUBIC = false;
  39959. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39960. _this.REFLECTIONMAP_PROJECTION = false;
  39961. _this.REFLECTIONMAP_SKYBOX = false;
  39962. _this.REFLECTIONMAP_EXPLICIT = false;
  39963. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39964. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39965. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39966. _this.INVERTCUBICMAP = false;
  39967. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39968. _this.USESPHERICALINVERTEX = false;
  39969. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39970. _this.LODINREFLECTIONALPHA = false;
  39971. _this.GAMMAREFLECTION = false;
  39972. _this.RADIANCEOCCLUSION = false;
  39973. _this.HORIZONOCCLUSION = false;
  39974. _this.REFRACTION = false;
  39975. _this.REFRACTIONMAP_3D = false;
  39976. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39977. _this.LODINREFRACTIONALPHA = false;
  39978. _this.GAMMAREFRACTION = false;
  39979. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39980. _this.INSTANCES = false;
  39981. _this.NUM_BONE_INFLUENCERS = 0;
  39982. _this.BonesPerMesh = 0;
  39983. _this.NONUNIFORMSCALING = false;
  39984. _this.MORPHTARGETS = false;
  39985. _this.MORPHTARGETS_NORMAL = false;
  39986. _this.MORPHTARGETS_TANGENT = false;
  39987. _this.NUM_MORPH_INFLUENCERS = 0;
  39988. _this.IMAGEPROCESSING = false;
  39989. _this.VIGNETTE = false;
  39990. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39991. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39992. _this.TONEMAPPING = false;
  39993. _this.CONTRAST = false;
  39994. _this.COLORCURVES = false;
  39995. _this.COLORGRADING = false;
  39996. _this.COLORGRADING3D = false;
  39997. _this.SAMPLER3DGREENDEPTH = false;
  39998. _this.SAMPLER3DBGRMAP = false;
  39999. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40000. _this.EXPOSURE = false;
  40001. _this.USEPHYSICALLIGHTFALLOFF = false;
  40002. _this.TWOSIDEDLIGHTING = false;
  40003. _this.SHADOWFLOAT = false;
  40004. _this.CLIPPLANE = false;
  40005. _this.POINTSIZE = false;
  40006. _this.FOG = false;
  40007. _this.LOGARITHMICDEPTH = false;
  40008. _this.FORCENORMALFORWARD = false;
  40009. _this.rebuild();
  40010. return _this;
  40011. }
  40012. /**
  40013. * Resets the PBR Material defines.
  40014. */
  40015. PBRMaterialDefines.prototype.reset = function () {
  40016. _super.prototype.reset.call(this);
  40017. this.ALPHATESTVALUE = 0.5;
  40018. this.PBR = true;
  40019. };
  40020. return PBRMaterialDefines;
  40021. }(BABYLON.MaterialDefines));
  40022. /**
  40023. * The Physically based material base class of BJS.
  40024. *
  40025. * This offers the main features of a standard PBR material.
  40026. * For more information, please refer to the documentation :
  40027. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  40028. */
  40029. var PBRBaseMaterial = /** @class */ (function (_super) {
  40030. __extends(PBRBaseMaterial, _super);
  40031. /**
  40032. * Instantiates a new PBRMaterial instance.
  40033. *
  40034. * @param name The material name
  40035. * @param scene The scene the material will be use in.
  40036. */
  40037. function PBRBaseMaterial(name, scene) {
  40038. var _this = _super.call(this, name, scene) || this;
  40039. /**
  40040. * Intensity of the direct lights e.g. the four lights available in your scene.
  40041. * This impacts both the direct diffuse and specular highlights.
  40042. */
  40043. _this._directIntensity = 1.0;
  40044. /**
  40045. * Intensity of the emissive part of the material.
  40046. * This helps controlling the emissive effect without modifying the emissive color.
  40047. */
  40048. _this._emissiveIntensity = 1.0;
  40049. /**
  40050. * Intensity of the environment e.g. how much the environment will light the object
  40051. * either through harmonics for rough material or through the refelction for shiny ones.
  40052. */
  40053. _this._environmentIntensity = 1.0;
  40054. /**
  40055. * This is a special control allowing the reduction of the specular highlights coming from the
  40056. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  40057. */
  40058. _this._specularIntensity = 1.0;
  40059. /**
  40060. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  40061. */
  40062. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  40063. /**
  40064. * Debug Control allowing disabling the bump map on this material.
  40065. */
  40066. _this._disableBumpMap = false;
  40067. /**
  40068. * AKA Occlusion Texture Intensity in other nomenclature.
  40069. */
  40070. _this._ambientTextureStrength = 1.0;
  40071. /**
  40072. * The color of a material in ambient lighting.
  40073. */
  40074. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  40075. /**
  40076. * AKA Diffuse Color in other nomenclature.
  40077. */
  40078. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40079. /**
  40080. * AKA Specular Color in other nomenclature.
  40081. */
  40082. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40083. /**
  40084. * The color applied when light is reflected from a material.
  40085. */
  40086. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40087. /**
  40088. * The color applied when light is emitted from a material.
  40089. */
  40090. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40091. /**
  40092. * AKA Glossiness in other nomenclature.
  40093. */
  40094. _this._microSurface = 0.9;
  40095. /**
  40096. * source material index of refraction (IOR)' / 'destination material IOR.
  40097. */
  40098. _this._indexOfRefraction = 0.66;
  40099. /**
  40100. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40101. */
  40102. _this._invertRefractionY = false;
  40103. /**
  40104. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40105. * Materials half opaque for instance using refraction could benefit from this control.
  40106. */
  40107. _this._linkRefractionWithTransparency = false;
  40108. /**
  40109. * Specifies that the material will use the light map as a show map.
  40110. */
  40111. _this._useLightmapAsShadowmap = false;
  40112. /**
  40113. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40114. * makes the reflect vector face the model (under horizon).
  40115. */
  40116. _this._useHorizonOcclusion = true;
  40117. /**
  40118. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40119. * too much the area relying on ambient texture to define their ambient occlusion.
  40120. */
  40121. _this._useRadianceOcclusion = true;
  40122. /**
  40123. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40124. */
  40125. _this._useAlphaFromAlbedoTexture = false;
  40126. /**
  40127. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40128. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40129. */
  40130. _this._useSpecularOverAlpha = true;
  40131. /**
  40132. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40133. */
  40134. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40135. /**
  40136. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40137. */
  40138. _this._useRoughnessFromMetallicTextureAlpha = true;
  40139. /**
  40140. * Specifies if the metallic texture contains the roughness information in its green channel.
  40141. */
  40142. _this._useRoughnessFromMetallicTextureGreen = false;
  40143. /**
  40144. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40145. */
  40146. _this._useMetallnessFromMetallicTextureBlue = false;
  40147. /**
  40148. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40149. */
  40150. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40151. /**
  40152. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40153. */
  40154. _this._useAmbientInGrayScale = false;
  40155. /**
  40156. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40157. * The material will try to infer what glossiness each pixel should be.
  40158. */
  40159. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40160. /**
  40161. * BJS is using an harcoded light falloff based on a manually sets up range.
  40162. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40163. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40164. */
  40165. _this._usePhysicalLightFalloff = true;
  40166. /**
  40167. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40168. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40169. */
  40170. _this._useRadianceOverAlpha = true;
  40171. /**
  40172. * Allows using an object space normal map (instead of tangent space).
  40173. */
  40174. _this._useObjectSpaceNormalMap = false;
  40175. /**
  40176. * Allows using the bump map in parallax mode.
  40177. */
  40178. _this._useParallax = false;
  40179. /**
  40180. * Allows using the bump map in parallax occlusion mode.
  40181. */
  40182. _this._useParallaxOcclusion = false;
  40183. /**
  40184. * Controls the scale bias of the parallax mode.
  40185. */
  40186. _this._parallaxScaleBias = 0.05;
  40187. /**
  40188. * If sets to true, disables all the lights affecting the material.
  40189. */
  40190. _this._disableLighting = false;
  40191. /**
  40192. * Number of Simultaneous lights allowed on the material.
  40193. */
  40194. _this._maxSimultaneousLights = 4;
  40195. /**
  40196. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40197. */
  40198. _this._invertNormalMapX = false;
  40199. /**
  40200. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40201. */
  40202. _this._invertNormalMapY = false;
  40203. /**
  40204. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40205. */
  40206. _this._twoSidedLighting = false;
  40207. /**
  40208. * Defines the alpha limits in alpha test mode.
  40209. */
  40210. _this._alphaCutOff = 0.4;
  40211. /**
  40212. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40213. */
  40214. _this._forceAlphaTest = false;
  40215. /**
  40216. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40217. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40218. */
  40219. _this._useAlphaFresnel = false;
  40220. /**
  40221. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40222. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40223. */
  40224. _this._useLinearAlphaFresnel = false;
  40225. /**
  40226. * The transparency mode of the material.
  40227. */
  40228. _this._transparencyMode = null;
  40229. /**
  40230. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40231. * from cos thetav and roughness:
  40232. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40233. */
  40234. _this._environmentBRDFTexture = null;
  40235. /**
  40236. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40237. */
  40238. _this._forceIrradianceInFragment = false;
  40239. /**
  40240. * Force normal to face away from face.
  40241. */
  40242. _this._forceNormalForward = false;
  40243. /**
  40244. * Force metallic workflow.
  40245. */
  40246. _this._forceMetallicWorkflow = false;
  40247. /**
  40248. * Stores the available render targets.
  40249. */
  40250. _this._renderTargets = new BABYLON.SmartArray(16);
  40251. /**
  40252. * Sets the global ambient color for the material used in lighting calculations.
  40253. */
  40254. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40255. // Setup the default processing configuration to the scene.
  40256. _this._attachImageProcessingConfiguration(null);
  40257. _this.getRenderTargetTextures = function () {
  40258. _this._renderTargets.reset();
  40259. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40260. _this._renderTargets.push(_this._reflectionTexture);
  40261. }
  40262. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40263. _this._renderTargets.push(_this._refractionTexture);
  40264. }
  40265. return _this._renderTargets;
  40266. };
  40267. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40268. return _this;
  40269. }
  40270. /**
  40271. * Attaches a new image processing configuration to the PBR Material.
  40272. * @param configuration
  40273. */
  40274. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40275. var _this = this;
  40276. if (configuration === this._imageProcessingConfiguration) {
  40277. return;
  40278. }
  40279. // Detaches observer.
  40280. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40281. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40282. }
  40283. // Pick the scene configuration if needed.
  40284. if (!configuration) {
  40285. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40286. }
  40287. else {
  40288. this._imageProcessingConfiguration = configuration;
  40289. }
  40290. // Attaches observer.
  40291. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40292. _this._markAllSubMeshesAsImageProcessingDirty();
  40293. });
  40294. };
  40295. /**
  40296. * Gets the name of the material class.
  40297. */
  40298. PBRBaseMaterial.prototype.getClassName = function () {
  40299. return "PBRBaseMaterial";
  40300. };
  40301. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40302. /**
  40303. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40304. */
  40305. get: function () {
  40306. return this._useLogarithmicDepth;
  40307. },
  40308. /**
  40309. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40310. */
  40311. set: function (value) {
  40312. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40313. },
  40314. enumerable: true,
  40315. configurable: true
  40316. });
  40317. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40318. /**
  40319. * Gets the current transparency mode.
  40320. */
  40321. get: function () {
  40322. return this._transparencyMode;
  40323. },
  40324. /**
  40325. * Sets the transparency mode of the material.
  40326. */
  40327. set: function (value) {
  40328. if (this._transparencyMode === value) {
  40329. return;
  40330. }
  40331. this._transparencyMode = value;
  40332. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40333. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40334. },
  40335. enumerable: true,
  40336. configurable: true
  40337. });
  40338. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40339. /**
  40340. * Returns true if alpha blending should be disabled.
  40341. */
  40342. get: function () {
  40343. return (this._linkRefractionWithTransparency ||
  40344. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40345. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40346. },
  40347. enumerable: true,
  40348. configurable: true
  40349. });
  40350. /**
  40351. * Specifies whether or not this material should be rendered in alpha blend mode.
  40352. */
  40353. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40354. if (this._disableAlphaBlending) {
  40355. return false;
  40356. }
  40357. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40358. };
  40359. /**
  40360. * Specifies if the mesh will require alpha blending.
  40361. * @param mesh - BJS mesh.
  40362. */
  40363. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40364. if (this._disableAlphaBlending) {
  40365. return false;
  40366. }
  40367. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40368. };
  40369. /**
  40370. * Specifies whether or not this material should be rendered in alpha test mode.
  40371. */
  40372. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40373. if (this._forceAlphaTest) {
  40374. return true;
  40375. }
  40376. if (this._linkRefractionWithTransparency) {
  40377. return false;
  40378. }
  40379. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40380. };
  40381. /**
  40382. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40383. */
  40384. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40385. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40386. };
  40387. /**
  40388. * Gets the texture used for the alpha test.
  40389. */
  40390. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40391. return this._albedoTexture;
  40392. };
  40393. /**
  40394. * Specifies that the submesh is ready to be used.
  40395. * @param mesh - BJS mesh.
  40396. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40397. * @param useInstances - Specifies that instances should be used.
  40398. * @returns - boolean indicating that the submesh is ready or not.
  40399. */
  40400. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40401. if (subMesh.effect && this.isFrozen) {
  40402. if (this._wasPreviouslyReady) {
  40403. return true;
  40404. }
  40405. }
  40406. if (!subMesh._materialDefines) {
  40407. subMesh._materialDefines = new PBRMaterialDefines();
  40408. }
  40409. var defines = subMesh._materialDefines;
  40410. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40411. if (defines._renderId === this.getScene().getRenderId()) {
  40412. return true;
  40413. }
  40414. }
  40415. var scene = this.getScene();
  40416. var engine = scene.getEngine();
  40417. if (defines._areTexturesDirty) {
  40418. if (scene.texturesEnabled) {
  40419. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40420. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40421. return false;
  40422. }
  40423. }
  40424. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40425. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40426. return false;
  40427. }
  40428. }
  40429. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40430. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40431. return false;
  40432. }
  40433. }
  40434. var reflectionTexture = this._getReflectionTexture();
  40435. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40436. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40437. return false;
  40438. }
  40439. }
  40440. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40441. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40442. return false;
  40443. }
  40444. }
  40445. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40446. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40447. return false;
  40448. }
  40449. }
  40450. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40451. if (this._metallicTexture) {
  40452. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40453. return false;
  40454. }
  40455. }
  40456. else if (this._reflectivityTexture) {
  40457. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40458. return false;
  40459. }
  40460. }
  40461. if (this._microSurfaceTexture) {
  40462. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40463. return false;
  40464. }
  40465. }
  40466. }
  40467. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40468. // Bump texture cannot be not blocking.
  40469. if (!this._bumpTexture.isReady()) {
  40470. return false;
  40471. }
  40472. }
  40473. var refractionTexture = this._getRefractionTexture();
  40474. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40475. if (!refractionTexture.isReadyOrNotBlocking()) {
  40476. return false;
  40477. }
  40478. }
  40479. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40480. // This is blocking.
  40481. if (!this._environmentBRDFTexture.isReady()) {
  40482. return false;
  40483. }
  40484. }
  40485. }
  40486. }
  40487. if (defines._areImageProcessingDirty) {
  40488. if (!this._imageProcessingConfiguration.isReady()) {
  40489. return false;
  40490. }
  40491. }
  40492. if (!engine.getCaps().standardDerivatives) {
  40493. var bufferMesh = null;
  40494. if (mesh.getClassName() === "InstancedMesh") {
  40495. bufferMesh = mesh.sourceMesh;
  40496. }
  40497. else if (mesh.getClassName() === "Mesh") {
  40498. bufferMesh = mesh;
  40499. }
  40500. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40501. bufferMesh.createNormals(true);
  40502. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40503. }
  40504. }
  40505. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40506. if (effect) {
  40507. scene.resetCachedMaterial();
  40508. subMesh.setEffect(effect, defines);
  40509. this.buildUniformLayout();
  40510. }
  40511. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40512. return false;
  40513. }
  40514. defines._renderId = scene.getRenderId();
  40515. this._wasPreviouslyReady = true;
  40516. return true;
  40517. };
  40518. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40519. if (onCompiled === void 0) { onCompiled = null; }
  40520. if (onError === void 0) { onError = null; }
  40521. if (useInstances === void 0) { useInstances = null; }
  40522. if (useClipPlane === void 0) { useClipPlane = null; }
  40523. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40524. if (!defines.isDirty) {
  40525. return null;
  40526. }
  40527. defines.markAsProcessed();
  40528. var scene = this.getScene();
  40529. var engine = scene.getEngine();
  40530. // Fallbacks
  40531. var fallbacks = new BABYLON.EffectFallbacks();
  40532. var fallbackRank = 0;
  40533. if (defines.USESPHERICALINVERTEX) {
  40534. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40535. }
  40536. if (defines.FOG) {
  40537. fallbacks.addFallback(fallbackRank, "FOG");
  40538. }
  40539. if (defines.POINTSIZE) {
  40540. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40541. }
  40542. if (defines.LOGARITHMICDEPTH) {
  40543. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40544. }
  40545. if (defines.PARALLAX) {
  40546. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40547. }
  40548. if (defines.PARALLAXOCCLUSION) {
  40549. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40550. }
  40551. if (defines.ENVIRONMENTBRDF) {
  40552. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40553. }
  40554. if (defines.TANGENT) {
  40555. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40556. }
  40557. if (defines.BUMP) {
  40558. fallbacks.addFallback(fallbackRank++, "BUMP");
  40559. }
  40560. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40561. if (defines.SPECULARTERM) {
  40562. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40563. }
  40564. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40565. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40566. }
  40567. if (defines.LIGHTMAP) {
  40568. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40569. }
  40570. if (defines.NORMAL) {
  40571. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40572. }
  40573. if (defines.AMBIENT) {
  40574. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40575. }
  40576. if (defines.EMISSIVE) {
  40577. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40578. }
  40579. if (defines.VERTEXCOLOR) {
  40580. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40581. }
  40582. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40583. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40584. }
  40585. if (defines.MORPHTARGETS) {
  40586. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40587. }
  40588. //Attributes
  40589. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40590. if (defines.NORMAL) {
  40591. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40592. }
  40593. if (defines.TANGENT) {
  40594. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40595. }
  40596. if (defines.UV1) {
  40597. attribs.push(BABYLON.VertexBuffer.UVKind);
  40598. }
  40599. if (defines.UV2) {
  40600. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40601. }
  40602. if (defines.VERTEXCOLOR) {
  40603. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40604. }
  40605. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40606. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40607. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40608. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40609. "vFogInfos", "vFogColor", "pointSize",
  40610. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40611. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40612. "mBones",
  40613. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40614. "vLightingIntensity",
  40615. "logarithmicDepthConstant",
  40616. "vSphericalX", "vSphericalY", "vSphericalZ",
  40617. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40618. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40619. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40620. "vTangentSpaceParams"
  40621. ];
  40622. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40623. "bumpSampler", "lightmapSampler", "opacitySampler",
  40624. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40625. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40626. "microSurfaceSampler", "environmentBrdfSampler"];
  40627. var uniformBuffers = ["Material", "Scene"];
  40628. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40629. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40630. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40631. uniformsNames: uniforms,
  40632. uniformBuffersNames: uniformBuffers,
  40633. samplers: samplers,
  40634. defines: defines,
  40635. maxSimultaneousLights: this._maxSimultaneousLights
  40636. });
  40637. var join = defines.toString();
  40638. return engine.createEffect("pbr", {
  40639. attributes: attribs,
  40640. uniformsNames: uniforms,
  40641. uniformBuffersNames: uniformBuffers,
  40642. samplers: samplers,
  40643. defines: join,
  40644. fallbacks: fallbacks,
  40645. onCompiled: onCompiled,
  40646. onError: onError,
  40647. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40648. }, engine);
  40649. };
  40650. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40651. if (useInstances === void 0) { useInstances = null; }
  40652. if (useClipPlane === void 0) { useClipPlane = null; }
  40653. var scene = this.getScene();
  40654. var engine = scene.getEngine();
  40655. // Lights
  40656. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40657. defines._needNormals = true;
  40658. // Textures
  40659. if (defines._areTexturesDirty) {
  40660. defines._needUVs = false;
  40661. if (scene.texturesEnabled) {
  40662. if (scene.getEngine().getCaps().textureLOD) {
  40663. defines.LODBASEDMICROSFURACE = true;
  40664. }
  40665. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40666. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40667. }
  40668. else {
  40669. defines.ALBEDO = false;
  40670. }
  40671. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40672. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40673. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40674. }
  40675. else {
  40676. defines.AMBIENT = false;
  40677. }
  40678. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40679. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40680. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40681. }
  40682. else {
  40683. defines.OPACITY = false;
  40684. }
  40685. var reflectionTexture = this._getReflectionTexture();
  40686. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40687. defines.REFLECTION = true;
  40688. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40689. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40690. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40691. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40692. defines.INVERTCUBICMAP = true;
  40693. }
  40694. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40695. switch (reflectionTexture.coordinatesMode) {
  40696. case BABYLON.Texture.CUBIC_MODE:
  40697. case BABYLON.Texture.INVCUBIC_MODE:
  40698. defines.REFLECTIONMAP_CUBIC = true;
  40699. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40700. break;
  40701. case BABYLON.Texture.EXPLICIT_MODE:
  40702. defines.REFLECTIONMAP_EXPLICIT = true;
  40703. break;
  40704. case BABYLON.Texture.PLANAR_MODE:
  40705. defines.REFLECTIONMAP_PLANAR = true;
  40706. break;
  40707. case BABYLON.Texture.PROJECTION_MODE:
  40708. defines.REFLECTIONMAP_PROJECTION = true;
  40709. break;
  40710. case BABYLON.Texture.SKYBOX_MODE:
  40711. defines.REFLECTIONMAP_SKYBOX = true;
  40712. break;
  40713. case BABYLON.Texture.SPHERICAL_MODE:
  40714. defines.REFLECTIONMAP_SPHERICAL = true;
  40715. break;
  40716. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40717. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40718. break;
  40719. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40720. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40721. break;
  40722. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40723. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40724. break;
  40725. }
  40726. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40727. if (reflectionTexture.sphericalPolynomial) {
  40728. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40729. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40730. defines.USESPHERICALINVERTEX = false;
  40731. }
  40732. else {
  40733. defines.USESPHERICALINVERTEX = true;
  40734. }
  40735. }
  40736. }
  40737. }
  40738. else {
  40739. defines.REFLECTION = false;
  40740. defines.REFLECTIONMAP_3D = false;
  40741. defines.REFLECTIONMAP_SPHERICAL = false;
  40742. defines.REFLECTIONMAP_PLANAR = false;
  40743. defines.REFLECTIONMAP_CUBIC = false;
  40744. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40745. defines.REFLECTIONMAP_PROJECTION = false;
  40746. defines.REFLECTIONMAP_SKYBOX = false;
  40747. defines.REFLECTIONMAP_EXPLICIT = false;
  40748. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40749. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40750. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40751. defines.INVERTCUBICMAP = false;
  40752. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40753. defines.USESPHERICALINVERTEX = false;
  40754. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40755. defines.LODINREFLECTIONALPHA = false;
  40756. defines.GAMMAREFLECTION = false;
  40757. }
  40758. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40759. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40760. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40761. }
  40762. else {
  40763. defines.LIGHTMAP = false;
  40764. }
  40765. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40766. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40767. }
  40768. else {
  40769. defines.EMISSIVE = false;
  40770. }
  40771. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40772. if (this._metallicTexture) {
  40773. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40774. defines.METALLICWORKFLOW = true;
  40775. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40776. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40777. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40778. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40779. }
  40780. else if (this._reflectivityTexture) {
  40781. defines.METALLICWORKFLOW = false;
  40782. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40783. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40784. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40785. }
  40786. else {
  40787. defines.METALLICWORKFLOW = false;
  40788. defines.REFLECTIVITY = false;
  40789. }
  40790. if (this._microSurfaceTexture) {
  40791. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40792. }
  40793. else {
  40794. defines.MICROSURFACEMAP = false;
  40795. }
  40796. }
  40797. else {
  40798. defines.REFLECTIVITY = false;
  40799. defines.MICROSURFACEMAP = false;
  40800. }
  40801. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40802. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40803. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40804. defines.PARALLAX = true;
  40805. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40806. }
  40807. else {
  40808. defines.PARALLAX = false;
  40809. }
  40810. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40811. }
  40812. else {
  40813. defines.BUMP = false;
  40814. }
  40815. var refractionTexture = this._getRefractionTexture();
  40816. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40817. defines.REFRACTION = true;
  40818. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40819. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40820. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40821. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40822. if (this._linkRefractionWithTransparency) {
  40823. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40824. }
  40825. }
  40826. else {
  40827. defines.REFRACTION = false;
  40828. }
  40829. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40830. defines.ENVIRONMENTBRDF = true;
  40831. }
  40832. else {
  40833. defines.ENVIRONMENTBRDF = false;
  40834. }
  40835. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40836. defines.ALPHAFROMALBEDO = true;
  40837. }
  40838. else {
  40839. defines.ALPHAFROMALBEDO = false;
  40840. }
  40841. }
  40842. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40843. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40844. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40845. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40846. defines.METALLICWORKFLOW = true;
  40847. }
  40848. else {
  40849. defines.METALLICWORKFLOW = false;
  40850. }
  40851. if (!this.backFaceCulling && this._twoSidedLighting) {
  40852. defines.TWOSIDEDLIGHTING = true;
  40853. }
  40854. else {
  40855. defines.TWOSIDEDLIGHTING = false;
  40856. }
  40857. defines.ALPHATESTVALUE = this._alphaCutOff;
  40858. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40859. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40860. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40861. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40862. }
  40863. if (defines._areImageProcessingDirty) {
  40864. this._imageProcessingConfiguration.prepareDefines(defines);
  40865. }
  40866. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40867. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40868. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40869. // Misc.
  40870. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40871. // Values that need to be evaluated on every frame
  40872. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40873. // Attribs
  40874. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40875. };
  40876. /**
  40877. * Force shader compilation
  40878. */
  40879. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40880. var _this = this;
  40881. var localOptions = __assign({ clipPlane: false }, options);
  40882. var defines = new PBRMaterialDefines();
  40883. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40884. if (effect.isReady()) {
  40885. if (onCompiled) {
  40886. onCompiled(this);
  40887. }
  40888. }
  40889. else {
  40890. effect.onCompileObservable.add(function () {
  40891. if (onCompiled) {
  40892. onCompiled(_this);
  40893. }
  40894. });
  40895. }
  40896. };
  40897. /**
  40898. * Initializes the uniform buffer layout for the shader.
  40899. */
  40900. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40901. // Order is important !
  40902. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40903. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40904. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40905. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40906. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40907. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40908. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40909. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40910. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40911. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40912. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40913. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40914. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40915. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40916. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40917. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40918. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40919. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40920. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40921. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40922. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40923. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40924. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40925. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40926. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40927. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40928. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40929. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40930. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40931. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40932. this._uniformBuffer.addUniform("pointSize", 1);
  40933. this._uniformBuffer.create();
  40934. };
  40935. /**
  40936. * Unbinds the textures.
  40937. */
  40938. PBRBaseMaterial.prototype.unbind = function () {
  40939. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40940. this._uniformBuffer.setTexture("reflectionSampler", null);
  40941. }
  40942. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40943. this._uniformBuffer.setTexture("refractionSampler", null);
  40944. }
  40945. _super.prototype.unbind.call(this);
  40946. };
  40947. /**
  40948. * Binds the submesh data.
  40949. * @param world - The world matrix.
  40950. * @param mesh - The BJS mesh.
  40951. * @param subMesh - A submesh of the BJS mesh.
  40952. */
  40953. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40954. var scene = this.getScene();
  40955. var defines = subMesh._materialDefines;
  40956. if (!defines) {
  40957. return;
  40958. }
  40959. var effect = subMesh.effect;
  40960. if (!effect) {
  40961. return;
  40962. }
  40963. this._activeEffect = effect;
  40964. // Matrices
  40965. this.bindOnlyWorldMatrix(world);
  40966. // Normal Matrix
  40967. if (defines.OBJECTSPACE_NORMALMAP) {
  40968. world.toNormalMatrix(this._normalMatrix);
  40969. this.bindOnlyNormalMatrix(this._normalMatrix);
  40970. }
  40971. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40972. // Bones
  40973. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40974. var reflectionTexture = null;
  40975. if (mustRebind) {
  40976. this._uniformBuffer.bindToEffect(effect, "Material");
  40977. this.bindViewProjection(effect);
  40978. reflectionTexture = this._getReflectionTexture();
  40979. var refractionTexture = this._getRefractionTexture();
  40980. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40981. // Texture uniforms
  40982. if (scene.texturesEnabled) {
  40983. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40984. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40985. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40986. }
  40987. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40988. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40989. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40990. }
  40991. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40992. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40993. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40994. }
  40995. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40996. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40997. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40998. if (reflectionTexture.boundingBoxSize) {
  40999. var cubeTexture = reflectionTexture;
  41000. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41001. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41002. }
  41003. var polynomials = reflectionTexture.sphericalPolynomial;
  41004. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41005. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41006. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41007. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41008. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41009. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41010. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41011. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41012. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41013. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41014. }
  41015. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41016. }
  41017. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41018. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41019. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41020. }
  41021. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41022. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41023. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41024. }
  41025. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41026. if (this._metallicTexture) {
  41027. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  41028. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  41029. }
  41030. else if (this._reflectivityTexture) {
  41031. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  41032. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  41033. }
  41034. if (this._microSurfaceTexture) {
  41035. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  41036. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  41037. }
  41038. }
  41039. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41040. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  41041. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  41042. if (scene._mirroredCameraPosition) {
  41043. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  41044. }
  41045. else {
  41046. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  41047. }
  41048. }
  41049. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41050. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  41051. var depth = 1.0;
  41052. if (!refractionTexture.isCube) {
  41053. if (refractionTexture.depth) {
  41054. depth = refractionTexture.depth;
  41055. }
  41056. }
  41057. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  41058. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  41059. }
  41060. }
  41061. // Point size
  41062. if (this.pointsCloud) {
  41063. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  41064. }
  41065. // Colors
  41066. if (defines.METALLICWORKFLOW) {
  41067. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  41068. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  41069. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  41070. }
  41071. else {
  41072. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  41073. }
  41074. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  41075. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  41076. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41077. // Misc
  41078. this._lightingInfos.x = this._directIntensity;
  41079. this._lightingInfos.y = this._emissiveIntensity;
  41080. this._lightingInfos.z = this._environmentIntensity;
  41081. this._lightingInfos.w = this._specularIntensity;
  41082. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41083. }
  41084. // Textures
  41085. if (scene.texturesEnabled) {
  41086. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41087. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41088. }
  41089. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41090. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41091. }
  41092. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41093. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41094. }
  41095. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41096. if (defines.LODBASEDMICROSFURACE) {
  41097. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41098. }
  41099. else {
  41100. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41101. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41102. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41103. }
  41104. }
  41105. if (defines.ENVIRONMENTBRDF) {
  41106. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41107. }
  41108. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41109. if (defines.LODBASEDMICROSFURACE) {
  41110. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41111. }
  41112. else {
  41113. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41114. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41115. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41116. }
  41117. }
  41118. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41119. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41120. }
  41121. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41122. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41123. }
  41124. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41125. if (this._metallicTexture) {
  41126. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41127. }
  41128. else if (this._reflectivityTexture) {
  41129. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41130. }
  41131. if (this._microSurfaceTexture) {
  41132. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41133. }
  41134. }
  41135. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41136. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41137. }
  41138. }
  41139. // Clip plane
  41140. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41141. // Colors
  41142. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41143. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41144. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41145. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41146. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41147. }
  41148. if (mustRebind || !this.isFrozen) {
  41149. // Lights
  41150. if (scene.lightsEnabled && !this._disableLighting) {
  41151. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41152. }
  41153. // View
  41154. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41155. this.bindView(effect);
  41156. }
  41157. // Fog
  41158. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41159. // Morph targets
  41160. if (defines.NUM_MORPH_INFLUENCERS) {
  41161. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41162. }
  41163. // image processing
  41164. this._imageProcessingConfiguration.bind(this._activeEffect);
  41165. // Log. depth
  41166. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41167. }
  41168. this._uniformBuffer.update();
  41169. this._afterBind(mesh);
  41170. };
  41171. /**
  41172. * Returns the animatable textures.
  41173. * @returns - Array of animatable textures.
  41174. */
  41175. PBRBaseMaterial.prototype.getAnimatables = function () {
  41176. var results = [];
  41177. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41178. results.push(this._albedoTexture);
  41179. }
  41180. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41181. results.push(this._ambientTexture);
  41182. }
  41183. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41184. results.push(this._opacityTexture);
  41185. }
  41186. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41187. results.push(this._reflectionTexture);
  41188. }
  41189. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41190. results.push(this._emissiveTexture);
  41191. }
  41192. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41193. results.push(this._metallicTexture);
  41194. }
  41195. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41196. results.push(this._reflectivityTexture);
  41197. }
  41198. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41199. results.push(this._bumpTexture);
  41200. }
  41201. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41202. results.push(this._lightmapTexture);
  41203. }
  41204. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41205. results.push(this._refractionTexture);
  41206. }
  41207. return results;
  41208. };
  41209. /**
  41210. * Returns the texture used for reflections.
  41211. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41212. */
  41213. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41214. if (this._reflectionTexture) {
  41215. return this._reflectionTexture;
  41216. }
  41217. return this.getScene().environmentTexture;
  41218. };
  41219. /**
  41220. * Returns the texture used for refraction or null if none is used.
  41221. * @returns - Refection texture if present. If no refraction texture and refraction
  41222. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41223. */
  41224. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41225. if (this._refractionTexture) {
  41226. return this._refractionTexture;
  41227. }
  41228. if (this._linkRefractionWithTransparency) {
  41229. return this.getScene().environmentTexture;
  41230. }
  41231. return null;
  41232. };
  41233. /**
  41234. * Disposes the resources of the material.
  41235. * @param forceDisposeEffect - Forces the disposal of effects.
  41236. * @param forceDisposeTextures - Forces the disposal of all textures.
  41237. */
  41238. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41239. if (forceDisposeTextures) {
  41240. if (this._albedoTexture) {
  41241. this._albedoTexture.dispose();
  41242. }
  41243. if (this._ambientTexture) {
  41244. this._ambientTexture.dispose();
  41245. }
  41246. if (this._opacityTexture) {
  41247. this._opacityTexture.dispose();
  41248. }
  41249. if (this._reflectionTexture) {
  41250. this._reflectionTexture.dispose();
  41251. }
  41252. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41253. this._environmentBRDFTexture.dispose();
  41254. }
  41255. if (this._emissiveTexture) {
  41256. this._emissiveTexture.dispose();
  41257. }
  41258. if (this._metallicTexture) {
  41259. this._metallicTexture.dispose();
  41260. }
  41261. if (this._reflectivityTexture) {
  41262. this._reflectivityTexture.dispose();
  41263. }
  41264. if (this._bumpTexture) {
  41265. this._bumpTexture.dispose();
  41266. }
  41267. if (this._lightmapTexture) {
  41268. this._lightmapTexture.dispose();
  41269. }
  41270. if (this._refractionTexture) {
  41271. this._refractionTexture.dispose();
  41272. }
  41273. }
  41274. this._renderTargets.dispose();
  41275. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41276. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41277. }
  41278. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41279. };
  41280. /**
  41281. * Stores the reflectivity values based on metallic roughness workflow.
  41282. */
  41283. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41284. __decorate([
  41285. BABYLON.serializeAsImageProcessingConfiguration()
  41286. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41287. __decorate([
  41288. BABYLON.serialize()
  41289. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41290. __decorate([
  41291. BABYLON.serialize()
  41292. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41293. return PBRBaseMaterial;
  41294. }(BABYLON.PushMaterial));
  41295. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41296. })(BABYLON || (BABYLON = {}));
  41297. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41298. var BABYLON;
  41299. (function (BABYLON) {
  41300. /**
  41301. * The Physically based simple base material of BJS.
  41302. *
  41303. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41304. * It is used as the base class for both the specGloss and metalRough conventions.
  41305. */
  41306. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41307. __extends(PBRBaseSimpleMaterial, _super);
  41308. /**
  41309. * Instantiates a new PBRMaterial instance.
  41310. *
  41311. * @param name The material name
  41312. * @param scene The scene the material will be use in.
  41313. */
  41314. function PBRBaseSimpleMaterial(name, scene) {
  41315. var _this = _super.call(this, name, scene) || this;
  41316. /**
  41317. * Number of Simultaneous lights allowed on the material.
  41318. */
  41319. _this.maxSimultaneousLights = 4;
  41320. /**
  41321. * If sets to true, disables all the lights affecting the material.
  41322. */
  41323. _this.disableLighting = false;
  41324. /**
  41325. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41326. */
  41327. _this.invertNormalMapX = false;
  41328. /**
  41329. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41330. */
  41331. _this.invertNormalMapY = false;
  41332. /**
  41333. * Emissivie color used to self-illuminate the model.
  41334. */
  41335. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41336. /**
  41337. * Occlusion Channel Strenght.
  41338. */
  41339. _this.occlusionStrength = 1.0;
  41340. _this.useLightmapAsShadowmap = false;
  41341. _this._useAlphaFromAlbedoTexture = true;
  41342. _this._useAmbientInGrayScale = true;
  41343. return _this;
  41344. }
  41345. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41346. /**
  41347. * Gets the current double sided mode.
  41348. */
  41349. get: function () {
  41350. return this._twoSidedLighting;
  41351. },
  41352. /**
  41353. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41354. */
  41355. set: function (value) {
  41356. if (this._twoSidedLighting === value) {
  41357. return;
  41358. }
  41359. this._twoSidedLighting = value;
  41360. this.backFaceCulling = !value;
  41361. this._markAllSubMeshesAsTexturesDirty();
  41362. },
  41363. enumerable: true,
  41364. configurable: true
  41365. });
  41366. /**
  41367. * Return the active textures of the material.
  41368. */
  41369. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41370. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41371. if (this.environmentTexture) {
  41372. activeTextures.push(this.environmentTexture);
  41373. }
  41374. if (this.normalTexture) {
  41375. activeTextures.push(this.normalTexture);
  41376. }
  41377. if (this.emissiveTexture) {
  41378. activeTextures.push(this.emissiveTexture);
  41379. }
  41380. if (this.occlusionTexture) {
  41381. activeTextures.push(this.occlusionTexture);
  41382. }
  41383. if (this.lightmapTexture) {
  41384. activeTextures.push(this.lightmapTexture);
  41385. }
  41386. return activeTextures;
  41387. };
  41388. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41389. if (_super.prototype.hasTexture.call(this, texture)) {
  41390. return true;
  41391. }
  41392. if (this.lightmapTexture === texture) {
  41393. return true;
  41394. }
  41395. return false;
  41396. };
  41397. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41398. return "PBRBaseSimpleMaterial";
  41399. };
  41400. __decorate([
  41401. BABYLON.serialize(),
  41402. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41403. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41404. __decorate([
  41405. BABYLON.serialize(),
  41406. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41407. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41408. __decorate([
  41409. BABYLON.serializeAsTexture(),
  41410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41411. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41412. __decorate([
  41413. BABYLON.serialize(),
  41414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41415. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41416. __decorate([
  41417. BABYLON.serialize(),
  41418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41419. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41420. __decorate([
  41421. BABYLON.serializeAsTexture(),
  41422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41423. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41424. __decorate([
  41425. BABYLON.serializeAsColor3("emissive"),
  41426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41427. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41428. __decorate([
  41429. BABYLON.serializeAsTexture(),
  41430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41431. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41432. __decorate([
  41433. BABYLON.serialize(),
  41434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41435. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41436. __decorate([
  41437. BABYLON.serializeAsTexture(),
  41438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41439. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41440. __decorate([
  41441. BABYLON.serialize(),
  41442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41443. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41444. __decorate([
  41445. BABYLON.serialize()
  41446. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41447. __decorate([
  41448. BABYLON.serializeAsTexture(),
  41449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41450. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41451. __decorate([
  41452. BABYLON.serialize(),
  41453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41454. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41455. return PBRBaseSimpleMaterial;
  41456. }(BABYLON.PBRBaseMaterial));
  41457. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41458. })(BABYLON || (BABYLON = {}));
  41459. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41460. var BABYLON;
  41461. (function (BABYLON) {
  41462. /**
  41463. * The Physically based material of BJS.
  41464. *
  41465. * This offers the main features of a standard PBR material.
  41466. * For more information, please refer to the documentation :
  41467. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41468. */
  41469. var PBRMaterial = /** @class */ (function (_super) {
  41470. __extends(PBRMaterial, _super);
  41471. /**
  41472. * Instantiates a new PBRMaterial instance.
  41473. *
  41474. * @param name The material name
  41475. * @param scene The scene the material will be use in.
  41476. */
  41477. function PBRMaterial(name, scene) {
  41478. var _this = _super.call(this, name, scene) || this;
  41479. /**
  41480. * Intensity of the direct lights e.g. the four lights available in your scene.
  41481. * This impacts both the direct diffuse and specular highlights.
  41482. */
  41483. _this.directIntensity = 1.0;
  41484. /**
  41485. * Intensity of the emissive part of the material.
  41486. * This helps controlling the emissive effect without modifying the emissive color.
  41487. */
  41488. _this.emissiveIntensity = 1.0;
  41489. /**
  41490. * Intensity of the environment e.g. how much the environment will light the object
  41491. * either through harmonics for rough material or through the refelction for shiny ones.
  41492. */
  41493. _this.environmentIntensity = 1.0;
  41494. /**
  41495. * This is a special control allowing the reduction of the specular highlights coming from the
  41496. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41497. */
  41498. _this.specularIntensity = 1.0;
  41499. /**
  41500. * Debug Control allowing disabling the bump map on this material.
  41501. */
  41502. _this.disableBumpMap = false;
  41503. /**
  41504. * AKA Occlusion Texture Intensity in other nomenclature.
  41505. */
  41506. _this.ambientTextureStrength = 1.0;
  41507. /**
  41508. * The color of a material in ambient lighting.
  41509. */
  41510. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41511. /**
  41512. * AKA Diffuse Color in other nomenclature.
  41513. */
  41514. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41515. /**
  41516. * AKA Specular Color in other nomenclature.
  41517. */
  41518. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41519. /**
  41520. * The color reflected from the material.
  41521. */
  41522. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41523. /**
  41524. * The color emitted from the material.
  41525. */
  41526. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41527. /**
  41528. * AKA Glossiness in other nomenclature.
  41529. */
  41530. _this.microSurface = 1.0;
  41531. /**
  41532. * source material index of refraction (IOR)' / 'destination material IOR.
  41533. */
  41534. _this.indexOfRefraction = 0.66;
  41535. /**
  41536. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41537. */
  41538. _this.invertRefractionY = false;
  41539. /**
  41540. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41541. * Materials half opaque for instance using refraction could benefit from this control.
  41542. */
  41543. _this.linkRefractionWithTransparency = false;
  41544. _this.useLightmapAsShadowmap = false;
  41545. /**
  41546. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41547. */
  41548. _this.useAlphaFromAlbedoTexture = false;
  41549. /**
  41550. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41551. */
  41552. _this.forceAlphaTest = false;
  41553. /**
  41554. * Defines the alpha limits in alpha test mode.
  41555. */
  41556. _this.alphaCutOff = 0.4;
  41557. /**
  41558. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41559. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41560. */
  41561. _this.useSpecularOverAlpha = true;
  41562. /**
  41563. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41564. */
  41565. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41566. /**
  41567. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41568. */
  41569. _this.useRoughnessFromMetallicTextureAlpha = true;
  41570. /**
  41571. * Specifies if the metallic texture contains the roughness information in its green channel.
  41572. */
  41573. _this.useRoughnessFromMetallicTextureGreen = false;
  41574. /**
  41575. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41576. */
  41577. _this.useMetallnessFromMetallicTextureBlue = false;
  41578. /**
  41579. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41580. */
  41581. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41582. /**
  41583. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41584. */
  41585. _this.useAmbientInGrayScale = false;
  41586. /**
  41587. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41588. * The material will try to infer what glossiness each pixel should be.
  41589. */
  41590. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41591. /**
  41592. * BJS is using an harcoded light falloff based on a manually sets up range.
  41593. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41594. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41595. */
  41596. _this.usePhysicalLightFalloff = true;
  41597. /**
  41598. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41599. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41600. */
  41601. _this.useRadianceOverAlpha = true;
  41602. /**
  41603. * Allows using an object space normal map (instead of tangent space).
  41604. */
  41605. _this.useObjectSpaceNormalMap = false;
  41606. /**
  41607. * Allows using the bump map in parallax mode.
  41608. */
  41609. _this.useParallax = false;
  41610. /**
  41611. * Allows using the bump map in parallax occlusion mode.
  41612. */
  41613. _this.useParallaxOcclusion = false;
  41614. /**
  41615. * Controls the scale bias of the parallax mode.
  41616. */
  41617. _this.parallaxScaleBias = 0.05;
  41618. /**
  41619. * If sets to true, disables all the lights affecting the material.
  41620. */
  41621. _this.disableLighting = false;
  41622. /**
  41623. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41624. */
  41625. _this.forceIrradianceInFragment = false;
  41626. /**
  41627. * Number of Simultaneous lights allowed on the material.
  41628. */
  41629. _this.maxSimultaneousLights = 4;
  41630. /**
  41631. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41632. */
  41633. _this.invertNormalMapX = false;
  41634. /**
  41635. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41636. */
  41637. _this.invertNormalMapY = false;
  41638. /**
  41639. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41640. */
  41641. _this.twoSidedLighting = false;
  41642. /**
  41643. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41644. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41645. */
  41646. _this.useAlphaFresnel = false;
  41647. /**
  41648. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41649. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41650. */
  41651. _this.useLinearAlphaFresnel = false;
  41652. /**
  41653. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41654. * And/Or occlude the blended part.
  41655. */
  41656. _this.environmentBRDFTexture = null;
  41657. /**
  41658. * Force normal to face away from face.
  41659. */
  41660. _this.forceNormalForward = false;
  41661. /**
  41662. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41663. * makes the reflect vector face the model (under horizon).
  41664. */
  41665. _this.useHorizonOcclusion = true;
  41666. /**
  41667. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41668. * too much the area relying on ambient texture to define their ambient occlusion.
  41669. */
  41670. _this.useRadianceOcclusion = true;
  41671. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41672. return _this;
  41673. }
  41674. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41675. /**
  41676. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41677. */
  41678. get: function () {
  41679. return this._PBRMATERIAL_OPAQUE;
  41680. },
  41681. enumerable: true,
  41682. configurable: true
  41683. });
  41684. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41685. /**
  41686. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41687. */
  41688. get: function () {
  41689. return this._PBRMATERIAL_ALPHATEST;
  41690. },
  41691. enumerable: true,
  41692. configurable: true
  41693. });
  41694. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41695. /**
  41696. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41697. */
  41698. get: function () {
  41699. return this._PBRMATERIAL_ALPHABLEND;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41705. /**
  41706. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41707. * They are also discarded below the alpha cutoff threshold to improve performances.
  41708. */
  41709. get: function () {
  41710. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41711. },
  41712. enumerable: true,
  41713. configurable: true
  41714. });
  41715. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41716. /**
  41717. * Gets the image processing configuration used either in this material.
  41718. */
  41719. get: function () {
  41720. return this._imageProcessingConfiguration;
  41721. },
  41722. /**
  41723. * Sets the Default image processing configuration used either in the this material.
  41724. *
  41725. * If sets to null, the scene one is in use.
  41726. */
  41727. set: function (value) {
  41728. this._attachImageProcessingConfiguration(value);
  41729. // Ensure the effect will be rebuilt.
  41730. this._markAllSubMeshesAsTexturesDirty();
  41731. },
  41732. enumerable: true,
  41733. configurable: true
  41734. });
  41735. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41736. /**
  41737. * Gets wether the color curves effect is enabled.
  41738. */
  41739. get: function () {
  41740. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41741. },
  41742. /**
  41743. * Sets wether the color curves effect is enabled.
  41744. */
  41745. set: function (value) {
  41746. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41752. /**
  41753. * Gets wether the color grading effect is enabled.
  41754. */
  41755. get: function () {
  41756. return this.imageProcessingConfiguration.colorGradingEnabled;
  41757. },
  41758. /**
  41759. * Gets wether the color grading effect is enabled.
  41760. */
  41761. set: function (value) {
  41762. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41763. },
  41764. enumerable: true,
  41765. configurable: true
  41766. });
  41767. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41768. /**
  41769. * Gets wether tonemapping is enabled or not.
  41770. */
  41771. get: function () {
  41772. return this._imageProcessingConfiguration.toneMappingEnabled;
  41773. },
  41774. /**
  41775. * Sets wether tonemapping is enabled or not
  41776. */
  41777. set: function (value) {
  41778. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41779. },
  41780. enumerable: true,
  41781. configurable: true
  41782. });
  41783. ;
  41784. ;
  41785. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41786. /**
  41787. * The camera exposure used on this material.
  41788. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41789. * This corresponds to a photographic exposure.
  41790. */
  41791. get: function () {
  41792. return this._imageProcessingConfiguration.exposure;
  41793. },
  41794. /**
  41795. * The camera exposure used on this material.
  41796. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41797. * This corresponds to a photographic exposure.
  41798. */
  41799. set: function (value) {
  41800. this._imageProcessingConfiguration.exposure = value;
  41801. },
  41802. enumerable: true,
  41803. configurable: true
  41804. });
  41805. ;
  41806. ;
  41807. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41808. /**
  41809. * Gets The camera contrast used on this material.
  41810. */
  41811. get: function () {
  41812. return this._imageProcessingConfiguration.contrast;
  41813. },
  41814. /**
  41815. * Sets The camera contrast used on this material.
  41816. */
  41817. set: function (value) {
  41818. this._imageProcessingConfiguration.contrast = value;
  41819. },
  41820. enumerable: true,
  41821. configurable: true
  41822. });
  41823. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41824. /**
  41825. * Gets the Color Grading 2D Lookup Texture.
  41826. */
  41827. get: function () {
  41828. return this._imageProcessingConfiguration.colorGradingTexture;
  41829. },
  41830. /**
  41831. * Sets the Color Grading 2D Lookup Texture.
  41832. */
  41833. set: function (value) {
  41834. this._imageProcessingConfiguration.colorGradingTexture = value;
  41835. },
  41836. enumerable: true,
  41837. configurable: true
  41838. });
  41839. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41840. /**
  41841. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41842. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41843. * 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;
  41844. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41845. */
  41846. get: function () {
  41847. return this._imageProcessingConfiguration.colorCurves;
  41848. },
  41849. /**
  41850. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41851. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41852. * 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;
  41853. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41854. */
  41855. set: function (value) {
  41856. this._imageProcessingConfiguration.colorCurves = value;
  41857. },
  41858. enumerable: true,
  41859. configurable: true
  41860. });
  41861. /**
  41862. * Returns the name of this material class.
  41863. */
  41864. PBRMaterial.prototype.getClassName = function () {
  41865. return "PBRMaterial";
  41866. };
  41867. /**
  41868. * Returns an array of the actively used textures.
  41869. * @returns - Array of BaseTextures
  41870. */
  41871. PBRMaterial.prototype.getActiveTextures = function () {
  41872. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41873. if (this._albedoTexture) {
  41874. activeTextures.push(this._albedoTexture);
  41875. }
  41876. if (this._ambientTexture) {
  41877. activeTextures.push(this._ambientTexture);
  41878. }
  41879. if (this._opacityTexture) {
  41880. activeTextures.push(this._opacityTexture);
  41881. }
  41882. if (this._reflectionTexture) {
  41883. activeTextures.push(this._reflectionTexture);
  41884. }
  41885. if (this._emissiveTexture) {
  41886. activeTextures.push(this._emissiveTexture);
  41887. }
  41888. if (this._reflectivityTexture) {
  41889. activeTextures.push(this._reflectivityTexture);
  41890. }
  41891. if (this._metallicTexture) {
  41892. activeTextures.push(this._metallicTexture);
  41893. }
  41894. if (this._microSurfaceTexture) {
  41895. activeTextures.push(this._microSurfaceTexture);
  41896. }
  41897. if (this._bumpTexture) {
  41898. activeTextures.push(this._bumpTexture);
  41899. }
  41900. if (this._lightmapTexture) {
  41901. activeTextures.push(this._lightmapTexture);
  41902. }
  41903. if (this._refractionTexture) {
  41904. activeTextures.push(this._refractionTexture);
  41905. }
  41906. return activeTextures;
  41907. };
  41908. /**
  41909. * Checks to see if a texture is used in the material.
  41910. * @param texture - Base texture to use.
  41911. * @returns - Boolean specifying if a texture is used in the material.
  41912. */
  41913. PBRMaterial.prototype.hasTexture = function (texture) {
  41914. if (_super.prototype.hasTexture.call(this, texture)) {
  41915. return true;
  41916. }
  41917. if (this._albedoTexture === texture) {
  41918. return true;
  41919. }
  41920. if (this._ambientTexture === texture) {
  41921. return true;
  41922. }
  41923. if (this._opacityTexture === texture) {
  41924. return true;
  41925. }
  41926. if (this._reflectionTexture === texture) {
  41927. return true;
  41928. }
  41929. if (this._reflectivityTexture === texture) {
  41930. return true;
  41931. }
  41932. if (this._metallicTexture === texture) {
  41933. return true;
  41934. }
  41935. if (this._microSurfaceTexture === texture) {
  41936. return true;
  41937. }
  41938. if (this._bumpTexture === texture) {
  41939. return true;
  41940. }
  41941. if (this._lightmapTexture === texture) {
  41942. return true;
  41943. }
  41944. if (this._refractionTexture === texture) {
  41945. return true;
  41946. }
  41947. return false;
  41948. };
  41949. /**
  41950. * Makes a duplicate of the current material.
  41951. * @param name - name to use for the new material.
  41952. */
  41953. PBRMaterial.prototype.clone = function (name) {
  41954. var _this = this;
  41955. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41956. clone.id = name;
  41957. clone.name = name;
  41958. return clone;
  41959. };
  41960. /**
  41961. * Serializes this PBR Material.
  41962. * @returns - An object with the serialized material.
  41963. */
  41964. PBRMaterial.prototype.serialize = function () {
  41965. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41966. serializationObject.customType = "BABYLON.PBRMaterial";
  41967. return serializationObject;
  41968. };
  41969. // Statics
  41970. /**
  41971. * Parses a PBR Material from a serialized object.
  41972. * @param source - Serialized object.
  41973. * @param scene - BJS scene instance.
  41974. * @param rootUrl - url for the scene object
  41975. * @returns - PBRMaterial
  41976. */
  41977. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41978. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41979. };
  41980. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41981. /**
  41982. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41983. */
  41984. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41985. /**
  41986. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41987. */
  41988. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41989. /**
  41990. * 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.
  41991. * They are also discarded below the alpha cutoff threshold to improve performances.
  41992. */
  41993. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41994. __decorate([
  41995. BABYLON.serialize(),
  41996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41997. ], PBRMaterial.prototype, "directIntensity", void 0);
  41998. __decorate([
  41999. BABYLON.serialize(),
  42000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42001. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42002. __decorate([
  42003. BABYLON.serialize(),
  42004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42005. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42006. __decorate([
  42007. BABYLON.serialize(),
  42008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42009. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42010. __decorate([
  42011. BABYLON.serialize(),
  42012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42013. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42014. __decorate([
  42015. BABYLON.serializeAsTexture(),
  42016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42017. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42018. __decorate([
  42019. BABYLON.serializeAsTexture(),
  42020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42021. ], PBRMaterial.prototype, "ambientTexture", void 0);
  42022. __decorate([
  42023. BABYLON.serialize(),
  42024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42025. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  42026. __decorate([
  42027. BABYLON.serializeAsTexture(),
  42028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42029. ], PBRMaterial.prototype, "opacityTexture", void 0);
  42030. __decorate([
  42031. BABYLON.serializeAsTexture(),
  42032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42033. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  42034. __decorate([
  42035. BABYLON.serializeAsTexture(),
  42036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42037. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  42038. __decorate([
  42039. BABYLON.serializeAsTexture(),
  42040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42041. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  42042. __decorate([
  42043. BABYLON.serializeAsTexture(),
  42044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42045. ], PBRMaterial.prototype, "metallicTexture", void 0);
  42046. __decorate([
  42047. BABYLON.serialize(),
  42048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42049. ], PBRMaterial.prototype, "metallic", void 0);
  42050. __decorate([
  42051. BABYLON.serialize(),
  42052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42053. ], PBRMaterial.prototype, "roughness", void 0);
  42054. __decorate([
  42055. BABYLON.serializeAsTexture(),
  42056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42057. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  42058. __decorate([
  42059. BABYLON.serializeAsTexture(),
  42060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42061. ], PBRMaterial.prototype, "bumpTexture", void 0);
  42062. __decorate([
  42063. BABYLON.serializeAsTexture(),
  42064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42065. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  42066. __decorate([
  42067. BABYLON.serializeAsTexture(),
  42068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42069. ], PBRMaterial.prototype, "refractionTexture", void 0);
  42070. __decorate([
  42071. BABYLON.serializeAsColor3("ambient"),
  42072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42073. ], PBRMaterial.prototype, "ambientColor", void 0);
  42074. __decorate([
  42075. BABYLON.serializeAsColor3("albedo"),
  42076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42077. ], PBRMaterial.prototype, "albedoColor", void 0);
  42078. __decorate([
  42079. BABYLON.serializeAsColor3("reflectivity"),
  42080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42081. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42082. __decorate([
  42083. BABYLON.serializeAsColor3("reflection"),
  42084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42085. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42086. __decorate([
  42087. BABYLON.serializeAsColor3("emissive"),
  42088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42089. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42090. __decorate([
  42091. BABYLON.serialize(),
  42092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42093. ], PBRMaterial.prototype, "microSurface", void 0);
  42094. __decorate([
  42095. BABYLON.serialize(),
  42096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42097. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42098. __decorate([
  42099. BABYLON.serialize(),
  42100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42101. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42102. __decorate([
  42103. BABYLON.serialize(),
  42104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42105. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42106. __decorate([
  42107. BABYLON.serialize(),
  42108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42109. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42110. __decorate([
  42111. BABYLON.serialize(),
  42112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42113. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42114. __decorate([
  42115. BABYLON.serialize(),
  42116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42117. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42118. __decorate([
  42119. BABYLON.serialize(),
  42120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42121. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42122. __decorate([
  42123. BABYLON.serialize(),
  42124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42125. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42126. __decorate([
  42127. BABYLON.serialize(),
  42128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42129. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42130. __decorate([
  42131. BABYLON.serialize(),
  42132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42133. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42134. __decorate([
  42135. BABYLON.serialize(),
  42136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42137. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42138. __decorate([
  42139. BABYLON.serialize(),
  42140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42141. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42142. __decorate([
  42143. BABYLON.serialize(),
  42144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42145. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42146. __decorate([
  42147. BABYLON.serialize(),
  42148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42149. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42150. __decorate([
  42151. BABYLON.serialize(),
  42152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42153. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42154. __decorate([
  42155. BABYLON.serialize(),
  42156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42157. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42158. __decorate([
  42159. BABYLON.serialize(),
  42160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42161. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42162. __decorate([
  42163. BABYLON.serialize(),
  42164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42165. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42166. __decorate([
  42167. BABYLON.serialize(),
  42168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42169. ], PBRMaterial.prototype, "useParallax", void 0);
  42170. __decorate([
  42171. BABYLON.serialize(),
  42172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42173. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42174. __decorate([
  42175. BABYLON.serialize(),
  42176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42177. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42178. __decorate([
  42179. BABYLON.serialize(),
  42180. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42181. ], PBRMaterial.prototype, "disableLighting", void 0);
  42182. __decorate([
  42183. BABYLON.serialize(),
  42184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42185. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42186. __decorate([
  42187. BABYLON.serialize(),
  42188. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42189. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42190. __decorate([
  42191. BABYLON.serialize(),
  42192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42193. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42194. __decorate([
  42195. BABYLON.serialize(),
  42196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42197. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42198. __decorate([
  42199. BABYLON.serialize(),
  42200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42201. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42202. __decorate([
  42203. BABYLON.serialize(),
  42204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42205. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42206. __decorate([
  42207. BABYLON.serialize(),
  42208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42209. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42210. __decorate([
  42211. BABYLON.serializeAsTexture(),
  42212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42213. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42214. __decorate([
  42215. BABYLON.serialize(),
  42216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42217. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42218. __decorate([
  42219. BABYLON.serialize(),
  42220. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42221. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42222. __decorate([
  42223. BABYLON.serialize(),
  42224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42225. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42226. return PBRMaterial;
  42227. }(BABYLON.PBRBaseMaterial));
  42228. BABYLON.PBRMaterial = PBRMaterial;
  42229. })(BABYLON || (BABYLON = {}));
  42230. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42231. var BABYLON;
  42232. (function (BABYLON) {
  42233. /**
  42234. * The PBR material of BJS following the metal roughness convention.
  42235. *
  42236. * This fits to the PBR convention in the GLTF definition:
  42237. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42238. */
  42239. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42240. __extends(PBRMetallicRoughnessMaterial, _super);
  42241. /**
  42242. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42243. *
  42244. * @param name The material name
  42245. * @param scene The scene the material will be use in.
  42246. */
  42247. function PBRMetallicRoughnessMaterial(name, scene) {
  42248. var _this = _super.call(this, name, scene) || this;
  42249. _this._useRoughnessFromMetallicTextureAlpha = false;
  42250. _this._useRoughnessFromMetallicTextureGreen = true;
  42251. _this._useMetallnessFromMetallicTextureBlue = true;
  42252. _this._forceMetallicWorkflow = true;
  42253. return _this;
  42254. }
  42255. /**
  42256. * Return the currrent class name of the material.
  42257. */
  42258. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42259. return "PBRMetallicRoughnessMaterial";
  42260. };
  42261. /**
  42262. * Return the active textures of the material.
  42263. */
  42264. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42265. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42266. if (this.baseTexture) {
  42267. activeTextures.push(this.baseTexture);
  42268. }
  42269. if (this.metallicRoughnessTexture) {
  42270. activeTextures.push(this.metallicRoughnessTexture);
  42271. }
  42272. return activeTextures;
  42273. };
  42274. /**
  42275. * Checks to see if a texture is used in the material.
  42276. * @param texture - Base texture to use.
  42277. * @returns - Boolean specifying if a texture is used in the material.
  42278. */
  42279. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42280. if (_super.prototype.hasTexture.call(this, texture)) {
  42281. return true;
  42282. }
  42283. if (this.baseTexture === texture) {
  42284. return true;
  42285. }
  42286. if (this.metallicRoughnessTexture === texture) {
  42287. return true;
  42288. }
  42289. return false;
  42290. };
  42291. /**
  42292. * Makes a duplicate of the current material.
  42293. * @param name - name to use for the new material.
  42294. */
  42295. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42296. var _this = this;
  42297. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42298. clone.id = name;
  42299. clone.name = name;
  42300. return clone;
  42301. };
  42302. /**
  42303. * Serialize the material to a parsable JSON object.
  42304. */
  42305. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42306. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42307. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42308. return serializationObject;
  42309. };
  42310. /**
  42311. * Parses a JSON object correponding to the serialize function.
  42312. */
  42313. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42314. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42315. };
  42316. __decorate([
  42317. BABYLON.serializeAsColor3(),
  42318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42319. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42320. __decorate([
  42321. BABYLON.serializeAsTexture(),
  42322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42323. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42324. __decorate([
  42325. BABYLON.serialize(),
  42326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42327. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42328. __decorate([
  42329. BABYLON.serialize(),
  42330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42331. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42332. __decorate([
  42333. BABYLON.serializeAsTexture(),
  42334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42335. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42336. return PBRMetallicRoughnessMaterial;
  42337. }(BABYLON.PBRBaseSimpleMaterial));
  42338. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42339. })(BABYLON || (BABYLON = {}));
  42340. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42341. var BABYLON;
  42342. (function (BABYLON) {
  42343. /**
  42344. * The PBR material of BJS following the specular glossiness convention.
  42345. *
  42346. * This fits to the PBR convention in the GLTF definition:
  42347. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42348. */
  42349. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42350. __extends(PBRSpecularGlossinessMaterial, _super);
  42351. /**
  42352. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42353. *
  42354. * @param name The material name
  42355. * @param scene The scene the material will be use in.
  42356. */
  42357. function PBRSpecularGlossinessMaterial(name, scene) {
  42358. var _this = _super.call(this, name, scene) || this;
  42359. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42360. return _this;
  42361. }
  42362. /**
  42363. * Return the currrent class name of the material.
  42364. */
  42365. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42366. return "PBRSpecularGlossinessMaterial";
  42367. };
  42368. /**
  42369. * Return the active textures of the material.
  42370. */
  42371. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42372. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42373. if (this.diffuseTexture) {
  42374. activeTextures.push(this.diffuseTexture);
  42375. }
  42376. if (this.specularGlossinessTexture) {
  42377. activeTextures.push(this.specularGlossinessTexture);
  42378. }
  42379. return activeTextures;
  42380. };
  42381. /**
  42382. * Checks to see if a texture is used in the material.
  42383. * @param texture - Base texture to use.
  42384. * @returns - Boolean specifying if a texture is used in the material.
  42385. */
  42386. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42387. if (_super.prototype.hasTexture.call(this, texture)) {
  42388. return true;
  42389. }
  42390. if (this.diffuseTexture === texture) {
  42391. return true;
  42392. }
  42393. if (this.specularGlossinessTexture === texture) {
  42394. return true;
  42395. }
  42396. return false;
  42397. };
  42398. /**
  42399. * Makes a duplicate of the current material.
  42400. * @param name - name to use for the new material.
  42401. */
  42402. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42403. var _this = this;
  42404. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42405. clone.id = name;
  42406. clone.name = name;
  42407. return clone;
  42408. };
  42409. /**
  42410. * Serialize the material to a parsable JSON object.
  42411. */
  42412. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42413. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42414. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42415. return serializationObject;
  42416. };
  42417. /**
  42418. * Parses a JSON object correponding to the serialize function.
  42419. */
  42420. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42421. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42422. };
  42423. __decorate([
  42424. BABYLON.serializeAsColor3("diffuse"),
  42425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42426. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42427. __decorate([
  42428. BABYLON.serializeAsTexture(),
  42429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42430. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42431. __decorate([
  42432. BABYLON.serializeAsColor3("specular"),
  42433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42434. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42435. __decorate([
  42436. BABYLON.serialize(),
  42437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42438. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42439. __decorate([
  42440. BABYLON.serializeAsTexture(),
  42441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42442. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42443. return PBRSpecularGlossinessMaterial;
  42444. }(BABYLON.PBRBaseSimpleMaterial));
  42445. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42446. })(BABYLON || (BABYLON = {}));
  42447. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42448. var BABYLON;
  42449. (function (BABYLON) {
  42450. BABYLON.CameraInputTypes = {};
  42451. var CameraInputsManager = /** @class */ (function () {
  42452. function CameraInputsManager(camera) {
  42453. this.attached = {};
  42454. this.camera = camera;
  42455. this.checkInputs = function () { };
  42456. }
  42457. /**
  42458. * Add an input method to a camera.
  42459. * builtin inputs example: camera.inputs.addGamepad();
  42460. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42461. * @param input camera input method
  42462. */
  42463. CameraInputsManager.prototype.add = function (input) {
  42464. var type = input.getSimpleName();
  42465. if (this.attached[type]) {
  42466. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42467. return;
  42468. }
  42469. this.attached[type] = input;
  42470. input.camera = this.camera;
  42471. //for checkInputs, we are dynamically creating a function
  42472. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42473. if (input.checkInputs) {
  42474. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42475. }
  42476. if (this.attachedElement) {
  42477. input.attachControl(this.attachedElement);
  42478. }
  42479. };
  42480. /**
  42481. * Remove a specific input method from a camera
  42482. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42483. * @param inputToRemove camera input method
  42484. */
  42485. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42486. for (var cam in this.attached) {
  42487. var input = this.attached[cam];
  42488. if (input === inputToRemove) {
  42489. input.detachControl(this.attachedElement);
  42490. input.camera = null;
  42491. delete this.attached[cam];
  42492. this.rebuildInputCheck();
  42493. }
  42494. }
  42495. };
  42496. CameraInputsManager.prototype.removeByType = function (inputType) {
  42497. for (var cam in this.attached) {
  42498. var input = this.attached[cam];
  42499. if (input.getClassName() === inputType) {
  42500. input.detachControl(this.attachedElement);
  42501. input.camera = null;
  42502. delete this.attached[cam];
  42503. this.rebuildInputCheck();
  42504. }
  42505. }
  42506. };
  42507. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42508. var current = this.checkInputs;
  42509. return function () {
  42510. current();
  42511. fn();
  42512. };
  42513. };
  42514. CameraInputsManager.prototype.attachInput = function (input) {
  42515. if (this.attachedElement) {
  42516. input.attachControl(this.attachedElement, this.noPreventDefault);
  42517. }
  42518. };
  42519. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42520. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42521. if (this.attachedElement) {
  42522. return;
  42523. }
  42524. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42525. this.attachedElement = element;
  42526. this.noPreventDefault = noPreventDefault;
  42527. for (var cam in this.attached) {
  42528. this.attached[cam].attachControl(element, noPreventDefault);
  42529. }
  42530. };
  42531. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42532. if (disconnect === void 0) { disconnect = false; }
  42533. if (this.attachedElement !== element) {
  42534. return;
  42535. }
  42536. for (var cam in this.attached) {
  42537. this.attached[cam].detachControl(element);
  42538. if (disconnect) {
  42539. this.attached[cam].camera = null;
  42540. }
  42541. }
  42542. this.attachedElement = null;
  42543. };
  42544. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42545. this.checkInputs = function () { };
  42546. for (var cam in this.attached) {
  42547. var input = this.attached[cam];
  42548. if (input.checkInputs) {
  42549. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42550. }
  42551. }
  42552. };
  42553. /**
  42554. * Remove all attached input methods from a camera
  42555. */
  42556. CameraInputsManager.prototype.clear = function () {
  42557. if (this.attachedElement) {
  42558. this.detachElement(this.attachedElement, true);
  42559. }
  42560. this.attached = {};
  42561. this.attachedElement = null;
  42562. this.checkInputs = function () { };
  42563. };
  42564. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42565. var inputs = {};
  42566. for (var cam in this.attached) {
  42567. var input = this.attached[cam];
  42568. var res = BABYLON.SerializationHelper.Serialize(input);
  42569. inputs[input.getClassName()] = res;
  42570. }
  42571. serializedCamera.inputsmgr = inputs;
  42572. };
  42573. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42574. var parsedInputs = parsedCamera.inputsmgr;
  42575. if (parsedInputs) {
  42576. this.clear();
  42577. for (var n in parsedInputs) {
  42578. var construct = BABYLON.CameraInputTypes[n];
  42579. if (construct) {
  42580. var parsedinput = parsedInputs[n];
  42581. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42582. this.add(input);
  42583. }
  42584. }
  42585. }
  42586. else {
  42587. //2016-03-08 this part is for managing backward compatibility
  42588. for (var n in this.attached) {
  42589. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42590. if (construct) {
  42591. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42592. this.remove(this.attached[n]);
  42593. this.add(input);
  42594. }
  42595. }
  42596. }
  42597. };
  42598. return CameraInputsManager;
  42599. }());
  42600. BABYLON.CameraInputsManager = CameraInputsManager;
  42601. })(BABYLON || (BABYLON = {}));
  42602. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42603. var BABYLON;
  42604. (function (BABYLON) {
  42605. var TargetCamera = /** @class */ (function (_super) {
  42606. __extends(TargetCamera, _super);
  42607. function TargetCamera(name, position, scene) {
  42608. var _this = _super.call(this, name, position, scene) || this;
  42609. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42610. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42611. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42612. _this.speed = 2.0;
  42613. _this.noRotationConstraint = false;
  42614. _this.lockedTarget = null;
  42615. _this._currentTarget = BABYLON.Vector3.Zero();
  42616. _this._viewMatrix = BABYLON.Matrix.Zero();
  42617. _this._camMatrix = BABYLON.Matrix.Zero();
  42618. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42619. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42620. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42621. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42622. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42623. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42624. _this._tempMatrix = BABYLON.Matrix.Zero();
  42625. return _this;
  42626. }
  42627. TargetCamera.prototype.getFrontPosition = function (distance) {
  42628. this.getWorldMatrix();
  42629. var direction = this.getTarget().subtract(this.position);
  42630. direction.normalize();
  42631. direction.scaleInPlace(distance);
  42632. return this.globalPosition.add(direction);
  42633. };
  42634. TargetCamera.prototype._getLockedTargetPosition = function () {
  42635. if (!this.lockedTarget) {
  42636. return null;
  42637. }
  42638. if (this.lockedTarget.absolutePosition) {
  42639. this.lockedTarget.computeWorldMatrix();
  42640. }
  42641. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42642. };
  42643. TargetCamera.prototype.storeState = function () {
  42644. this._storedPosition = this.position.clone();
  42645. this._storedRotation = this.rotation.clone();
  42646. if (this.rotationQuaternion) {
  42647. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42648. }
  42649. return _super.prototype.storeState.call(this);
  42650. };
  42651. /**
  42652. * Restored camera state. You must call storeState() first
  42653. */
  42654. TargetCamera.prototype._restoreStateValues = function () {
  42655. if (!_super.prototype._restoreStateValues.call(this)) {
  42656. return false;
  42657. }
  42658. this.position = this._storedPosition.clone();
  42659. this.rotation = this._storedRotation.clone();
  42660. if (this.rotationQuaternion) {
  42661. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42662. }
  42663. this.cameraDirection.copyFromFloats(0, 0, 0);
  42664. this.cameraRotation.copyFromFloats(0, 0);
  42665. return true;
  42666. };
  42667. // Cache
  42668. TargetCamera.prototype._initCache = function () {
  42669. _super.prototype._initCache.call(this);
  42670. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42671. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42672. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42673. };
  42674. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42675. if (!ignoreParentClass) {
  42676. _super.prototype._updateCache.call(this);
  42677. }
  42678. var lockedTargetPosition = this._getLockedTargetPosition();
  42679. if (!lockedTargetPosition) {
  42680. this._cache.lockedTarget = null;
  42681. }
  42682. else {
  42683. if (!this._cache.lockedTarget) {
  42684. this._cache.lockedTarget = lockedTargetPosition.clone();
  42685. }
  42686. else {
  42687. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42688. }
  42689. }
  42690. this._cache.rotation.copyFrom(this.rotation);
  42691. if (this.rotationQuaternion)
  42692. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42693. };
  42694. // Synchronized
  42695. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42696. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42697. return false;
  42698. }
  42699. var lockedTargetPosition = this._getLockedTargetPosition();
  42700. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42701. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42702. };
  42703. // Methods
  42704. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42705. var engine = this.getEngine();
  42706. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42707. };
  42708. // Target
  42709. TargetCamera.prototype.setTarget = function (target) {
  42710. this.upVector.normalize();
  42711. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42712. this._camMatrix.invert();
  42713. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42714. var vDir = target.subtract(this.position);
  42715. if (vDir.x >= 0.0) {
  42716. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42717. }
  42718. else {
  42719. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42720. }
  42721. this.rotation.z = 0;
  42722. if (isNaN(this.rotation.x)) {
  42723. this.rotation.x = 0;
  42724. }
  42725. if (isNaN(this.rotation.y)) {
  42726. this.rotation.y = 0;
  42727. }
  42728. if (isNaN(this.rotation.z)) {
  42729. this.rotation.z = 0;
  42730. }
  42731. if (this.rotationQuaternion) {
  42732. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42733. }
  42734. };
  42735. /**
  42736. * Return the current target position of the camera. This value is expressed in local space.
  42737. */
  42738. TargetCamera.prototype.getTarget = function () {
  42739. return this._currentTarget;
  42740. };
  42741. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42742. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42743. };
  42744. TargetCamera.prototype._updatePosition = function () {
  42745. if (this.parent) {
  42746. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42747. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42748. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42749. return;
  42750. }
  42751. this.position.addInPlace(this.cameraDirection);
  42752. };
  42753. TargetCamera.prototype._checkInputs = function () {
  42754. var needToMove = this._decideIfNeedsToMove();
  42755. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42756. // Move
  42757. if (needToMove) {
  42758. this._updatePosition();
  42759. }
  42760. // Rotate
  42761. if (needToRotate) {
  42762. this.rotation.x += this.cameraRotation.x;
  42763. this.rotation.y += this.cameraRotation.y;
  42764. //rotate, if quaternion is set and rotation was used
  42765. if (this.rotationQuaternion) {
  42766. var len = this.rotation.lengthSquared();
  42767. if (len) {
  42768. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42769. }
  42770. }
  42771. if (!this.noRotationConstraint) {
  42772. var limit = (Math.PI / 2) * 0.95;
  42773. if (this.rotation.x > limit)
  42774. this.rotation.x = limit;
  42775. if (this.rotation.x < -limit)
  42776. this.rotation.x = -limit;
  42777. }
  42778. }
  42779. // Inertia
  42780. if (needToMove) {
  42781. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42782. this.cameraDirection.x = 0;
  42783. }
  42784. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42785. this.cameraDirection.y = 0;
  42786. }
  42787. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42788. this.cameraDirection.z = 0;
  42789. }
  42790. this.cameraDirection.scaleInPlace(this.inertia);
  42791. }
  42792. if (needToRotate) {
  42793. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42794. this.cameraRotation.x = 0;
  42795. }
  42796. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42797. this.cameraRotation.y = 0;
  42798. }
  42799. this.cameraRotation.scaleInPlace(this.inertia);
  42800. }
  42801. _super.prototype._checkInputs.call(this);
  42802. };
  42803. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42804. if (this.rotationQuaternion) {
  42805. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42806. }
  42807. else {
  42808. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42809. }
  42810. //update the up vector!
  42811. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42812. };
  42813. TargetCamera.prototype._getViewMatrix = function () {
  42814. if (this.lockedTarget) {
  42815. this.setTarget(this._getLockedTargetPosition());
  42816. }
  42817. // Compute
  42818. this._updateCameraRotationMatrix();
  42819. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42820. // Computing target and final matrix
  42821. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42822. if (this.getScene().useRightHandedSystem) {
  42823. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42824. }
  42825. else {
  42826. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42827. }
  42828. return this._viewMatrix;
  42829. };
  42830. /**
  42831. * @override
  42832. * Override Camera.createRigCamera
  42833. */
  42834. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42835. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42836. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42837. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42838. if (!this.rotationQuaternion) {
  42839. this.rotationQuaternion = new BABYLON.Quaternion();
  42840. }
  42841. rigCamera._cameraRigParams = {};
  42842. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42843. }
  42844. return rigCamera;
  42845. }
  42846. return null;
  42847. };
  42848. /**
  42849. * @override
  42850. * Override Camera._updateRigCameras
  42851. */
  42852. TargetCamera.prototype._updateRigCameras = function () {
  42853. var camLeft = this._rigCameras[0];
  42854. var camRight = this._rigCameras[1];
  42855. switch (this.cameraRigMode) {
  42856. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42857. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42858. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42859. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42860. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42861. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42862. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42863. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42864. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42865. camLeft.setTarget(this.getTarget());
  42866. camRight.setTarget(this.getTarget());
  42867. break;
  42868. case BABYLON.Camera.RIG_MODE_VR:
  42869. if (camLeft.rotationQuaternion) {
  42870. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42871. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42872. }
  42873. else {
  42874. camLeft.rotation.copyFrom(this.rotation);
  42875. camRight.rotation.copyFrom(this.rotation);
  42876. }
  42877. camLeft.position.copyFrom(this.position);
  42878. camRight.position.copyFrom(this.position);
  42879. break;
  42880. }
  42881. _super.prototype._updateRigCameras.call(this);
  42882. };
  42883. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42884. if (!this._rigCamTransformMatrix) {
  42885. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42886. }
  42887. var target = this.getTarget();
  42888. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42889. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42890. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42891. };
  42892. TargetCamera.prototype.getClassName = function () {
  42893. return "TargetCamera";
  42894. };
  42895. __decorate([
  42896. BABYLON.serializeAsVector3()
  42897. ], TargetCamera.prototype, "rotation", void 0);
  42898. __decorate([
  42899. BABYLON.serialize()
  42900. ], TargetCamera.prototype, "speed", void 0);
  42901. __decorate([
  42902. BABYLON.serializeAsMeshReference("lockedTargetId")
  42903. ], TargetCamera.prototype, "lockedTarget", void 0);
  42904. return TargetCamera;
  42905. }(BABYLON.Camera));
  42906. BABYLON.TargetCamera = TargetCamera;
  42907. })(BABYLON || (BABYLON = {}));
  42908. //# sourceMappingURL=babylon.targetCamera.js.map
  42909. var BABYLON;
  42910. (function (BABYLON) {
  42911. var FreeCameraMouseInput = /** @class */ (function () {
  42912. function FreeCameraMouseInput(touchEnabled) {
  42913. if (touchEnabled === void 0) { touchEnabled = true; }
  42914. this.touchEnabled = touchEnabled;
  42915. this.buttons = [0, 1, 2];
  42916. this.angularSensibility = 2000.0;
  42917. this.previousPosition = null;
  42918. }
  42919. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42920. var _this = this;
  42921. var engine = this.camera.getEngine();
  42922. if (!this._pointerInput) {
  42923. this._pointerInput = function (p, s) {
  42924. var evt = p.event;
  42925. if (engine.isInVRExclusivePointerMode) {
  42926. return;
  42927. }
  42928. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42929. return;
  42930. }
  42931. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42932. return;
  42933. }
  42934. var srcElement = (evt.srcElement || evt.target);
  42935. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42936. try {
  42937. srcElement.setPointerCapture(evt.pointerId);
  42938. }
  42939. catch (e) {
  42940. //Nothing to do with the error. Execution will continue.
  42941. }
  42942. _this.previousPosition = {
  42943. x: evt.clientX,
  42944. y: evt.clientY
  42945. };
  42946. if (!noPreventDefault) {
  42947. evt.preventDefault();
  42948. element.focus();
  42949. }
  42950. }
  42951. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42952. try {
  42953. srcElement.releasePointerCapture(evt.pointerId);
  42954. }
  42955. catch (e) {
  42956. //Nothing to do with the error.
  42957. }
  42958. _this.previousPosition = null;
  42959. if (!noPreventDefault) {
  42960. evt.preventDefault();
  42961. }
  42962. }
  42963. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42964. if (!_this.previousPosition || engine.isPointerLock) {
  42965. return;
  42966. }
  42967. var offsetX = evt.clientX - _this.previousPosition.x;
  42968. var offsetY = evt.clientY - _this.previousPosition.y;
  42969. if (_this.camera.getScene().useRightHandedSystem) {
  42970. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42971. }
  42972. else {
  42973. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42974. }
  42975. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42976. _this.previousPosition = {
  42977. x: evt.clientX,
  42978. y: evt.clientY
  42979. };
  42980. if (!noPreventDefault) {
  42981. evt.preventDefault();
  42982. }
  42983. }
  42984. };
  42985. }
  42986. this._onMouseMove = function (evt) {
  42987. if (!engine.isPointerLock) {
  42988. return;
  42989. }
  42990. if (engine.isInVRExclusivePointerMode) {
  42991. return;
  42992. }
  42993. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42994. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42995. if (_this.camera.getScene().useRightHandedSystem) {
  42996. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42997. }
  42998. else {
  42999. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43000. }
  43001. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43002. _this.previousPosition = null;
  43003. if (!noPreventDefault) {
  43004. evt.preventDefault();
  43005. }
  43006. };
  43007. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43008. element.addEventListener("mousemove", this._onMouseMove, false);
  43009. };
  43010. FreeCameraMouseInput.prototype.detachControl = function (element) {
  43011. if (this._observer && element) {
  43012. this.camera.getScene().onPointerObservable.remove(this._observer);
  43013. if (this._onMouseMove) {
  43014. element.removeEventListener("mousemove", this._onMouseMove);
  43015. }
  43016. this._observer = null;
  43017. this._onMouseMove = null;
  43018. this.previousPosition = null;
  43019. }
  43020. };
  43021. FreeCameraMouseInput.prototype.getClassName = function () {
  43022. return "FreeCameraMouseInput";
  43023. };
  43024. FreeCameraMouseInput.prototype.getSimpleName = function () {
  43025. return "mouse";
  43026. };
  43027. __decorate([
  43028. BABYLON.serialize()
  43029. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  43030. __decorate([
  43031. BABYLON.serialize()
  43032. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  43033. return FreeCameraMouseInput;
  43034. }());
  43035. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  43036. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  43037. })(BABYLON || (BABYLON = {}));
  43038. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  43039. var BABYLON;
  43040. (function (BABYLON) {
  43041. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  43042. function FreeCameraKeyboardMoveInput() {
  43043. this._keys = new Array();
  43044. this.keysUp = [38];
  43045. this.keysDown = [40];
  43046. this.keysLeft = [37];
  43047. this.keysRight = [39];
  43048. }
  43049. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43050. var _this = this;
  43051. if (this._onCanvasBlurObserver) {
  43052. return;
  43053. }
  43054. this._scene = this.camera.getScene();
  43055. this._engine = this._scene.getEngine();
  43056. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43057. _this._keys = [];
  43058. });
  43059. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43060. var evt = info.event;
  43061. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43062. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43063. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43064. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43065. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43066. var index = _this._keys.indexOf(evt.keyCode);
  43067. if (index === -1) {
  43068. _this._keys.push(evt.keyCode);
  43069. }
  43070. if (!noPreventDefault) {
  43071. evt.preventDefault();
  43072. }
  43073. }
  43074. }
  43075. else {
  43076. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43077. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43078. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43079. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43080. var index = _this._keys.indexOf(evt.keyCode);
  43081. if (index >= 0) {
  43082. _this._keys.splice(index, 1);
  43083. }
  43084. if (!noPreventDefault) {
  43085. evt.preventDefault();
  43086. }
  43087. }
  43088. }
  43089. });
  43090. };
  43091. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43092. if (this._scene) {
  43093. if (this._onKeyboardObserver) {
  43094. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43095. }
  43096. if (this._onCanvasBlurObserver) {
  43097. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43098. }
  43099. this._onKeyboardObserver = null;
  43100. this._onCanvasBlurObserver = null;
  43101. }
  43102. this._keys = [];
  43103. };
  43104. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43105. if (this._onKeyboardObserver) {
  43106. var camera = this.camera;
  43107. // Keyboard
  43108. for (var index = 0; index < this._keys.length; index++) {
  43109. var keyCode = this._keys[index];
  43110. var speed = camera._computeLocalCameraSpeed();
  43111. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43112. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43113. }
  43114. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43115. camera._localDirection.copyFromFloats(0, 0, speed);
  43116. }
  43117. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43118. camera._localDirection.copyFromFloats(speed, 0, 0);
  43119. }
  43120. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43121. camera._localDirection.copyFromFloats(0, 0, -speed);
  43122. }
  43123. if (camera.getScene().useRightHandedSystem) {
  43124. camera._localDirection.z *= -1;
  43125. }
  43126. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43127. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43128. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43129. }
  43130. }
  43131. };
  43132. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43133. return "FreeCameraKeyboardMoveInput";
  43134. };
  43135. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43136. this._keys = [];
  43137. };
  43138. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43139. return "keyboard";
  43140. };
  43141. __decorate([
  43142. BABYLON.serialize()
  43143. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43144. __decorate([
  43145. BABYLON.serialize()
  43146. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43147. __decorate([
  43148. BABYLON.serialize()
  43149. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43150. __decorate([
  43151. BABYLON.serialize()
  43152. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43153. return FreeCameraKeyboardMoveInput;
  43154. }());
  43155. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43156. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43157. })(BABYLON || (BABYLON = {}));
  43158. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43159. var BABYLON;
  43160. (function (BABYLON) {
  43161. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43162. __extends(FreeCameraInputsManager, _super);
  43163. function FreeCameraInputsManager(camera) {
  43164. return _super.call(this, camera) || this;
  43165. }
  43166. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43167. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43168. return this;
  43169. };
  43170. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43171. if (touchEnabled === void 0) { touchEnabled = true; }
  43172. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43173. return this;
  43174. };
  43175. FreeCameraInputsManager.prototype.addGamepad = function () {
  43176. this.add(new BABYLON.FreeCameraGamepadInput());
  43177. return this;
  43178. };
  43179. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43180. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43181. return this;
  43182. };
  43183. FreeCameraInputsManager.prototype.addTouch = function () {
  43184. this.add(new BABYLON.FreeCameraTouchInput());
  43185. return this;
  43186. };
  43187. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43188. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43189. return this;
  43190. };
  43191. return FreeCameraInputsManager;
  43192. }(BABYLON.CameraInputsManager));
  43193. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43194. })(BABYLON || (BABYLON = {}));
  43195. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43196. var BABYLON;
  43197. (function (BABYLON) {
  43198. var FreeCamera = /** @class */ (function (_super) {
  43199. __extends(FreeCamera, _super);
  43200. function FreeCamera(name, position, scene) {
  43201. var _this = _super.call(this, name, position, scene) || this;
  43202. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43203. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43204. _this.checkCollisions = false;
  43205. _this.applyGravity = false;
  43206. _this._needMoveForGravity = false;
  43207. _this._oldPosition = BABYLON.Vector3.Zero();
  43208. _this._diffPosition = BABYLON.Vector3.Zero();
  43209. _this._newPosition = BABYLON.Vector3.Zero();
  43210. // Collisions
  43211. _this._collisionMask = -1;
  43212. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43213. if (collidedMesh === void 0) { collidedMesh = null; }
  43214. //TODO move this to the collision coordinator!
  43215. if (_this.getScene().workerCollisions)
  43216. newPosition.multiplyInPlace(_this._collider._radius);
  43217. var updatePosition = function (newPos) {
  43218. _this._newPosition.copyFrom(newPos);
  43219. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43220. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43221. _this.position.addInPlace(_this._diffPosition);
  43222. if (_this.onCollide && collidedMesh) {
  43223. _this.onCollide(collidedMesh);
  43224. }
  43225. }
  43226. };
  43227. updatePosition(newPosition);
  43228. };
  43229. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43230. _this.inputs.addKeyboard().addMouse();
  43231. return _this;
  43232. }
  43233. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43234. //-- begin properties for backward compatibility for inputs
  43235. /**
  43236. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43237. * Higher values reduce sensitivity.
  43238. */
  43239. get: function () {
  43240. var mouse = this.inputs.attached["mouse"];
  43241. if (mouse)
  43242. return mouse.angularSensibility;
  43243. return 0;
  43244. },
  43245. /**
  43246. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43247. * Higher values reduce sensitivity.
  43248. */
  43249. set: function (value) {
  43250. var mouse = this.inputs.attached["mouse"];
  43251. if (mouse)
  43252. mouse.angularSensibility = value;
  43253. },
  43254. enumerable: true,
  43255. configurable: true
  43256. });
  43257. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43258. get: function () {
  43259. var keyboard = this.inputs.attached["keyboard"];
  43260. if (keyboard)
  43261. return keyboard.keysUp;
  43262. return [];
  43263. },
  43264. set: function (value) {
  43265. var keyboard = this.inputs.attached["keyboard"];
  43266. if (keyboard)
  43267. keyboard.keysUp = value;
  43268. },
  43269. enumerable: true,
  43270. configurable: true
  43271. });
  43272. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43273. get: function () {
  43274. var keyboard = this.inputs.attached["keyboard"];
  43275. if (keyboard)
  43276. return keyboard.keysDown;
  43277. return [];
  43278. },
  43279. set: function (value) {
  43280. var keyboard = this.inputs.attached["keyboard"];
  43281. if (keyboard)
  43282. keyboard.keysDown = value;
  43283. },
  43284. enumerable: true,
  43285. configurable: true
  43286. });
  43287. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43288. get: function () {
  43289. var keyboard = this.inputs.attached["keyboard"];
  43290. if (keyboard)
  43291. return keyboard.keysLeft;
  43292. return [];
  43293. },
  43294. set: function (value) {
  43295. var keyboard = this.inputs.attached["keyboard"];
  43296. if (keyboard)
  43297. keyboard.keysLeft = value;
  43298. },
  43299. enumerable: true,
  43300. configurable: true
  43301. });
  43302. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43303. get: function () {
  43304. var keyboard = this.inputs.attached["keyboard"];
  43305. if (keyboard)
  43306. return keyboard.keysRight;
  43307. return [];
  43308. },
  43309. set: function (value) {
  43310. var keyboard = this.inputs.attached["keyboard"];
  43311. if (keyboard)
  43312. keyboard.keysRight = value;
  43313. },
  43314. enumerable: true,
  43315. configurable: true
  43316. });
  43317. // Controls
  43318. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43319. this.inputs.attachElement(element, noPreventDefault);
  43320. };
  43321. FreeCamera.prototype.detachControl = function (element) {
  43322. this.inputs.detachElement(element);
  43323. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43324. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43325. };
  43326. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43327. get: function () {
  43328. return this._collisionMask;
  43329. },
  43330. set: function (mask) {
  43331. this._collisionMask = !isNaN(mask) ? mask : -1;
  43332. },
  43333. enumerable: true,
  43334. configurable: true
  43335. });
  43336. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43337. var globalPosition;
  43338. if (this.parent) {
  43339. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43340. }
  43341. else {
  43342. globalPosition = this.position;
  43343. }
  43344. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43345. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43346. if (!this._collider) {
  43347. this._collider = new BABYLON.Collider();
  43348. }
  43349. this._collider._radius = this.ellipsoid;
  43350. this._collider.collisionMask = this._collisionMask;
  43351. //no need for clone, as long as gravity is not on.
  43352. var actualDisplacement = displacement;
  43353. //add gravity to the direction to prevent the dual-collision checking
  43354. if (this.applyGravity) {
  43355. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43356. actualDisplacement = displacement.add(this.getScene().gravity);
  43357. }
  43358. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43359. };
  43360. FreeCamera.prototype._checkInputs = function () {
  43361. if (!this._localDirection) {
  43362. this._localDirection = BABYLON.Vector3.Zero();
  43363. this._transformedDirection = BABYLON.Vector3.Zero();
  43364. }
  43365. this.inputs.checkInputs();
  43366. _super.prototype._checkInputs.call(this);
  43367. };
  43368. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43369. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43370. };
  43371. FreeCamera.prototype._updatePosition = function () {
  43372. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43373. this._collideWithWorld(this.cameraDirection);
  43374. }
  43375. else {
  43376. _super.prototype._updatePosition.call(this);
  43377. }
  43378. };
  43379. FreeCamera.prototype.dispose = function () {
  43380. this.inputs.clear();
  43381. _super.prototype.dispose.call(this);
  43382. };
  43383. FreeCamera.prototype.getClassName = function () {
  43384. return "FreeCamera";
  43385. };
  43386. __decorate([
  43387. BABYLON.serializeAsVector3()
  43388. ], FreeCamera.prototype, "ellipsoid", void 0);
  43389. __decorate([
  43390. BABYLON.serializeAsVector3()
  43391. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43392. __decorate([
  43393. BABYLON.serialize()
  43394. ], FreeCamera.prototype, "checkCollisions", void 0);
  43395. __decorate([
  43396. BABYLON.serialize()
  43397. ], FreeCamera.prototype, "applyGravity", void 0);
  43398. return FreeCamera;
  43399. }(BABYLON.TargetCamera));
  43400. BABYLON.FreeCamera = FreeCamera;
  43401. })(BABYLON || (BABYLON = {}));
  43402. //# sourceMappingURL=babylon.freeCamera.js.map
  43403. var BABYLON;
  43404. (function (BABYLON) {
  43405. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43406. function ArcRotateCameraKeyboardMoveInput() {
  43407. this._keys = new Array();
  43408. this.keysUp = [38];
  43409. this.keysDown = [40];
  43410. this.keysLeft = [37];
  43411. this.keysRight = [39];
  43412. this.keysReset = [220];
  43413. this.panningSensibility = 50.0;
  43414. this.zoomingSensibility = 25.0;
  43415. this.useAltToZoom = true;
  43416. }
  43417. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43418. var _this = this;
  43419. if (this._onCanvasBlurObserver) {
  43420. return;
  43421. }
  43422. this._scene = this.camera.getScene();
  43423. this._engine = this._scene.getEngine();
  43424. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43425. _this._keys = [];
  43426. });
  43427. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43428. var evt = info.event;
  43429. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43430. _this._ctrlPressed = evt.ctrlKey;
  43431. _this._altPressed = evt.altKey;
  43432. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43433. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43434. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43435. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43436. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43437. var index = _this._keys.indexOf(evt.keyCode);
  43438. if (index === -1) {
  43439. _this._keys.push(evt.keyCode);
  43440. }
  43441. if (evt.preventDefault) {
  43442. if (!noPreventDefault) {
  43443. evt.preventDefault();
  43444. }
  43445. }
  43446. }
  43447. }
  43448. else {
  43449. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43450. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43451. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43452. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43453. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43454. var index = _this._keys.indexOf(evt.keyCode);
  43455. if (index >= 0) {
  43456. _this._keys.splice(index, 1);
  43457. }
  43458. if (evt.preventDefault) {
  43459. if (!noPreventDefault) {
  43460. evt.preventDefault();
  43461. }
  43462. }
  43463. }
  43464. }
  43465. });
  43466. };
  43467. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43468. if (this._scene) {
  43469. if (this._onKeyboardObserver) {
  43470. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43471. }
  43472. if (this._onCanvasBlurObserver) {
  43473. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43474. }
  43475. this._onKeyboardObserver = null;
  43476. this._onCanvasBlurObserver = null;
  43477. }
  43478. this._keys = [];
  43479. };
  43480. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43481. if (this._onKeyboardObserver) {
  43482. var camera = this.camera;
  43483. for (var index = 0; index < this._keys.length; index++) {
  43484. var keyCode = this._keys[index];
  43485. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43486. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43487. camera.inertialPanningX -= 1 / this.panningSensibility;
  43488. }
  43489. else {
  43490. camera.inertialAlphaOffset -= 0.01;
  43491. }
  43492. }
  43493. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43494. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43495. camera.inertialPanningY += 1 / this.panningSensibility;
  43496. }
  43497. else if (this._altPressed && this.useAltToZoom) {
  43498. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43499. }
  43500. else {
  43501. camera.inertialBetaOffset -= 0.01;
  43502. }
  43503. }
  43504. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43505. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43506. camera.inertialPanningX += 1 / this.panningSensibility;
  43507. }
  43508. else {
  43509. camera.inertialAlphaOffset += 0.01;
  43510. }
  43511. }
  43512. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43513. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43514. camera.inertialPanningY -= 1 / this.panningSensibility;
  43515. }
  43516. else if (this._altPressed && this.useAltToZoom) {
  43517. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43518. }
  43519. else {
  43520. camera.inertialBetaOffset += 0.01;
  43521. }
  43522. }
  43523. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43524. camera.restoreState();
  43525. }
  43526. }
  43527. }
  43528. };
  43529. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43530. return "ArcRotateCameraKeyboardMoveInput";
  43531. };
  43532. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43533. return "keyboard";
  43534. };
  43535. __decorate([
  43536. BABYLON.serialize()
  43537. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43538. __decorate([
  43539. BABYLON.serialize()
  43540. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43541. __decorate([
  43542. BABYLON.serialize()
  43543. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43544. __decorate([
  43545. BABYLON.serialize()
  43546. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43547. __decorate([
  43548. BABYLON.serialize()
  43549. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43550. __decorate([
  43551. BABYLON.serialize()
  43552. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43553. __decorate([
  43554. BABYLON.serialize()
  43555. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43556. __decorate([
  43557. BABYLON.serialize()
  43558. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43559. return ArcRotateCameraKeyboardMoveInput;
  43560. }());
  43561. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43562. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43563. })(BABYLON || (BABYLON = {}));
  43564. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43565. var BABYLON;
  43566. (function (BABYLON) {
  43567. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43568. function ArcRotateCameraMouseWheelInput() {
  43569. this.wheelPrecision = 3.0;
  43570. /**
  43571. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43572. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43573. */
  43574. this.wheelDeltaPercentage = 0;
  43575. }
  43576. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43577. var _this = this;
  43578. this._wheel = function (p, s) {
  43579. //sanity check - this should be a PointerWheel event.
  43580. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43581. return;
  43582. var event = p.event;
  43583. var delta = 0;
  43584. if (event.wheelDelta) {
  43585. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43586. }
  43587. else if (event.detail) {
  43588. delta = -event.detail / _this.wheelPrecision;
  43589. }
  43590. if (delta)
  43591. _this.camera.inertialRadiusOffset += delta;
  43592. if (event.preventDefault) {
  43593. if (!noPreventDefault) {
  43594. event.preventDefault();
  43595. }
  43596. }
  43597. };
  43598. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43599. };
  43600. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43601. if (this._observer && element) {
  43602. this.camera.getScene().onPointerObservable.remove(this._observer);
  43603. this._observer = null;
  43604. this._wheel = null;
  43605. }
  43606. };
  43607. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43608. return "ArcRotateCameraMouseWheelInput";
  43609. };
  43610. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43611. return "mousewheel";
  43612. };
  43613. __decorate([
  43614. BABYLON.serialize()
  43615. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43616. __decorate([
  43617. BABYLON.serialize()
  43618. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43619. return ArcRotateCameraMouseWheelInput;
  43620. }());
  43621. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43622. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43623. })(BABYLON || (BABYLON = {}));
  43624. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43625. var BABYLON;
  43626. (function (BABYLON) {
  43627. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43628. function ArcRotateCameraPointersInput() {
  43629. this.buttons = [0, 1, 2];
  43630. this.angularSensibilityX = 1000.0;
  43631. this.angularSensibilityY = 1000.0;
  43632. this.pinchPrecision = 12.0;
  43633. /**
  43634. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43635. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43636. */
  43637. this.pinchDeltaPercentage = 0;
  43638. this.panningSensibility = 1000.0;
  43639. this.multiTouchPanning = true;
  43640. this.multiTouchPanAndZoom = true;
  43641. this._isPanClick = false;
  43642. this.pinchInwards = true;
  43643. }
  43644. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43645. var _this = this;
  43646. var engine = this.camera.getEngine();
  43647. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43648. var pointA = null;
  43649. var pointB = null;
  43650. var previousPinchSquaredDistance = 0;
  43651. var initialDistance = 0;
  43652. var twoFingerActivityCount = 0;
  43653. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43654. this._pointerInput = function (p, s) {
  43655. var evt = p.event;
  43656. var isTouch = p.event.pointerType === "touch";
  43657. if (engine.isInVRExclusivePointerMode) {
  43658. return;
  43659. }
  43660. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43661. return;
  43662. }
  43663. var srcElement = (evt.srcElement || evt.target);
  43664. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43665. try {
  43666. srcElement.setPointerCapture(evt.pointerId);
  43667. }
  43668. catch (e) {
  43669. //Nothing to do with the error. Execution will continue.
  43670. }
  43671. // Manage panning with pan button click
  43672. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43673. // manage pointers
  43674. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43675. if (pointA === null) {
  43676. pointA = cacheSoloPointer;
  43677. }
  43678. else if (pointB === null) {
  43679. pointB = cacheSoloPointer;
  43680. }
  43681. if (!noPreventDefault) {
  43682. evt.preventDefault();
  43683. element.focus();
  43684. }
  43685. }
  43686. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43687. _this.camera.restoreState();
  43688. }
  43689. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43690. try {
  43691. srcElement.releasePointerCapture(evt.pointerId);
  43692. }
  43693. catch (e) {
  43694. //Nothing to do with the error.
  43695. }
  43696. cacheSoloPointer = null;
  43697. previousPinchSquaredDistance = 0;
  43698. previousMultiTouchPanPosition.isPaning = false;
  43699. previousMultiTouchPanPosition.isPinching = false;
  43700. twoFingerActivityCount = 0;
  43701. initialDistance = 0;
  43702. if (!isTouch) {
  43703. pointB = null; // Mouse and pen are mono pointer
  43704. }
  43705. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43706. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43707. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43708. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43709. if (engine.badOS) {
  43710. pointA = pointB = null;
  43711. }
  43712. else {
  43713. //only remove the impacted pointer in case of multitouch allowing on most
  43714. //platforms switching from rotate to zoom and pan seamlessly.
  43715. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43716. pointA = pointB;
  43717. pointB = null;
  43718. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43719. }
  43720. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43721. pointB = null;
  43722. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43723. }
  43724. else {
  43725. pointA = pointB = null;
  43726. }
  43727. }
  43728. if (!noPreventDefault) {
  43729. evt.preventDefault();
  43730. }
  43731. }
  43732. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43733. if (!noPreventDefault) {
  43734. evt.preventDefault();
  43735. }
  43736. // One button down
  43737. if (pointA && pointB === null && cacheSoloPointer) {
  43738. if (_this.panningSensibility !== 0 &&
  43739. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43740. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43741. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43742. }
  43743. else {
  43744. var offsetX = evt.clientX - cacheSoloPointer.x;
  43745. var offsetY = evt.clientY - cacheSoloPointer.y;
  43746. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43747. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43748. }
  43749. cacheSoloPointer.x = evt.clientX;
  43750. cacheSoloPointer.y = evt.clientY;
  43751. }
  43752. else if (pointA && pointB) {
  43753. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43754. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43755. ed.x = evt.clientX;
  43756. ed.y = evt.clientY;
  43757. var direction = _this.pinchInwards ? 1 : -1;
  43758. var distX = pointA.x - pointB.x;
  43759. var distY = pointA.y - pointB.y;
  43760. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43761. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43762. if (previousPinchSquaredDistance === 0) {
  43763. initialDistance = pinchDistance;
  43764. previousPinchSquaredDistance = pinchSquaredDistance;
  43765. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43766. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43767. return;
  43768. }
  43769. if (_this.multiTouchPanAndZoom) {
  43770. if (_this.pinchDeltaPercentage) {
  43771. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43772. }
  43773. else {
  43774. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43775. (_this.pinchPrecision *
  43776. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43777. direction);
  43778. }
  43779. if (_this.panningSensibility !== 0) {
  43780. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43781. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43782. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43783. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43784. previousMultiTouchPanPosition.x = pointersCenterX;
  43785. previousMultiTouchPanPosition.y = pointersCenterY;
  43786. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43787. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43788. }
  43789. }
  43790. else {
  43791. twoFingerActivityCount++;
  43792. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43793. if (_this.pinchDeltaPercentage) {
  43794. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43795. }
  43796. else {
  43797. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43798. (_this.pinchPrecision *
  43799. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43800. direction);
  43801. }
  43802. previousMultiTouchPanPosition.isPaning = false;
  43803. previousMultiTouchPanPosition.isPinching = true;
  43804. }
  43805. else {
  43806. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43807. if (!previousMultiTouchPanPosition.isPaning) {
  43808. previousMultiTouchPanPosition.isPaning = true;
  43809. previousMultiTouchPanPosition.isPinching = false;
  43810. previousMultiTouchPanPosition.x = ed.x;
  43811. previousMultiTouchPanPosition.y = ed.y;
  43812. return;
  43813. }
  43814. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43815. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43816. }
  43817. }
  43818. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43819. previousMultiTouchPanPosition.x = ed.x;
  43820. previousMultiTouchPanPosition.y = ed.y;
  43821. }
  43822. }
  43823. previousPinchSquaredDistance = pinchSquaredDistance;
  43824. }
  43825. }
  43826. };
  43827. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43828. this._onContextMenu = function (evt) {
  43829. evt.preventDefault();
  43830. };
  43831. if (!this.camera._useCtrlForPanning) {
  43832. element.addEventListener("contextmenu", this._onContextMenu, false);
  43833. }
  43834. this._onLostFocus = function () {
  43835. //this._keys = [];
  43836. pointA = pointB = null;
  43837. previousPinchSquaredDistance = 0;
  43838. previousMultiTouchPanPosition.isPaning = false;
  43839. previousMultiTouchPanPosition.isPinching = false;
  43840. twoFingerActivityCount = 0;
  43841. cacheSoloPointer = null;
  43842. initialDistance = 0;
  43843. };
  43844. this._onMouseMove = function (evt) {
  43845. if (!engine.isPointerLock) {
  43846. return;
  43847. }
  43848. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43849. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43850. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43851. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43852. if (!noPreventDefault) {
  43853. evt.preventDefault();
  43854. }
  43855. };
  43856. this._onGestureStart = function (e) {
  43857. if (window.MSGesture === undefined) {
  43858. return;
  43859. }
  43860. if (!_this._MSGestureHandler) {
  43861. _this._MSGestureHandler = new MSGesture();
  43862. _this._MSGestureHandler.target = element;
  43863. }
  43864. _this._MSGestureHandler.addPointer(e.pointerId);
  43865. };
  43866. this._onGesture = function (e) {
  43867. _this.camera.radius *= e.scale;
  43868. if (e.preventDefault) {
  43869. if (!noPreventDefault) {
  43870. e.stopPropagation();
  43871. e.preventDefault();
  43872. }
  43873. }
  43874. };
  43875. element.addEventListener("mousemove", this._onMouseMove, false);
  43876. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43877. element.addEventListener("MSGestureChange", this._onGesture, false);
  43878. BABYLON.Tools.RegisterTopRootEvents([
  43879. { name: "blur", handler: this._onLostFocus }
  43880. ]);
  43881. };
  43882. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43883. if (this._onLostFocus) {
  43884. BABYLON.Tools.UnregisterTopRootEvents([
  43885. { name: "blur", handler: this._onLostFocus }
  43886. ]);
  43887. }
  43888. if (element && this._observer) {
  43889. this.camera.getScene().onPointerObservable.remove(this._observer);
  43890. this._observer = null;
  43891. if (this._onContextMenu) {
  43892. element.removeEventListener("contextmenu", this._onContextMenu);
  43893. }
  43894. if (this._onMouseMove) {
  43895. element.removeEventListener("mousemove", this._onMouseMove);
  43896. }
  43897. if (this._onGestureStart) {
  43898. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43899. }
  43900. if (this._onGesture) {
  43901. element.removeEventListener("MSGestureChange", this._onGesture);
  43902. }
  43903. this._isPanClick = false;
  43904. this.pinchInwards = true;
  43905. this._onMouseMove = null;
  43906. this._onGestureStart = null;
  43907. this._onGesture = null;
  43908. this._MSGestureHandler = null;
  43909. this._onLostFocus = null;
  43910. this._onContextMenu = null;
  43911. }
  43912. };
  43913. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43914. return "ArcRotateCameraPointersInput";
  43915. };
  43916. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43917. return "pointers";
  43918. };
  43919. __decorate([
  43920. BABYLON.serialize()
  43921. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43922. __decorate([
  43923. BABYLON.serialize()
  43924. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43925. __decorate([
  43926. BABYLON.serialize()
  43927. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43928. __decorate([
  43929. BABYLON.serialize()
  43930. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43931. __decorate([
  43932. BABYLON.serialize()
  43933. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43934. __decorate([
  43935. BABYLON.serialize()
  43936. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43937. __decorate([
  43938. BABYLON.serialize()
  43939. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43940. __decorate([
  43941. BABYLON.serialize()
  43942. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43943. return ArcRotateCameraPointersInput;
  43944. }());
  43945. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43946. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43947. })(BABYLON || (BABYLON = {}));
  43948. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43949. var BABYLON;
  43950. (function (BABYLON) {
  43951. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43952. __extends(ArcRotateCameraInputsManager, _super);
  43953. function ArcRotateCameraInputsManager(camera) {
  43954. return _super.call(this, camera) || this;
  43955. }
  43956. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43957. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43958. return this;
  43959. };
  43960. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43961. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43962. return this;
  43963. };
  43964. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43965. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43966. return this;
  43967. };
  43968. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43969. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43970. return this;
  43971. };
  43972. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43973. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43974. return this;
  43975. };
  43976. return ArcRotateCameraInputsManager;
  43977. }(BABYLON.CameraInputsManager));
  43978. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43979. })(BABYLON || (BABYLON = {}));
  43980. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43981. var BABYLON;
  43982. (function (BABYLON) {
  43983. var ArcRotateCamera = /** @class */ (function (_super) {
  43984. __extends(ArcRotateCamera, _super);
  43985. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43986. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43987. _this.inertialAlphaOffset = 0;
  43988. _this.inertialBetaOffset = 0;
  43989. _this.inertialRadiusOffset = 0;
  43990. _this.lowerAlphaLimit = null;
  43991. _this.upperAlphaLimit = null;
  43992. _this.lowerBetaLimit = 0.01;
  43993. _this.upperBetaLimit = Math.PI;
  43994. _this.lowerRadiusLimit = null;
  43995. _this.upperRadiusLimit = null;
  43996. _this.inertialPanningX = 0;
  43997. _this.inertialPanningY = 0;
  43998. _this.pinchToPanMaxDistance = 20;
  43999. _this.panningDistanceLimit = null;
  44000. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44001. _this.panningInertia = 0.9;
  44002. //-- end properties for backward compatibility for inputs
  44003. _this.zoomOnFactor = 1;
  44004. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  44005. _this.allowUpsideDown = true;
  44006. _this._viewMatrix = new BABYLON.Matrix();
  44007. // Panning
  44008. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  44009. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  44010. _this.checkCollisions = false;
  44011. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  44012. _this._previousPosition = BABYLON.Vector3.Zero();
  44013. _this._collisionVelocity = BABYLON.Vector3.Zero();
  44014. _this._newPosition = BABYLON.Vector3.Zero();
  44015. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44016. if (collidedMesh === void 0) { collidedMesh = null; }
  44017. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  44018. newPosition.multiplyInPlace(_this._collider._radius);
  44019. }
  44020. if (!collidedMesh) {
  44021. _this._previousPosition.copyFrom(_this.position);
  44022. }
  44023. else {
  44024. _this.setPosition(newPosition);
  44025. if (_this.onCollide) {
  44026. _this.onCollide(collidedMesh);
  44027. }
  44028. }
  44029. // Recompute because of constraints
  44030. var cosa = Math.cos(_this.alpha);
  44031. var sina = Math.sin(_this.alpha);
  44032. var cosb = Math.cos(_this.beta);
  44033. var sinb = Math.sin(_this.beta);
  44034. if (sinb === 0) {
  44035. sinb = 0.0001;
  44036. }
  44037. var target = _this._getTargetPosition();
  44038. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  44039. _this.position.copyFrom(_this._newPosition);
  44040. var up = _this.upVector;
  44041. if (_this.allowUpsideDown && _this.beta < 0) {
  44042. up = up.clone();
  44043. up = up.negate();
  44044. }
  44045. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  44046. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  44047. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  44048. _this._collisionTriggered = false;
  44049. };
  44050. _this._target = BABYLON.Vector3.Zero();
  44051. if (target) {
  44052. _this.setTarget(target);
  44053. }
  44054. _this.alpha = alpha;
  44055. _this.beta = beta;
  44056. _this.radius = radius;
  44057. _this.getViewMatrix();
  44058. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  44059. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  44060. return _this;
  44061. }
  44062. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  44063. get: function () {
  44064. return this._target;
  44065. },
  44066. set: function (value) {
  44067. this.setTarget(value);
  44068. },
  44069. enumerable: true,
  44070. configurable: true
  44071. });
  44072. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  44073. //-- begin properties for backward compatibility for inputs
  44074. get: function () {
  44075. var pointers = this.inputs.attached["pointers"];
  44076. if (pointers)
  44077. return pointers.angularSensibilityX;
  44078. return 0;
  44079. },
  44080. set: function (value) {
  44081. var pointers = this.inputs.attached["pointers"];
  44082. if (pointers) {
  44083. pointers.angularSensibilityX = value;
  44084. }
  44085. },
  44086. enumerable: true,
  44087. configurable: true
  44088. });
  44089. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44090. get: function () {
  44091. var pointers = this.inputs.attached["pointers"];
  44092. if (pointers)
  44093. return pointers.angularSensibilityY;
  44094. return 0;
  44095. },
  44096. set: function (value) {
  44097. var pointers = this.inputs.attached["pointers"];
  44098. if (pointers) {
  44099. pointers.angularSensibilityY = value;
  44100. }
  44101. },
  44102. enumerable: true,
  44103. configurable: true
  44104. });
  44105. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44106. get: function () {
  44107. var pointers = this.inputs.attached["pointers"];
  44108. if (pointers)
  44109. return pointers.pinchPrecision;
  44110. return 0;
  44111. },
  44112. set: function (value) {
  44113. var pointers = this.inputs.attached["pointers"];
  44114. if (pointers) {
  44115. pointers.pinchPrecision = value;
  44116. }
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44122. get: function () {
  44123. var pointers = this.inputs.attached["pointers"];
  44124. if (pointers)
  44125. return pointers.pinchDeltaPercentage;
  44126. return 0;
  44127. },
  44128. set: function (value) {
  44129. var pointers = this.inputs.attached["pointers"];
  44130. if (pointers) {
  44131. pointers.pinchDeltaPercentage = value;
  44132. }
  44133. },
  44134. enumerable: true,
  44135. configurable: true
  44136. });
  44137. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44138. get: function () {
  44139. var pointers = this.inputs.attached["pointers"];
  44140. if (pointers)
  44141. return pointers.panningSensibility;
  44142. return 0;
  44143. },
  44144. set: function (value) {
  44145. var pointers = this.inputs.attached["pointers"];
  44146. if (pointers) {
  44147. pointers.panningSensibility = value;
  44148. }
  44149. },
  44150. enumerable: true,
  44151. configurable: true
  44152. });
  44153. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44154. get: function () {
  44155. var keyboard = this.inputs.attached["keyboard"];
  44156. if (keyboard)
  44157. return keyboard.keysUp;
  44158. return [];
  44159. },
  44160. set: function (value) {
  44161. var keyboard = this.inputs.attached["keyboard"];
  44162. if (keyboard)
  44163. keyboard.keysUp = value;
  44164. },
  44165. enumerable: true,
  44166. configurable: true
  44167. });
  44168. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44169. get: function () {
  44170. var keyboard = this.inputs.attached["keyboard"];
  44171. if (keyboard)
  44172. return keyboard.keysDown;
  44173. return [];
  44174. },
  44175. set: function (value) {
  44176. var keyboard = this.inputs.attached["keyboard"];
  44177. if (keyboard)
  44178. keyboard.keysDown = value;
  44179. },
  44180. enumerable: true,
  44181. configurable: true
  44182. });
  44183. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44184. get: function () {
  44185. var keyboard = this.inputs.attached["keyboard"];
  44186. if (keyboard)
  44187. return keyboard.keysLeft;
  44188. return [];
  44189. },
  44190. set: function (value) {
  44191. var keyboard = this.inputs.attached["keyboard"];
  44192. if (keyboard)
  44193. keyboard.keysLeft = value;
  44194. },
  44195. enumerable: true,
  44196. configurable: true
  44197. });
  44198. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44199. get: function () {
  44200. var keyboard = this.inputs.attached["keyboard"];
  44201. if (keyboard)
  44202. return keyboard.keysRight;
  44203. return [];
  44204. },
  44205. set: function (value) {
  44206. var keyboard = this.inputs.attached["keyboard"];
  44207. if (keyboard)
  44208. keyboard.keysRight = value;
  44209. },
  44210. enumerable: true,
  44211. configurable: true
  44212. });
  44213. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44214. get: function () {
  44215. var mousewheel = this.inputs.attached["mousewheel"];
  44216. if (mousewheel)
  44217. return mousewheel.wheelPrecision;
  44218. return 0;
  44219. },
  44220. set: function (value) {
  44221. var mousewheel = this.inputs.attached["mousewheel"];
  44222. if (mousewheel)
  44223. mousewheel.wheelPrecision = value;
  44224. },
  44225. enumerable: true,
  44226. configurable: true
  44227. });
  44228. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44229. get: function () {
  44230. var mousewheel = this.inputs.attached["mousewheel"];
  44231. if (mousewheel)
  44232. return mousewheel.wheelDeltaPercentage;
  44233. return 0;
  44234. },
  44235. set: function (value) {
  44236. var mousewheel = this.inputs.attached["mousewheel"];
  44237. if (mousewheel)
  44238. mousewheel.wheelDeltaPercentage = value;
  44239. },
  44240. enumerable: true,
  44241. configurable: true
  44242. });
  44243. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44244. get: function () {
  44245. return this._bouncingBehavior;
  44246. },
  44247. enumerable: true,
  44248. configurable: true
  44249. });
  44250. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44251. get: function () {
  44252. return this._bouncingBehavior != null;
  44253. },
  44254. set: function (value) {
  44255. if (value === this.useBouncingBehavior) {
  44256. return;
  44257. }
  44258. if (value) {
  44259. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44260. this.addBehavior(this._bouncingBehavior);
  44261. }
  44262. else if (this._bouncingBehavior) {
  44263. this.removeBehavior(this._bouncingBehavior);
  44264. this._bouncingBehavior = null;
  44265. }
  44266. },
  44267. enumerable: true,
  44268. configurable: true
  44269. });
  44270. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44271. get: function () {
  44272. return this._framingBehavior;
  44273. },
  44274. enumerable: true,
  44275. configurable: true
  44276. });
  44277. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44278. get: function () {
  44279. return this._framingBehavior != null;
  44280. },
  44281. set: function (value) {
  44282. if (value === this.useFramingBehavior) {
  44283. return;
  44284. }
  44285. if (value) {
  44286. this._framingBehavior = new BABYLON.FramingBehavior();
  44287. this.addBehavior(this._framingBehavior);
  44288. }
  44289. else if (this._framingBehavior) {
  44290. this.removeBehavior(this._framingBehavior);
  44291. this._framingBehavior = null;
  44292. }
  44293. },
  44294. enumerable: true,
  44295. configurable: true
  44296. });
  44297. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44298. get: function () {
  44299. return this._autoRotationBehavior;
  44300. },
  44301. enumerable: true,
  44302. configurable: true
  44303. });
  44304. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44305. get: function () {
  44306. return this._autoRotationBehavior != null;
  44307. },
  44308. set: function (value) {
  44309. if (value === this.useAutoRotationBehavior) {
  44310. return;
  44311. }
  44312. if (value) {
  44313. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44314. this.addBehavior(this._autoRotationBehavior);
  44315. }
  44316. else if (this._autoRotationBehavior) {
  44317. this.removeBehavior(this._autoRotationBehavior);
  44318. this._autoRotationBehavior = null;
  44319. }
  44320. },
  44321. enumerable: true,
  44322. configurable: true
  44323. });
  44324. // Cache
  44325. ArcRotateCamera.prototype._initCache = function () {
  44326. _super.prototype._initCache.call(this);
  44327. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44328. this._cache.alpha = undefined;
  44329. this._cache.beta = undefined;
  44330. this._cache.radius = undefined;
  44331. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44332. };
  44333. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44334. if (!ignoreParentClass) {
  44335. _super.prototype._updateCache.call(this);
  44336. }
  44337. this._cache._target.copyFrom(this._getTargetPosition());
  44338. this._cache.alpha = this.alpha;
  44339. this._cache.beta = this.beta;
  44340. this._cache.radius = this.radius;
  44341. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44342. };
  44343. ArcRotateCamera.prototype._getTargetPosition = function () {
  44344. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44345. var pos = this._targetHost.getAbsolutePosition();
  44346. if (this._targetBoundingCenter) {
  44347. pos.addToRef(this._targetBoundingCenter, this._target);
  44348. }
  44349. else {
  44350. this._target.copyFrom(pos);
  44351. }
  44352. }
  44353. var lockedTargetPosition = this._getLockedTargetPosition();
  44354. if (lockedTargetPosition) {
  44355. return lockedTargetPosition;
  44356. }
  44357. return this._target;
  44358. };
  44359. ArcRotateCamera.prototype.storeState = function () {
  44360. this._storedAlpha = this.alpha;
  44361. this._storedBeta = this.beta;
  44362. this._storedRadius = this.radius;
  44363. this._storedTarget = this._getTargetPosition().clone();
  44364. return _super.prototype.storeState.call(this);
  44365. };
  44366. /**
  44367. * Restored camera state. You must call storeState() first
  44368. */
  44369. ArcRotateCamera.prototype._restoreStateValues = function () {
  44370. if (!_super.prototype._restoreStateValues.call(this)) {
  44371. return false;
  44372. }
  44373. this.alpha = this._storedAlpha;
  44374. this.beta = this._storedBeta;
  44375. this.radius = this._storedRadius;
  44376. this.setTarget(this._storedTarget.clone());
  44377. this.inertialAlphaOffset = 0;
  44378. this.inertialBetaOffset = 0;
  44379. this.inertialRadiusOffset = 0;
  44380. this.inertialPanningX = 0;
  44381. this.inertialPanningY = 0;
  44382. return true;
  44383. };
  44384. // Synchronized
  44385. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44386. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44387. return false;
  44388. return this._cache._target.equals(this._getTargetPosition())
  44389. && this._cache.alpha === this.alpha
  44390. && this._cache.beta === this.beta
  44391. && this._cache.radius === this.radius
  44392. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44393. };
  44394. // Methods
  44395. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44396. var _this = this;
  44397. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44398. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44399. this._useCtrlForPanning = useCtrlForPanning;
  44400. this._panningMouseButton = panningMouseButton;
  44401. this.inputs.attachElement(element, noPreventDefault);
  44402. this._reset = function () {
  44403. _this.inertialAlphaOffset = 0;
  44404. _this.inertialBetaOffset = 0;
  44405. _this.inertialRadiusOffset = 0;
  44406. _this.inertialPanningX = 0;
  44407. _this.inertialPanningY = 0;
  44408. };
  44409. };
  44410. ArcRotateCamera.prototype.detachControl = function (element) {
  44411. this.inputs.detachElement(element);
  44412. if (this._reset) {
  44413. this._reset();
  44414. }
  44415. };
  44416. ArcRotateCamera.prototype._checkInputs = function () {
  44417. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44418. if (this._collisionTriggered) {
  44419. return;
  44420. }
  44421. this.inputs.checkInputs();
  44422. // Inertia
  44423. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44424. if (this.getScene().useRightHandedSystem) {
  44425. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44426. }
  44427. else {
  44428. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44429. }
  44430. this.beta += this.inertialBetaOffset;
  44431. this.radius -= this.inertialRadiusOffset;
  44432. this.inertialAlphaOffset *= this.inertia;
  44433. this.inertialBetaOffset *= this.inertia;
  44434. this.inertialRadiusOffset *= this.inertia;
  44435. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44436. this.inertialAlphaOffset = 0;
  44437. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44438. this.inertialBetaOffset = 0;
  44439. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44440. this.inertialRadiusOffset = 0;
  44441. }
  44442. // Panning inertia
  44443. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44444. if (!this._localDirection) {
  44445. this._localDirection = BABYLON.Vector3.Zero();
  44446. this._transformedDirection = BABYLON.Vector3.Zero();
  44447. }
  44448. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44449. this._localDirection.multiplyInPlace(this.panningAxis);
  44450. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44451. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44452. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44453. if (!this.panningAxis.y) {
  44454. this._transformedDirection.y = 0;
  44455. }
  44456. if (!this._targetHost) {
  44457. if (this.panningDistanceLimit) {
  44458. this._transformedDirection.addInPlace(this._target);
  44459. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44460. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44461. this._target.copyFrom(this._transformedDirection);
  44462. }
  44463. }
  44464. else {
  44465. this._target.addInPlace(this._transformedDirection);
  44466. }
  44467. }
  44468. this.inertialPanningX *= this.panningInertia;
  44469. this.inertialPanningY *= this.panningInertia;
  44470. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44471. this.inertialPanningX = 0;
  44472. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44473. this.inertialPanningY = 0;
  44474. }
  44475. // Limits
  44476. this._checkLimits();
  44477. _super.prototype._checkInputs.call(this);
  44478. };
  44479. ArcRotateCamera.prototype._checkLimits = function () {
  44480. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44481. if (this.allowUpsideDown && this.beta > Math.PI) {
  44482. this.beta = this.beta - (2 * Math.PI);
  44483. }
  44484. }
  44485. else {
  44486. if (this.beta < this.lowerBetaLimit) {
  44487. this.beta = this.lowerBetaLimit;
  44488. }
  44489. }
  44490. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44491. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44492. this.beta = this.beta + (2 * Math.PI);
  44493. }
  44494. }
  44495. else {
  44496. if (this.beta > this.upperBetaLimit) {
  44497. this.beta = this.upperBetaLimit;
  44498. }
  44499. }
  44500. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44501. this.alpha = this.lowerAlphaLimit;
  44502. }
  44503. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44504. this.alpha = this.upperAlphaLimit;
  44505. }
  44506. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44507. this.radius = this.lowerRadiusLimit;
  44508. }
  44509. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44510. this.radius = this.upperRadiusLimit;
  44511. }
  44512. };
  44513. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44514. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44515. this.radius = radiusv3.length();
  44516. if (this.radius === 0) {
  44517. this.radius = 0.0001; // Just to avoid division by zero
  44518. }
  44519. // Alpha
  44520. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44521. if (radiusv3.z < 0) {
  44522. this.alpha = 2 * Math.PI - this.alpha;
  44523. }
  44524. // Beta
  44525. this.beta = Math.acos(radiusv3.y / this.radius);
  44526. this._checkLimits();
  44527. };
  44528. ArcRotateCamera.prototype.setPosition = function (position) {
  44529. if (this.position.equals(position)) {
  44530. return;
  44531. }
  44532. this.position.copyFrom(position);
  44533. this.rebuildAnglesAndRadius();
  44534. };
  44535. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44536. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44537. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44538. if (target.getBoundingInfo) {
  44539. if (toBoundingCenter) {
  44540. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44541. }
  44542. else {
  44543. this._targetBoundingCenter = null;
  44544. }
  44545. this._targetHost = target;
  44546. this._target = this._getTargetPosition();
  44547. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44548. }
  44549. else {
  44550. var newTarget = target;
  44551. var currentTarget = this._getTargetPosition();
  44552. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44553. return;
  44554. }
  44555. this._targetHost = null;
  44556. this._target = newTarget;
  44557. this._targetBoundingCenter = null;
  44558. this.onMeshTargetChangedObservable.notifyObservers(null);
  44559. }
  44560. this.rebuildAnglesAndRadius();
  44561. };
  44562. ArcRotateCamera.prototype._getViewMatrix = function () {
  44563. // Compute
  44564. var cosa = Math.cos(this.alpha);
  44565. var sina = Math.sin(this.alpha);
  44566. var cosb = Math.cos(this.beta);
  44567. var sinb = Math.sin(this.beta);
  44568. if (sinb === 0) {
  44569. sinb = 0.0001;
  44570. }
  44571. var target = this._getTargetPosition();
  44572. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44573. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44574. if (!this._collider) {
  44575. this._collider = new BABYLON.Collider();
  44576. }
  44577. this._collider._radius = this.collisionRadius;
  44578. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44579. this._collisionTriggered = true;
  44580. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44581. }
  44582. else {
  44583. this.position.copyFrom(this._newPosition);
  44584. var up = this.upVector;
  44585. if (this.allowUpsideDown && sinb < 0) {
  44586. up = up.clone();
  44587. up = up.negate();
  44588. }
  44589. if (this.getScene().useRightHandedSystem) {
  44590. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44591. }
  44592. else {
  44593. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44594. }
  44595. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44596. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44597. }
  44598. this._currentTarget = target;
  44599. return this._viewMatrix;
  44600. };
  44601. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44602. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44603. meshes = meshes || this.getScene().meshes;
  44604. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44605. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44606. this.radius = distance * this.zoomOnFactor;
  44607. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44608. };
  44609. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44610. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44611. var meshesOrMinMaxVector;
  44612. var distance;
  44613. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44614. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44615. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44616. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44617. }
  44618. else {
  44619. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44620. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44621. distance = minMaxVectorAndDistance.distance;
  44622. }
  44623. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44624. if (!doNotUpdateMaxZ) {
  44625. this.maxZ = distance * 2;
  44626. }
  44627. };
  44628. /**
  44629. * @override
  44630. * Override Camera.createRigCamera
  44631. */
  44632. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44633. var alphaShift = 0;
  44634. switch (this.cameraRigMode) {
  44635. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44638. case BABYLON.Camera.RIG_MODE_VR:
  44639. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44640. break;
  44641. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44642. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44643. break;
  44644. }
  44645. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44646. rigCam._cameraRigParams = {};
  44647. return rigCam;
  44648. };
  44649. /**
  44650. * @override
  44651. * Override Camera._updateRigCameras
  44652. */
  44653. ArcRotateCamera.prototype._updateRigCameras = function () {
  44654. var camLeft = this._rigCameras[0];
  44655. var camRight = this._rigCameras[1];
  44656. camLeft.beta = camRight.beta = this.beta;
  44657. camLeft.radius = camRight.radius = this.radius;
  44658. switch (this.cameraRigMode) {
  44659. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44662. case BABYLON.Camera.RIG_MODE_VR:
  44663. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44664. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44665. break;
  44666. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44667. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44668. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44669. break;
  44670. }
  44671. _super.prototype._updateRigCameras.call(this);
  44672. };
  44673. ArcRotateCamera.prototype.dispose = function () {
  44674. this.inputs.clear();
  44675. _super.prototype.dispose.call(this);
  44676. };
  44677. ArcRotateCamera.prototype.getClassName = function () {
  44678. return "ArcRotateCamera";
  44679. };
  44680. __decorate([
  44681. BABYLON.serialize()
  44682. ], ArcRotateCamera.prototype, "alpha", void 0);
  44683. __decorate([
  44684. BABYLON.serialize()
  44685. ], ArcRotateCamera.prototype, "beta", void 0);
  44686. __decorate([
  44687. BABYLON.serialize()
  44688. ], ArcRotateCamera.prototype, "radius", void 0);
  44689. __decorate([
  44690. BABYLON.serializeAsVector3("target")
  44691. ], ArcRotateCamera.prototype, "_target", void 0);
  44692. __decorate([
  44693. BABYLON.serialize()
  44694. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44695. __decorate([
  44696. BABYLON.serialize()
  44697. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44698. __decorate([
  44699. BABYLON.serialize()
  44700. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44701. __decorate([
  44702. BABYLON.serialize()
  44703. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44704. __decorate([
  44705. BABYLON.serialize()
  44706. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44707. __decorate([
  44708. BABYLON.serialize()
  44709. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44710. __decorate([
  44711. BABYLON.serialize()
  44712. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44713. __decorate([
  44714. BABYLON.serialize()
  44715. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44716. __decorate([
  44717. BABYLON.serialize()
  44718. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44719. __decorate([
  44720. BABYLON.serialize()
  44721. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44722. __decorate([
  44723. BABYLON.serialize()
  44724. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44725. __decorate([
  44726. BABYLON.serialize()
  44727. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44728. __decorate([
  44729. BABYLON.serialize()
  44730. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44731. __decorate([
  44732. BABYLON.serializeAsVector3()
  44733. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44734. __decorate([
  44735. BABYLON.serialize()
  44736. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44737. __decorate([
  44738. BABYLON.serialize()
  44739. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44740. __decorate([
  44741. BABYLON.serialize()
  44742. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44743. return ArcRotateCamera;
  44744. }(BABYLON.TargetCamera));
  44745. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44746. })(BABYLON || (BABYLON = {}));
  44747. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44748. var BABYLON;
  44749. (function (BABYLON) {
  44750. /**
  44751. * The HemisphericLight simulates the ambient environment light,
  44752. * so the passed direction is the light reflection direction, not the incoming direction.
  44753. */
  44754. var HemisphericLight = /** @class */ (function (_super) {
  44755. __extends(HemisphericLight, _super);
  44756. /**
  44757. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44758. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44759. * The HemisphericLight can't cast shadows.
  44760. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44761. * @param name The friendly name of the light
  44762. * @param direction The direction of the light reflection
  44763. * @param scene The scene the light belongs to
  44764. */
  44765. function HemisphericLight(name, direction, scene) {
  44766. var _this = _super.call(this, name, scene) || this;
  44767. /**
  44768. * The groundColor is the light in the opposite direction to the one specified during creation.
  44769. * 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.
  44770. */
  44771. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44772. _this.direction = direction || BABYLON.Vector3.Up();
  44773. return _this;
  44774. }
  44775. HemisphericLight.prototype._buildUniformLayout = function () {
  44776. this._uniformBuffer.addUniform("vLightData", 4);
  44777. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44778. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44779. this._uniformBuffer.addUniform("vLightGround", 3);
  44780. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44781. this._uniformBuffer.addUniform("depthValues", 2);
  44782. this._uniformBuffer.create();
  44783. };
  44784. /**
  44785. * Returns the string "HemisphericLight".
  44786. * @return The class name
  44787. */
  44788. HemisphericLight.prototype.getClassName = function () {
  44789. return "HemisphericLight";
  44790. };
  44791. /**
  44792. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44793. * Returns the updated direction.
  44794. * @param target The target the direction should point to
  44795. * @return The computed direction
  44796. */
  44797. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44798. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44799. return this.direction;
  44800. };
  44801. /**
  44802. * Returns the shadow generator associated to the light.
  44803. * @returns Always null for hemispheric lights because it does not support shadows.
  44804. */
  44805. HemisphericLight.prototype.getShadowGenerator = function () {
  44806. return null;
  44807. };
  44808. /**
  44809. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44810. * @param effect The effect to update
  44811. * @param lightIndex The index of the light in the effect to update
  44812. * @returns The hemispheric light
  44813. */
  44814. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44815. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44816. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44817. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44818. return this;
  44819. };
  44820. /**
  44821. * @ignore internal use only.
  44822. */
  44823. HemisphericLight.prototype._getWorldMatrix = function () {
  44824. if (!this._worldMatrix) {
  44825. this._worldMatrix = BABYLON.Matrix.Identity();
  44826. }
  44827. return this._worldMatrix;
  44828. };
  44829. /**
  44830. * Returns the integer 3.
  44831. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44832. */
  44833. HemisphericLight.prototype.getTypeID = function () {
  44834. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44835. };
  44836. __decorate([
  44837. BABYLON.serializeAsColor3()
  44838. ], HemisphericLight.prototype, "groundColor", void 0);
  44839. __decorate([
  44840. BABYLON.serializeAsVector3()
  44841. ], HemisphericLight.prototype, "direction", void 0);
  44842. return HemisphericLight;
  44843. }(BABYLON.Light));
  44844. BABYLON.HemisphericLight = HemisphericLight;
  44845. })(BABYLON || (BABYLON = {}));
  44846. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44847. var BABYLON;
  44848. (function (BABYLON) {
  44849. /**
  44850. * Base implementation of @see IShadowLight
  44851. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44852. */
  44853. var ShadowLight = /** @class */ (function (_super) {
  44854. __extends(ShadowLight, _super);
  44855. function ShadowLight() {
  44856. var _this = _super !== null && _super.apply(this, arguments) || this;
  44857. _this._needProjectionMatrixCompute = true;
  44858. return _this;
  44859. }
  44860. ShadowLight.prototype._setPosition = function (value) {
  44861. this._position = value;
  44862. };
  44863. Object.defineProperty(ShadowLight.prototype, "position", {
  44864. /**
  44865. * Sets the position the shadow will be casted from. Also use as the light position for both
  44866. * point and spot lights.
  44867. */
  44868. get: function () {
  44869. return this._position;
  44870. },
  44871. /**
  44872. * Sets the position the shadow will be casted from. Also use as the light position for both
  44873. * point and spot lights.
  44874. */
  44875. set: function (value) {
  44876. this._setPosition(value);
  44877. },
  44878. enumerable: true,
  44879. configurable: true
  44880. });
  44881. ShadowLight.prototype._setDirection = function (value) {
  44882. this._direction = value;
  44883. };
  44884. Object.defineProperty(ShadowLight.prototype, "direction", {
  44885. /**
  44886. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44887. * Also use as the light direction on spot and directional lights.
  44888. */
  44889. get: function () {
  44890. return this._direction;
  44891. },
  44892. /**
  44893. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44894. * Also use as the light direction on spot and directional lights.
  44895. */
  44896. set: function (value) {
  44897. this._setDirection(value);
  44898. },
  44899. enumerable: true,
  44900. configurable: true
  44901. });
  44902. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44903. /**
  44904. * Gets the shadow projection clipping minimum z value.
  44905. */
  44906. get: function () {
  44907. return this._shadowMinZ;
  44908. },
  44909. /**
  44910. * Sets the shadow projection clipping minimum z value.
  44911. */
  44912. set: function (value) {
  44913. this._shadowMinZ = value;
  44914. this.forceProjectionMatrixCompute();
  44915. },
  44916. enumerable: true,
  44917. configurable: true
  44918. });
  44919. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44920. /**
  44921. * Sets the shadow projection clipping maximum z value.
  44922. */
  44923. get: function () {
  44924. return this._shadowMaxZ;
  44925. },
  44926. /**
  44927. * Gets the shadow projection clipping maximum z value.
  44928. */
  44929. set: function (value) {
  44930. this._shadowMaxZ = value;
  44931. this.forceProjectionMatrixCompute();
  44932. },
  44933. enumerable: true,
  44934. configurable: true
  44935. });
  44936. /**
  44937. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44938. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44939. */
  44940. ShadowLight.prototype.computeTransformedInformation = function () {
  44941. if (this.parent && this.parent.getWorldMatrix) {
  44942. if (!this.transformedPosition) {
  44943. this.transformedPosition = BABYLON.Vector3.Zero();
  44944. }
  44945. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44946. // In case the direction is present.
  44947. if (this.direction) {
  44948. if (!this.transformedDirection) {
  44949. this.transformedDirection = BABYLON.Vector3.Zero();
  44950. }
  44951. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44952. }
  44953. return true;
  44954. }
  44955. return false;
  44956. };
  44957. /**
  44958. * Return the depth scale used for the shadow map.
  44959. * @returns the depth scale.
  44960. */
  44961. ShadowLight.prototype.getDepthScale = function () {
  44962. return 50.0;
  44963. };
  44964. /**
  44965. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44966. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44967. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44968. */
  44969. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44970. return this.transformedDirection ? this.transformedDirection : this.direction;
  44971. };
  44972. /**
  44973. * Returns the ShadowLight absolute position in the World.
  44974. * @returns the position vector in world space
  44975. */
  44976. ShadowLight.prototype.getAbsolutePosition = function () {
  44977. return this.transformedPosition ? this.transformedPosition : this.position;
  44978. };
  44979. /**
  44980. * Sets the ShadowLight direction toward the passed target.
  44981. * @param target The point tot target in local space
  44982. * @returns the updated ShadowLight direction
  44983. */
  44984. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44985. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44986. return this.direction;
  44987. };
  44988. /**
  44989. * Returns the light rotation in euler definition.
  44990. * @returns the x y z rotation in local space.
  44991. */
  44992. ShadowLight.prototype.getRotation = function () {
  44993. this.direction.normalize();
  44994. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44995. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44996. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44997. };
  44998. /**
  44999. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  45000. * @returns true if a cube texture needs to be use
  45001. */
  45002. ShadowLight.prototype.needCube = function () {
  45003. return false;
  45004. };
  45005. /**
  45006. * Detects if the projection matrix requires to be recomputed this frame.
  45007. * @returns true if it requires to be recomputed otherwise, false.
  45008. */
  45009. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  45010. return this._needProjectionMatrixCompute;
  45011. };
  45012. /**
  45013. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  45014. */
  45015. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  45016. this._needProjectionMatrixCompute = true;
  45017. };
  45018. /**
  45019. * Get the world matrix of the sahdow lights.
  45020. * @ignore Internal Use Only
  45021. */
  45022. ShadowLight.prototype._getWorldMatrix = function () {
  45023. if (!this._worldMatrix) {
  45024. this._worldMatrix = BABYLON.Matrix.Identity();
  45025. }
  45026. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  45027. return this._worldMatrix;
  45028. };
  45029. /**
  45030. * Gets the minZ used for shadow according to both the scene and the light.
  45031. * @param activeCamera The camera we are returning the min for
  45032. * @returns the depth min z
  45033. */
  45034. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  45035. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  45036. };
  45037. /**
  45038. * Gets the maxZ used for shadow according to both the scene and the light.
  45039. * @param activeCamera The camera we are returning the max for
  45040. * @returns the depth max z
  45041. */
  45042. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  45043. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  45044. };
  45045. /**
  45046. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  45047. * @param matrix The materix to updated with the projection information
  45048. * @param viewMatrix The transform matrix of the light
  45049. * @param renderList The list of mesh to render in the map
  45050. * @returns The current light
  45051. */
  45052. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45053. if (this.customProjectionMatrixBuilder) {
  45054. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  45055. }
  45056. else {
  45057. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45058. }
  45059. return this;
  45060. };
  45061. __decorate([
  45062. BABYLON.serializeAsVector3()
  45063. ], ShadowLight.prototype, "position", null);
  45064. __decorate([
  45065. BABYLON.serializeAsVector3()
  45066. ], ShadowLight.prototype, "direction", null);
  45067. __decorate([
  45068. BABYLON.serialize()
  45069. ], ShadowLight.prototype, "shadowMinZ", null);
  45070. __decorate([
  45071. BABYLON.serialize()
  45072. ], ShadowLight.prototype, "shadowMaxZ", null);
  45073. return ShadowLight;
  45074. }(BABYLON.Light));
  45075. BABYLON.ShadowLight = ShadowLight;
  45076. })(BABYLON || (BABYLON = {}));
  45077. //# sourceMappingURL=babylon.shadowLight.js.map
  45078. var BABYLON;
  45079. (function (BABYLON) {
  45080. /**
  45081. * A point light is a light defined by an unique point in world space.
  45082. * The light is emitted in every direction from this point.
  45083. * A good example of a point light is a standard light bulb.
  45084. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45085. */
  45086. var PointLight = /** @class */ (function (_super) {
  45087. __extends(PointLight, _super);
  45088. /**
  45089. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45090. * A PointLight emits the light in every direction.
  45091. * It can cast shadows.
  45092. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45093. * ```javascript
  45094. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45095. * ```
  45096. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45097. * @param name The light friendly name
  45098. * @param position The position of the point light in the scene
  45099. * @param scene The scene the lights belongs to
  45100. */
  45101. function PointLight(name, position, scene) {
  45102. var _this = _super.call(this, name, scene) || this;
  45103. _this._shadowAngle = Math.PI / 2;
  45104. _this.position = position;
  45105. return _this;
  45106. }
  45107. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45108. /**
  45109. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45110. * This specifies what angle the shadow will use to be created.
  45111. *
  45112. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45113. */
  45114. get: function () {
  45115. return this._shadowAngle;
  45116. },
  45117. /**
  45118. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45119. * This specifies what angle the shadow will use to be created.
  45120. *
  45121. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45122. */
  45123. set: function (value) {
  45124. this._shadowAngle = value;
  45125. this.forceProjectionMatrixCompute();
  45126. },
  45127. enumerable: true,
  45128. configurable: true
  45129. });
  45130. Object.defineProperty(PointLight.prototype, "direction", {
  45131. /**
  45132. * Gets the direction if it has been set.
  45133. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45134. */
  45135. get: function () {
  45136. return this._direction;
  45137. },
  45138. /**
  45139. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45140. */
  45141. set: function (value) {
  45142. var previousNeedCube = this.needCube();
  45143. this._direction = value;
  45144. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45145. this._shadowGenerator.recreateShadowMap();
  45146. }
  45147. },
  45148. enumerable: true,
  45149. configurable: true
  45150. });
  45151. /**
  45152. * Returns the string "PointLight"
  45153. * @returns the class name
  45154. */
  45155. PointLight.prototype.getClassName = function () {
  45156. return "PointLight";
  45157. };
  45158. /**
  45159. * Returns the integer 0.
  45160. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45161. */
  45162. PointLight.prototype.getTypeID = function () {
  45163. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45164. };
  45165. /**
  45166. * Specifies wether or not the shadowmap should be a cube texture.
  45167. * @returns true if the shadowmap needs to be a cube texture.
  45168. */
  45169. PointLight.prototype.needCube = function () {
  45170. return !this.direction;
  45171. };
  45172. /**
  45173. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45174. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45175. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45176. */
  45177. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45178. if (this.direction) {
  45179. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45180. }
  45181. else {
  45182. switch (faceIndex) {
  45183. case 0:
  45184. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45185. case 1:
  45186. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45187. case 2:
  45188. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45189. case 3:
  45190. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45191. case 4:
  45192. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45193. case 5:
  45194. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45195. }
  45196. }
  45197. return BABYLON.Vector3.Zero();
  45198. };
  45199. /**
  45200. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45201. * - fov = PI / 2
  45202. * - aspect ratio : 1.0
  45203. * - z-near and far equal to the active camera minZ and maxZ.
  45204. * Returns the PointLight.
  45205. */
  45206. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45207. var activeCamera = this.getScene().activeCamera;
  45208. if (!activeCamera) {
  45209. return;
  45210. }
  45211. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45212. };
  45213. PointLight.prototype._buildUniformLayout = function () {
  45214. this._uniformBuffer.addUniform("vLightData", 4);
  45215. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45216. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45217. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45218. this._uniformBuffer.addUniform("depthValues", 2);
  45219. this._uniformBuffer.create();
  45220. };
  45221. /**
  45222. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45223. * @param effect The effect to update
  45224. * @param lightIndex The index of the light in the effect to update
  45225. * @returns The point light
  45226. */
  45227. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45228. if (this.computeTransformedInformation()) {
  45229. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45230. return this;
  45231. }
  45232. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45233. return this;
  45234. };
  45235. __decorate([
  45236. BABYLON.serialize()
  45237. ], PointLight.prototype, "shadowAngle", null);
  45238. return PointLight;
  45239. }(BABYLON.ShadowLight));
  45240. BABYLON.PointLight = PointLight;
  45241. })(BABYLON || (BABYLON = {}));
  45242. //# sourceMappingURL=babylon.pointLight.js.map
  45243. var BABYLON;
  45244. (function (BABYLON) {
  45245. /**
  45246. * A directional light is defined by a direction (what a surprise!).
  45247. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45248. * 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.
  45249. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45250. */
  45251. var DirectionalLight = /** @class */ (function (_super) {
  45252. __extends(DirectionalLight, _super);
  45253. /**
  45254. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45255. * The directional light is emitted from everywhere in the given direction.
  45256. * It can cast shawdows.
  45257. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45258. * @param name The friendly name of the light
  45259. * @param direction The direction of the light
  45260. * @param scene The scene the light belongs to
  45261. */
  45262. function DirectionalLight(name, direction, scene) {
  45263. var _this = _super.call(this, name, scene) || this;
  45264. _this._shadowFrustumSize = 0;
  45265. _this._shadowOrthoScale = 0.5;
  45266. /**
  45267. * Automatically compute the projection matrix to best fit (including all the casters)
  45268. * on each frame.
  45269. */
  45270. _this.autoUpdateExtends = true;
  45271. // Cache
  45272. _this._orthoLeft = Number.MAX_VALUE;
  45273. _this._orthoRight = Number.MIN_VALUE;
  45274. _this._orthoTop = Number.MIN_VALUE;
  45275. _this._orthoBottom = Number.MAX_VALUE;
  45276. _this.position = direction.scale(-1.0);
  45277. _this.direction = direction;
  45278. return _this;
  45279. }
  45280. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45281. /**
  45282. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45283. */
  45284. get: function () {
  45285. return this._shadowFrustumSize;
  45286. },
  45287. /**
  45288. * Specifies a fix frustum size for the shadow generation.
  45289. */
  45290. set: function (value) {
  45291. this._shadowFrustumSize = value;
  45292. this.forceProjectionMatrixCompute();
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45298. /**
  45299. * Gets the shadow projection scale against the optimal computed one.
  45300. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45301. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45302. */
  45303. get: function () {
  45304. return this._shadowOrthoScale;
  45305. },
  45306. /**
  45307. * Sets the shadow projection scale against the optimal computed one.
  45308. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45309. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45310. */
  45311. set: function (value) {
  45312. this._shadowOrthoScale = value;
  45313. this.forceProjectionMatrixCompute();
  45314. },
  45315. enumerable: true,
  45316. configurable: true
  45317. });
  45318. /**
  45319. * Returns the string "DirectionalLight".
  45320. * @return The class name
  45321. */
  45322. DirectionalLight.prototype.getClassName = function () {
  45323. return "DirectionalLight";
  45324. };
  45325. /**
  45326. * Returns the integer 1.
  45327. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45328. */
  45329. DirectionalLight.prototype.getTypeID = function () {
  45330. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45331. };
  45332. /**
  45333. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45334. * Returns the DirectionalLight Shadow projection matrix.
  45335. */
  45336. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45337. if (this.shadowFrustumSize > 0) {
  45338. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45339. }
  45340. else {
  45341. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45342. }
  45343. };
  45344. /**
  45345. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45346. * Returns the DirectionalLight Shadow projection matrix.
  45347. */
  45348. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45349. var activeCamera = this.getScene().activeCamera;
  45350. if (!activeCamera) {
  45351. return;
  45352. }
  45353. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45354. };
  45355. /**
  45356. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45357. * Returns the DirectionalLight Shadow projection matrix.
  45358. */
  45359. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45360. var activeCamera = this.getScene().activeCamera;
  45361. if (!activeCamera) {
  45362. return;
  45363. }
  45364. // Check extends
  45365. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45366. var tempVector3 = BABYLON.Vector3.Zero();
  45367. this._orthoLeft = Number.MAX_VALUE;
  45368. this._orthoRight = Number.MIN_VALUE;
  45369. this._orthoTop = Number.MIN_VALUE;
  45370. this._orthoBottom = Number.MAX_VALUE;
  45371. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45372. var mesh = renderList[meshIndex];
  45373. if (!mesh) {
  45374. continue;
  45375. }
  45376. var boundingInfo = mesh.getBoundingInfo();
  45377. var boundingBox = boundingInfo.boundingBox;
  45378. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45379. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45380. if (tempVector3.x < this._orthoLeft)
  45381. this._orthoLeft = tempVector3.x;
  45382. if (tempVector3.y < this._orthoBottom)
  45383. this._orthoBottom = tempVector3.y;
  45384. if (tempVector3.x > this._orthoRight)
  45385. this._orthoRight = tempVector3.x;
  45386. if (tempVector3.y > this._orthoTop)
  45387. this._orthoTop = tempVector3.y;
  45388. }
  45389. }
  45390. }
  45391. var xOffset = this._orthoRight - this._orthoLeft;
  45392. var yOffset = this._orthoTop - this._orthoBottom;
  45393. 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);
  45394. };
  45395. DirectionalLight.prototype._buildUniformLayout = function () {
  45396. this._uniformBuffer.addUniform("vLightData", 4);
  45397. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45398. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45399. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45400. this._uniformBuffer.addUniform("depthValues", 2);
  45401. this._uniformBuffer.create();
  45402. };
  45403. /**
  45404. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45405. * @param effect The effect to update
  45406. * @param lightIndex The index of the light in the effect to update
  45407. * @returns The directional light
  45408. */
  45409. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45410. if (this.computeTransformedInformation()) {
  45411. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45412. return this;
  45413. }
  45414. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45415. return this;
  45416. };
  45417. /**
  45418. * Gets the minZ used for shadow according to both the scene and the light.
  45419. *
  45420. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45421. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45422. * @param activeCamera The camera we are returning the min for
  45423. * @returns the depth min z
  45424. */
  45425. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45426. return 1;
  45427. };
  45428. /**
  45429. * Gets the maxZ used for shadow according to both the scene and the light.
  45430. *
  45431. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45432. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45433. * @param activeCamera The camera we are returning the max for
  45434. * @returns the depth max z
  45435. */
  45436. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45437. return 1;
  45438. };
  45439. __decorate([
  45440. BABYLON.serialize()
  45441. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45442. __decorate([
  45443. BABYLON.serialize()
  45444. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45445. __decorate([
  45446. BABYLON.serialize()
  45447. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45448. return DirectionalLight;
  45449. }(BABYLON.ShadowLight));
  45450. BABYLON.DirectionalLight = DirectionalLight;
  45451. })(BABYLON || (BABYLON = {}));
  45452. //# sourceMappingURL=babylon.directionalLight.js.map
  45453. var BABYLON;
  45454. (function (BABYLON) {
  45455. /**
  45456. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45457. * These values define a cone of light starting from the position, emitting toward the direction.
  45458. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45459. * and the exponent defines the speed of the decay of the light with distance (reach).
  45460. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45461. */
  45462. var SpotLight = /** @class */ (function (_super) {
  45463. __extends(SpotLight, _super);
  45464. /**
  45465. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45466. * It can cast shadows.
  45467. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45468. * @param name The light friendly name
  45469. * @param position The position of the spot light in the scene
  45470. * @param direction The direction of the light in the scene
  45471. * @param angle The cone angle of the light in Radians
  45472. * @param exponent The light decay speed with the distance from the emission spot
  45473. * @param scene The scene the lights belongs to
  45474. */
  45475. function SpotLight(name, position, direction, angle, exponent, scene) {
  45476. var _this = _super.call(this, name, scene) || this;
  45477. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45478. _this._projectionTextureLightNear = 1e-6;
  45479. _this._projectionTextureLightFar = 1000.0;
  45480. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45481. _this._projectionTextureViewLightDirty = true;
  45482. _this._projectionTextureProjectionLightDirty = true;
  45483. _this._projectionTextureDirty = true;
  45484. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45485. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45486. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45487. _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);
  45488. _this.position = position;
  45489. _this.direction = direction;
  45490. _this.angle = angle;
  45491. _this.exponent = exponent;
  45492. return _this;
  45493. }
  45494. Object.defineProperty(SpotLight.prototype, "angle", {
  45495. /**
  45496. * Gets the cone angle of the spot light in Radians.
  45497. */
  45498. get: function () {
  45499. return this._angle;
  45500. },
  45501. /**
  45502. * Sets the cone angle of the spot light in Radians.
  45503. */
  45504. set: function (value) {
  45505. this._angle = value;
  45506. this._projectionTextureProjectionLightDirty = true;
  45507. this.forceProjectionMatrixCompute();
  45508. },
  45509. enumerable: true,
  45510. configurable: true
  45511. });
  45512. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45513. /**
  45514. * Allows scaling the angle of the light for shadow generation only.
  45515. */
  45516. get: function () {
  45517. return this._shadowAngleScale;
  45518. },
  45519. /**
  45520. * Allows scaling the angle of the light for shadow generation only.
  45521. */
  45522. set: function (value) {
  45523. this._shadowAngleScale = value;
  45524. this.forceProjectionMatrixCompute();
  45525. },
  45526. enumerable: true,
  45527. configurable: true
  45528. });
  45529. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45530. /**
  45531. * Allows reading the projecton texture
  45532. */
  45533. get: function () {
  45534. return this._projectionTextureMatrix;
  45535. },
  45536. enumerable: true,
  45537. configurable: true
  45538. });
  45539. ;
  45540. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45541. /**
  45542. * Gets the near clip of the Spotlight for texture projection.
  45543. */
  45544. get: function () {
  45545. return this._projectionTextureLightNear;
  45546. },
  45547. /**
  45548. * Sets the near clip of the Spotlight for texture projection.
  45549. */
  45550. set: function (value) {
  45551. this._projectionTextureLightNear = value;
  45552. this._projectionTextureProjectionLightDirty = true;
  45553. },
  45554. enumerable: true,
  45555. configurable: true
  45556. });
  45557. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45558. /**
  45559. * Gets the far clip of the Spotlight for texture projection.
  45560. */
  45561. get: function () {
  45562. return this._projectionTextureLightFar;
  45563. },
  45564. /**
  45565. * Sets the far clip of the Spotlight for texture projection.
  45566. */
  45567. set: function (value) {
  45568. this._projectionTextureLightFar = value;
  45569. this._projectionTextureProjectionLightDirty = true;
  45570. },
  45571. enumerable: true,
  45572. configurable: true
  45573. });
  45574. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45575. /**
  45576. * Gets the Up vector of the Spotlight for texture projection.
  45577. */
  45578. get: function () {
  45579. return this._projectionTextureUpDirection;
  45580. },
  45581. /**
  45582. * Sets the Up vector of the Spotlight for texture projection.
  45583. */
  45584. set: function (value) {
  45585. this._projectionTextureUpDirection = value;
  45586. this._projectionTextureProjectionLightDirty = true;
  45587. },
  45588. enumerable: true,
  45589. configurable: true
  45590. });
  45591. ;
  45592. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45593. /**
  45594. * Gets the projection texture of the light.
  45595. */
  45596. get: function () {
  45597. return this._projectionTexture;
  45598. },
  45599. /**
  45600. * Sets the projection texture of the light.
  45601. */
  45602. set: function (value) {
  45603. this._projectionTexture = value;
  45604. this._projectionTextureDirty = true;
  45605. },
  45606. enumerable: true,
  45607. configurable: true
  45608. });
  45609. /**
  45610. * Returns the string "SpotLight".
  45611. * @returns the class name
  45612. */
  45613. SpotLight.prototype.getClassName = function () {
  45614. return "SpotLight";
  45615. };
  45616. /**
  45617. * Returns the integer 2.
  45618. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45619. */
  45620. SpotLight.prototype.getTypeID = function () {
  45621. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45622. };
  45623. /**
  45624. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45625. */
  45626. SpotLight.prototype._setDirection = function (value) {
  45627. _super.prototype._setDirection.call(this, value);
  45628. this._projectionTextureViewLightDirty = true;
  45629. };
  45630. /**
  45631. * Overrides the position setter to recompute the projection texture view light Matrix.
  45632. */
  45633. SpotLight.prototype._setPosition = function (value) {
  45634. _super.prototype._setPosition.call(this, value);
  45635. this._projectionTextureViewLightDirty = true;
  45636. };
  45637. /**
  45638. * 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.
  45639. * Returns the SpotLight.
  45640. */
  45641. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45642. var activeCamera = this.getScene().activeCamera;
  45643. if (!activeCamera) {
  45644. return;
  45645. }
  45646. this._shadowAngleScale = this._shadowAngleScale || 1;
  45647. var angle = this._shadowAngleScale * this._angle;
  45648. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45649. };
  45650. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45651. this._projectionTextureViewLightDirty = false;
  45652. this._projectionTextureDirty = true;
  45653. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45654. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45655. };
  45656. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45657. this._projectionTextureProjectionLightDirty = false;
  45658. this._projectionTextureDirty = true;
  45659. var light_far = this.projectionTextureLightFar;
  45660. var light_near = this.projectionTextureLightNear;
  45661. var P = light_far / (light_far - light_near);
  45662. var Q = -P * light_near;
  45663. var S = 1.0 / Math.tan(this._angle / 2.0);
  45664. var A = 1.0;
  45665. 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);
  45666. };
  45667. /**
  45668. * Main function for light texture projection matrix computing.
  45669. */
  45670. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45671. this._projectionTextureDirty = false;
  45672. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45673. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45674. };
  45675. SpotLight.prototype._buildUniformLayout = function () {
  45676. this._uniformBuffer.addUniform("vLightData", 4);
  45677. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45678. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45679. this._uniformBuffer.addUniform("vLightDirection", 3);
  45680. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45681. this._uniformBuffer.addUniform("depthValues", 2);
  45682. this._uniformBuffer.create();
  45683. };
  45684. /**
  45685. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45686. * @param effect The effect to update
  45687. * @param lightIndex The index of the light in the effect to update
  45688. * @returns The spot light
  45689. */
  45690. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45691. var normalizeDirection;
  45692. if (this.computeTransformedInformation()) {
  45693. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45694. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45695. }
  45696. else {
  45697. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45698. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45699. }
  45700. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45701. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45702. if (this._projectionTextureViewLightDirty) {
  45703. this._computeProjectionTextureViewLightMatrix();
  45704. }
  45705. if (this._projectionTextureProjectionLightDirty) {
  45706. this._computeProjectionTextureProjectionLightMatrix();
  45707. }
  45708. if (this._projectionTextureDirty) {
  45709. this._computeProjectionTextureMatrix();
  45710. }
  45711. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45712. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45713. }
  45714. return this;
  45715. };
  45716. /**
  45717. * Disposes the light and the associated resources.
  45718. */
  45719. SpotLight.prototype.dispose = function () {
  45720. _super.prototype.dispose.call(this);
  45721. if (this._projectionTexture) {
  45722. this._projectionTexture.dispose();
  45723. }
  45724. };
  45725. __decorate([
  45726. BABYLON.serialize()
  45727. ], SpotLight.prototype, "angle", null);
  45728. __decorate([
  45729. BABYLON.serialize()
  45730. ], SpotLight.prototype, "shadowAngleScale", null);
  45731. __decorate([
  45732. BABYLON.serialize()
  45733. ], SpotLight.prototype, "exponent", void 0);
  45734. __decorate([
  45735. BABYLON.serialize()
  45736. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45737. __decorate([
  45738. BABYLON.serialize()
  45739. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45740. __decorate([
  45741. BABYLON.serialize()
  45742. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45743. __decorate([
  45744. BABYLON.serializeAsTexture("projectedLightTexture")
  45745. ], SpotLight.prototype, "_projectionTexture", void 0);
  45746. return SpotLight;
  45747. }(BABYLON.ShadowLight));
  45748. BABYLON.SpotLight = SpotLight;
  45749. })(BABYLON || (BABYLON = {}));
  45750. //# sourceMappingURL=babylon.spotLight.js.map
  45751. var BABYLON;
  45752. (function (BABYLON) {
  45753. var AnimationRange = /** @class */ (function () {
  45754. function AnimationRange(name, from, to) {
  45755. this.name = name;
  45756. this.from = from;
  45757. this.to = to;
  45758. }
  45759. AnimationRange.prototype.clone = function () {
  45760. return new AnimationRange(this.name, this.from, this.to);
  45761. };
  45762. return AnimationRange;
  45763. }());
  45764. BABYLON.AnimationRange = AnimationRange;
  45765. /**
  45766. * Composed of a frame, and an action function
  45767. */
  45768. var AnimationEvent = /** @class */ (function () {
  45769. function AnimationEvent(frame, action, onlyOnce) {
  45770. this.frame = frame;
  45771. this.action = action;
  45772. this.onlyOnce = onlyOnce;
  45773. this.isDone = false;
  45774. }
  45775. return AnimationEvent;
  45776. }());
  45777. BABYLON.AnimationEvent = AnimationEvent;
  45778. var PathCursor = /** @class */ (function () {
  45779. function PathCursor(path) {
  45780. this.path = path;
  45781. this._onchange = new Array();
  45782. this.value = 0;
  45783. this.animations = new Array();
  45784. }
  45785. PathCursor.prototype.getPoint = function () {
  45786. var point = this.path.getPointAtLengthPosition(this.value);
  45787. return new BABYLON.Vector3(point.x, 0, point.y);
  45788. };
  45789. PathCursor.prototype.moveAhead = function (step) {
  45790. if (step === void 0) { step = 0.002; }
  45791. this.move(step);
  45792. return this;
  45793. };
  45794. PathCursor.prototype.moveBack = function (step) {
  45795. if (step === void 0) { step = 0.002; }
  45796. this.move(-step);
  45797. return this;
  45798. };
  45799. PathCursor.prototype.move = function (step) {
  45800. if (Math.abs(step) > 1) {
  45801. throw "step size should be less than 1.";
  45802. }
  45803. this.value += step;
  45804. this.ensureLimits();
  45805. this.raiseOnChange();
  45806. return this;
  45807. };
  45808. PathCursor.prototype.ensureLimits = function () {
  45809. while (this.value > 1) {
  45810. this.value -= 1;
  45811. }
  45812. while (this.value < 0) {
  45813. this.value += 1;
  45814. }
  45815. return this;
  45816. };
  45817. // used by animation engine
  45818. PathCursor.prototype.raiseOnChange = function () {
  45819. var _this = this;
  45820. this._onchange.forEach(function (f) { return f(_this); });
  45821. return this;
  45822. };
  45823. PathCursor.prototype.onchange = function (f) {
  45824. this._onchange.push(f);
  45825. return this;
  45826. };
  45827. return PathCursor;
  45828. }());
  45829. BABYLON.PathCursor = PathCursor;
  45830. var AnimationKeyInterpolation;
  45831. (function (AnimationKeyInterpolation) {
  45832. /**
  45833. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45834. */
  45835. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45836. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45837. var Animation = /** @class */ (function () {
  45838. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45839. this.name = name;
  45840. this.targetProperty = targetProperty;
  45841. this.framePerSecond = framePerSecond;
  45842. this.dataType = dataType;
  45843. this.loopMode = loopMode;
  45844. this.enableBlending = enableBlending;
  45845. this._runtimeAnimations = new Array();
  45846. // The set of event that will be linked to this animation
  45847. this._events = new Array();
  45848. this.blendingSpeed = 0.01;
  45849. this._ranges = {};
  45850. this.targetPropertyPath = targetProperty.split(".");
  45851. this.dataType = dataType;
  45852. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45853. }
  45854. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45855. var dataType = undefined;
  45856. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45857. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45858. }
  45859. else if (from instanceof BABYLON.Quaternion) {
  45860. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45861. }
  45862. else if (from instanceof BABYLON.Vector3) {
  45863. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45864. }
  45865. else if (from instanceof BABYLON.Vector2) {
  45866. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45867. }
  45868. else if (from instanceof BABYLON.Color3) {
  45869. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45870. }
  45871. else if (from instanceof BABYLON.Size) {
  45872. dataType = Animation.ANIMATIONTYPE_SIZE;
  45873. }
  45874. if (dataType == undefined) {
  45875. return null;
  45876. }
  45877. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45878. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45879. animation.setKeys(keys);
  45880. if (easingFunction !== undefined) {
  45881. animation.setEasingFunction(easingFunction);
  45882. }
  45883. return animation;
  45884. };
  45885. /**
  45886. * Sets up an animation.
  45887. * @param property the property to animate
  45888. * @param animationType the animation type to apply
  45889. * @param easingFunction the easing function used in the animation
  45890. * @returns The created animation
  45891. */
  45892. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45893. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45894. animation.setEasingFunction(easingFunction);
  45895. return animation;
  45896. };
  45897. /**
  45898. * Create and start an animation on a node
  45899. * @param {string} name defines the name of the global animation that will be run on all nodes
  45900. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45901. * @param {string} targetProperty defines property to animate
  45902. * @param {number} framePerSecond defines the number of frame per second yo use
  45903. * @param {number} totalFrame defines the number of frames in total
  45904. * @param {any} from defines the initial value
  45905. * @param {any} to defines the final value
  45906. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45907. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45908. * @param onAnimationEnd defines the callback to call when animation end
  45909. * @returns the animatable created for this animation
  45910. */
  45911. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45912. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45913. if (!animation) {
  45914. return null;
  45915. }
  45916. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45917. };
  45918. /**
  45919. * Create and start an animation on a node and its descendants
  45920. * @param {string} name defines the name of the global animation that will be run on all nodes
  45921. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45922. * @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.
  45923. * @param {string} targetProperty defines property to animate
  45924. * @param {number} framePerSecond defines the number of frame per second yo use
  45925. * @param {number} totalFrame defines the number of frames in total
  45926. * @param {any} from defines the initial value
  45927. * @param {any} to defines the final value
  45928. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45929. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45930. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45931. * @returns the list of animatables created for all nodes
  45932. * @example https://www.babylonjs-playground.com/#MH0VLI
  45933. */
  45934. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45935. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45936. if (!animation) {
  45937. return null;
  45938. }
  45939. var scene = node.getScene();
  45940. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45941. };
  45942. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45943. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45944. if (!animation) {
  45945. return null;
  45946. }
  45947. node.animations.push(animation);
  45948. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45949. };
  45950. /**
  45951. * Transition property of the Camera to the target Value.
  45952. * @param property The property to transition
  45953. * @param targetValue The target Value of the property
  45954. * @param host The object where the property to animate belongs
  45955. * @param scene Scene used to run the animation
  45956. * @param frameRate Framerate (in frame/s) to use
  45957. * @param transition The transition type we want to use
  45958. * @param duration The duration of the animation, in milliseconds
  45959. * @param onAnimationEnd Call back trigger at the end of the animation.
  45960. */
  45961. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45962. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45963. if (duration <= 0) {
  45964. host[property] = targetValue;
  45965. if (onAnimationEnd) {
  45966. onAnimationEnd();
  45967. }
  45968. return null;
  45969. }
  45970. var endFrame = frameRate * (duration / 1000);
  45971. transition.setKeys([{
  45972. frame: 0,
  45973. value: host[property].clone ? host[property].clone() : host[property]
  45974. },
  45975. {
  45976. frame: endFrame,
  45977. value: targetValue
  45978. }]);
  45979. if (!host.animations) {
  45980. host.animations = [];
  45981. }
  45982. host.animations.push(transition);
  45983. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45984. animation.onAnimationEnd = onAnimationEnd;
  45985. return animation;
  45986. };
  45987. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45988. /**
  45989. * Return the array of runtime animations currently using this animation
  45990. */
  45991. get: function () {
  45992. return this._runtimeAnimations;
  45993. },
  45994. enumerable: true,
  45995. configurable: true
  45996. });
  45997. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45998. get: function () {
  45999. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  46000. var runtimeAnimation = _a[_i];
  46001. if (!runtimeAnimation.isStopped) {
  46002. return true;
  46003. }
  46004. }
  46005. return false;
  46006. },
  46007. enumerable: true,
  46008. configurable: true
  46009. });
  46010. // Methods
  46011. /**
  46012. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  46013. */
  46014. Animation.prototype.toString = function (fullDetails) {
  46015. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  46016. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  46017. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  46018. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  46019. if (fullDetails) {
  46020. ret += ", Ranges: {";
  46021. var first = true;
  46022. for (var name in this._ranges) {
  46023. if (first) {
  46024. ret += ", ";
  46025. first = false;
  46026. }
  46027. ret += name;
  46028. }
  46029. ret += "}";
  46030. }
  46031. return ret;
  46032. };
  46033. /**
  46034. * Add an event to this animation.
  46035. */
  46036. Animation.prototype.addEvent = function (event) {
  46037. this._events.push(event);
  46038. };
  46039. /**
  46040. * Remove all events found at the given frame
  46041. * @param frame
  46042. */
  46043. Animation.prototype.removeEvents = function (frame) {
  46044. for (var index = 0; index < this._events.length; index++) {
  46045. if (this._events[index].frame === frame) {
  46046. this._events.splice(index, 1);
  46047. index--;
  46048. }
  46049. }
  46050. };
  46051. Animation.prototype.getEvents = function () {
  46052. return this._events;
  46053. };
  46054. Animation.prototype.createRange = function (name, from, to) {
  46055. // check name not already in use; could happen for bones after serialized
  46056. if (!this._ranges[name]) {
  46057. this._ranges[name] = new AnimationRange(name, from, to);
  46058. }
  46059. };
  46060. Animation.prototype.deleteRange = function (name, deleteFrames) {
  46061. if (deleteFrames === void 0) { deleteFrames = true; }
  46062. var range = this._ranges[name];
  46063. if (!range) {
  46064. return;
  46065. }
  46066. if (deleteFrames) {
  46067. var from = range.from;
  46068. var to = range.to;
  46069. // this loop MUST go high to low for multiple splices to work
  46070. for (var key = this._keys.length - 1; key >= 0; key--) {
  46071. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  46072. this._keys.splice(key, 1);
  46073. }
  46074. }
  46075. }
  46076. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46077. };
  46078. Animation.prototype.getRange = function (name) {
  46079. return this._ranges[name];
  46080. };
  46081. Animation.prototype.getKeys = function () {
  46082. return this._keys;
  46083. };
  46084. Animation.prototype.getHighestFrame = function () {
  46085. var ret = 0;
  46086. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46087. if (ret < this._keys[key].frame) {
  46088. ret = this._keys[key].frame;
  46089. }
  46090. }
  46091. return ret;
  46092. };
  46093. Animation.prototype.getEasingFunction = function () {
  46094. return this._easingFunction;
  46095. };
  46096. Animation.prototype.setEasingFunction = function (easingFunction) {
  46097. this._easingFunction = easingFunction;
  46098. };
  46099. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46100. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46101. };
  46102. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46103. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46104. };
  46105. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46106. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46107. };
  46108. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46109. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46110. };
  46111. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46112. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46113. };
  46114. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46115. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46116. };
  46117. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46118. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46119. };
  46120. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46121. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46122. };
  46123. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46124. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46125. };
  46126. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46127. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46128. };
  46129. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46130. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46131. };
  46132. Animation.prototype.clone = function () {
  46133. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46134. clone.enableBlending = this.enableBlending;
  46135. clone.blendingSpeed = this.blendingSpeed;
  46136. if (this._keys) {
  46137. clone.setKeys(this._keys);
  46138. }
  46139. if (this._ranges) {
  46140. clone._ranges = {};
  46141. for (var name in this._ranges) {
  46142. var range = this._ranges[name];
  46143. if (!range) {
  46144. continue;
  46145. }
  46146. clone._ranges[name] = range.clone();
  46147. }
  46148. }
  46149. return clone;
  46150. };
  46151. Animation.prototype.setKeys = function (values) {
  46152. this._keys = values.slice(0);
  46153. };
  46154. Animation.prototype.serialize = function () {
  46155. var serializationObject = {};
  46156. serializationObject.name = this.name;
  46157. serializationObject.property = this.targetProperty;
  46158. serializationObject.framePerSecond = this.framePerSecond;
  46159. serializationObject.dataType = this.dataType;
  46160. serializationObject.loopBehavior = this.loopMode;
  46161. serializationObject.enableBlending = this.enableBlending;
  46162. serializationObject.blendingSpeed = this.blendingSpeed;
  46163. var dataType = this.dataType;
  46164. serializationObject.keys = [];
  46165. var keys = this.getKeys();
  46166. for (var index = 0; index < keys.length; index++) {
  46167. var animationKey = keys[index];
  46168. var key = {};
  46169. key.frame = animationKey.frame;
  46170. switch (dataType) {
  46171. case Animation.ANIMATIONTYPE_FLOAT:
  46172. key.values = [animationKey.value];
  46173. break;
  46174. case Animation.ANIMATIONTYPE_QUATERNION:
  46175. case Animation.ANIMATIONTYPE_MATRIX:
  46176. case Animation.ANIMATIONTYPE_VECTOR3:
  46177. case Animation.ANIMATIONTYPE_COLOR3:
  46178. key.values = animationKey.value.asArray();
  46179. break;
  46180. }
  46181. serializationObject.keys.push(key);
  46182. }
  46183. serializationObject.ranges = [];
  46184. for (var name in this._ranges) {
  46185. var source = this._ranges[name];
  46186. if (!source) {
  46187. continue;
  46188. }
  46189. var range = {};
  46190. range.name = name;
  46191. range.from = source.from;
  46192. range.to = source.to;
  46193. serializationObject.ranges.push(range);
  46194. }
  46195. return serializationObject;
  46196. };
  46197. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46198. get: function () {
  46199. return Animation._ANIMATIONTYPE_FLOAT;
  46200. },
  46201. enumerable: true,
  46202. configurable: true
  46203. });
  46204. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46205. get: function () {
  46206. return Animation._ANIMATIONTYPE_VECTOR3;
  46207. },
  46208. enumerable: true,
  46209. configurable: true
  46210. });
  46211. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46212. get: function () {
  46213. return Animation._ANIMATIONTYPE_VECTOR2;
  46214. },
  46215. enumerable: true,
  46216. configurable: true
  46217. });
  46218. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46219. get: function () {
  46220. return Animation._ANIMATIONTYPE_SIZE;
  46221. },
  46222. enumerable: true,
  46223. configurable: true
  46224. });
  46225. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46226. get: function () {
  46227. return Animation._ANIMATIONTYPE_QUATERNION;
  46228. },
  46229. enumerable: true,
  46230. configurable: true
  46231. });
  46232. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46233. get: function () {
  46234. return Animation._ANIMATIONTYPE_MATRIX;
  46235. },
  46236. enumerable: true,
  46237. configurable: true
  46238. });
  46239. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46240. get: function () {
  46241. return Animation._ANIMATIONTYPE_COLOR3;
  46242. },
  46243. enumerable: true,
  46244. configurable: true
  46245. });
  46246. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46247. get: function () {
  46248. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46249. },
  46250. enumerable: true,
  46251. configurable: true
  46252. });
  46253. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46254. get: function () {
  46255. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46256. },
  46257. enumerable: true,
  46258. configurable: true
  46259. });
  46260. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46261. get: function () {
  46262. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46263. },
  46264. enumerable: true,
  46265. configurable: true
  46266. });
  46267. Animation.Parse = function (parsedAnimation) {
  46268. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46269. var dataType = parsedAnimation.dataType;
  46270. var keys = [];
  46271. var data;
  46272. var index;
  46273. if (parsedAnimation.enableBlending) {
  46274. animation.enableBlending = parsedAnimation.enableBlending;
  46275. }
  46276. if (parsedAnimation.blendingSpeed) {
  46277. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46278. }
  46279. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46280. var key = parsedAnimation.keys[index];
  46281. var inTangent;
  46282. var outTangent;
  46283. switch (dataType) {
  46284. case Animation.ANIMATIONTYPE_FLOAT:
  46285. data = key.values[0];
  46286. if (key.values.length >= 1) {
  46287. inTangent = key.values[1];
  46288. }
  46289. if (key.values.length >= 2) {
  46290. outTangent = key.values[2];
  46291. }
  46292. break;
  46293. case Animation.ANIMATIONTYPE_QUATERNION:
  46294. data = BABYLON.Quaternion.FromArray(key.values);
  46295. if (key.values.length >= 8) {
  46296. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46297. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46298. inTangent = _inTangent;
  46299. }
  46300. }
  46301. if (key.values.length >= 12) {
  46302. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46303. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46304. outTangent = _outTangent;
  46305. }
  46306. }
  46307. break;
  46308. case Animation.ANIMATIONTYPE_MATRIX:
  46309. data = BABYLON.Matrix.FromArray(key.values);
  46310. break;
  46311. case Animation.ANIMATIONTYPE_COLOR3:
  46312. data = BABYLON.Color3.FromArray(key.values);
  46313. break;
  46314. case Animation.ANIMATIONTYPE_VECTOR3:
  46315. default:
  46316. data = BABYLON.Vector3.FromArray(key.values);
  46317. break;
  46318. }
  46319. var keyData = {};
  46320. keyData.frame = key.frame;
  46321. keyData.value = data;
  46322. if (inTangent != undefined) {
  46323. keyData.inTangent = inTangent;
  46324. }
  46325. if (outTangent != undefined) {
  46326. keyData.outTangent = outTangent;
  46327. }
  46328. keys.push(keyData);
  46329. }
  46330. animation.setKeys(keys);
  46331. if (parsedAnimation.ranges) {
  46332. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46333. data = parsedAnimation.ranges[index];
  46334. animation.createRange(data.name, data.from, data.to);
  46335. }
  46336. }
  46337. return animation;
  46338. };
  46339. Animation.AppendSerializedAnimations = function (source, destination) {
  46340. if (source.animations) {
  46341. destination.animations = [];
  46342. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46343. var animation = source.animations[animationIndex];
  46344. destination.animations.push(animation.serialize());
  46345. }
  46346. }
  46347. };
  46348. Animation.AllowMatricesInterpolation = false;
  46349. // Statics
  46350. Animation._ANIMATIONTYPE_FLOAT = 0;
  46351. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46352. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46353. Animation._ANIMATIONTYPE_MATRIX = 3;
  46354. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46355. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46356. Animation._ANIMATIONTYPE_SIZE = 6;
  46357. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46358. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46359. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46360. return Animation;
  46361. }());
  46362. BABYLON.Animation = Animation;
  46363. })(BABYLON || (BABYLON = {}));
  46364. //# sourceMappingURL=babylon.animation.js.map
  46365. var BABYLON;
  46366. (function (BABYLON) {
  46367. /**
  46368. * This class defines the direct association between an animation and a target
  46369. */
  46370. var TargetedAnimation = /** @class */ (function () {
  46371. function TargetedAnimation() {
  46372. }
  46373. return TargetedAnimation;
  46374. }());
  46375. BABYLON.TargetedAnimation = TargetedAnimation;
  46376. /**
  46377. * Use this class to create coordinated animations on multiple targets
  46378. */
  46379. var AnimationGroup = /** @class */ (function () {
  46380. function AnimationGroup(name, scene) {
  46381. if (scene === void 0) { scene = null; }
  46382. this.name = name;
  46383. this._targetedAnimations = new Array();
  46384. this._animatables = new Array();
  46385. this._from = Number.MAX_VALUE;
  46386. this._to = -Number.MAX_VALUE;
  46387. this._speedRatio = 1;
  46388. this.onAnimationEndObservable = new BABYLON.Observable();
  46389. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46390. this._scene.animationGroups.push(this);
  46391. }
  46392. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46393. /**
  46394. * Define if the animations are started
  46395. */
  46396. get: function () {
  46397. return this._isStarted;
  46398. },
  46399. enumerable: true,
  46400. configurable: true
  46401. });
  46402. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46403. /**
  46404. * Gets or sets the speed ratio to use for all animations
  46405. */
  46406. get: function () {
  46407. return this._speedRatio;
  46408. },
  46409. /**
  46410. * Gets or sets the speed ratio to use for all animations
  46411. */
  46412. set: function (value) {
  46413. if (this._speedRatio === value) {
  46414. return;
  46415. }
  46416. this._speedRatio = value;
  46417. for (var index = 0; index < this._animatables.length; index++) {
  46418. var animatable = this._animatables[index];
  46419. animatable.speedRatio = this._speedRatio;
  46420. }
  46421. },
  46422. enumerable: true,
  46423. configurable: true
  46424. });
  46425. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46426. /**
  46427. * Gets the targeted animations for this animation group
  46428. */
  46429. get: function () {
  46430. return this._targetedAnimations;
  46431. },
  46432. enumerable: true,
  46433. configurable: true
  46434. });
  46435. /**
  46436. * Add an animation (with its target) in the group
  46437. * @param animation defines the animation we want to add
  46438. * @param target defines the target of the animation
  46439. * @returns the {BABYLON.TargetedAnimation} object
  46440. */
  46441. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46442. var targetedAnimation = {
  46443. animation: animation,
  46444. target: target
  46445. };
  46446. var keys = animation.getKeys();
  46447. if (this._from > keys[0].frame) {
  46448. this._from = keys[0].frame;
  46449. }
  46450. if (this._to < keys[keys.length - 1].frame) {
  46451. this._to = keys[keys.length - 1].frame;
  46452. }
  46453. this._targetedAnimations.push(targetedAnimation);
  46454. return targetedAnimation;
  46455. };
  46456. /**
  46457. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46458. * It can add constant keys at begin or end
  46459. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46460. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46461. */
  46462. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46463. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46464. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46465. beginFrame = Math.max(beginFrame, this._from);
  46466. endFrame = Math.min(endFrame, this._to);
  46467. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46468. var targetedAnimation = this._targetedAnimations[index];
  46469. var keys = targetedAnimation.animation.getKeys();
  46470. var startKey = keys[0];
  46471. var endKey = keys[keys.length - 1];
  46472. if (startKey.frame > beginFrame) {
  46473. var newKey = {
  46474. frame: beginFrame,
  46475. value: startKey.value,
  46476. inTangent: startKey.inTangent,
  46477. outTangent: startKey.outTangent,
  46478. interpolation: startKey.interpolation
  46479. };
  46480. keys.splice(0, 0, newKey);
  46481. }
  46482. if (endKey.frame < endFrame) {
  46483. var newKey = {
  46484. frame: endFrame,
  46485. value: endKey.value,
  46486. inTangent: endKey.outTangent,
  46487. outTangent: endKey.outTangent,
  46488. interpolation: endKey.interpolation
  46489. };
  46490. keys.push(newKey);
  46491. }
  46492. }
  46493. return this;
  46494. };
  46495. /**
  46496. * Start all animations on given targets
  46497. * @param loop defines if animations must loop
  46498. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46499. */
  46500. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46501. var _this = this;
  46502. if (loop === void 0) { loop = false; }
  46503. if (speedRatio === void 0) { speedRatio = 1; }
  46504. if (this._isStarted || this._targetedAnimations.length === 0) {
  46505. return this;
  46506. }
  46507. var _loop_1 = function () {
  46508. var targetedAnimation = this_1._targetedAnimations[index];
  46509. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46510. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46511. }));
  46512. };
  46513. var this_1 = this;
  46514. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46515. _loop_1();
  46516. }
  46517. this._speedRatio = speedRatio;
  46518. this._isStarted = true;
  46519. return this;
  46520. };
  46521. /**
  46522. * Pause all animations
  46523. */
  46524. AnimationGroup.prototype.pause = function () {
  46525. if (!this._isStarted) {
  46526. return this;
  46527. }
  46528. for (var index = 0; index < this._animatables.length; index++) {
  46529. var animatable = this._animatables[index];
  46530. animatable.pause();
  46531. }
  46532. return this;
  46533. };
  46534. /**
  46535. * Play all animations to initial state
  46536. * This function will start() the animations if they were not started or will restart() them if they were paused
  46537. * @param loop defines if animations must loop
  46538. */
  46539. AnimationGroup.prototype.play = function (loop) {
  46540. if (this.isStarted) {
  46541. if (loop !== undefined) {
  46542. for (var index = 0; index < this._animatables.length; index++) {
  46543. var animatable = this._animatables[index];
  46544. animatable.loopAnimation = loop;
  46545. }
  46546. }
  46547. this.restart();
  46548. }
  46549. else {
  46550. this.start(loop, this._speedRatio);
  46551. }
  46552. return this;
  46553. };
  46554. /**
  46555. * Reset all animations to initial state
  46556. */
  46557. AnimationGroup.prototype.reset = function () {
  46558. if (!this._isStarted) {
  46559. return this;
  46560. }
  46561. for (var index = 0; index < this._animatables.length; index++) {
  46562. var animatable = this._animatables[index];
  46563. animatable.reset();
  46564. }
  46565. return this;
  46566. };
  46567. /**
  46568. * Restart animations from key 0
  46569. */
  46570. AnimationGroup.prototype.restart = function () {
  46571. if (!this._isStarted) {
  46572. return this;
  46573. }
  46574. for (var index = 0; index < this._animatables.length; index++) {
  46575. var animatable = this._animatables[index];
  46576. animatable.restart();
  46577. }
  46578. return this;
  46579. };
  46580. /**
  46581. * Stop all animations
  46582. */
  46583. AnimationGroup.prototype.stop = function () {
  46584. if (!this._isStarted) {
  46585. return this;
  46586. }
  46587. for (var index = 0; index < this._animatables.length; index++) {
  46588. var animatable = this._animatables[index];
  46589. animatable.stop();
  46590. }
  46591. this._isStarted = false;
  46592. return this;
  46593. };
  46594. /**
  46595. * Dispose all associated resources
  46596. */
  46597. AnimationGroup.prototype.dispose = function () {
  46598. this._targetedAnimations = [];
  46599. this._animatables = [];
  46600. var index = this._scene.animationGroups.indexOf(this);
  46601. if (index > -1) {
  46602. this._scene.animationGroups.splice(index, 1);
  46603. }
  46604. };
  46605. return AnimationGroup;
  46606. }());
  46607. BABYLON.AnimationGroup = AnimationGroup;
  46608. })(BABYLON || (BABYLON = {}));
  46609. //# sourceMappingURL=babylon.animationGroup.js.map
  46610. var BABYLON;
  46611. (function (BABYLON) {
  46612. var RuntimeAnimation = /** @class */ (function () {
  46613. function RuntimeAnimation(target, animation) {
  46614. this._offsetsCache = {};
  46615. this._highLimitsCache = {};
  46616. this._stopped = false;
  46617. this._blendingFactor = 0;
  46618. this._ratioOffset = 0;
  46619. this._animation = animation;
  46620. this._target = target;
  46621. animation._runtimeAnimations.push(this);
  46622. }
  46623. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46624. get: function () {
  46625. return this._animation;
  46626. },
  46627. enumerable: true,
  46628. configurable: true
  46629. });
  46630. RuntimeAnimation.prototype.reset = function () {
  46631. this._offsetsCache = {};
  46632. this._highLimitsCache = {};
  46633. this.currentFrame = 0;
  46634. this._blendingFactor = 0;
  46635. this._originalBlendValue = null;
  46636. };
  46637. RuntimeAnimation.prototype.isStopped = function () {
  46638. return this._stopped;
  46639. };
  46640. RuntimeAnimation.prototype.dispose = function () {
  46641. var index = this._animation.runtimeAnimations.indexOf(this);
  46642. if (index > -1) {
  46643. this._animation.runtimeAnimations.splice(index, 1);
  46644. }
  46645. };
  46646. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46647. if (typeof value === "function") {
  46648. return value();
  46649. }
  46650. return value;
  46651. };
  46652. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46653. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46654. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46655. }
  46656. this.currentFrame = currentFrame;
  46657. var keys = this._animation.getKeys();
  46658. // Try to get a hash to find the right key
  46659. 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));
  46660. if (keys[startKeyIndex].frame >= currentFrame) {
  46661. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46662. startKeyIndex--;
  46663. }
  46664. }
  46665. for (var key = startKeyIndex; key < keys.length; key++) {
  46666. var endKey = keys[key + 1];
  46667. if (endKey.frame >= currentFrame) {
  46668. var startKey = keys[key];
  46669. var startValue = this._getKeyValue(startKey.value);
  46670. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46671. return startValue;
  46672. }
  46673. var endValue = this._getKeyValue(endKey.value);
  46674. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46675. var frameDelta = endKey.frame - startKey.frame;
  46676. // gradient : percent of currentFrame between the frame inf and the frame sup
  46677. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46678. // check for easingFunction and correction of gradient
  46679. var easingFunction = this._animation.getEasingFunction();
  46680. if (easingFunction != null) {
  46681. gradient = easingFunction.ease(gradient);
  46682. }
  46683. switch (this._animation.dataType) {
  46684. // Float
  46685. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46686. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46687. switch (loopMode) {
  46688. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46689. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46690. return floatValue;
  46691. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46692. return offsetValue * repeatCount + floatValue;
  46693. }
  46694. break;
  46695. // Quaternion
  46696. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46697. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46698. switch (loopMode) {
  46699. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46700. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46701. return quatValue;
  46702. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46703. return quatValue.add(offsetValue.scale(repeatCount));
  46704. }
  46705. return quatValue;
  46706. // Vector3
  46707. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46708. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46709. switch (loopMode) {
  46710. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46711. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46712. return vec3Value;
  46713. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46714. return vec3Value.add(offsetValue.scale(repeatCount));
  46715. }
  46716. // Vector2
  46717. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46718. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46719. switch (loopMode) {
  46720. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46721. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46722. return vec2Value;
  46723. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46724. return vec2Value.add(offsetValue.scale(repeatCount));
  46725. }
  46726. // Size
  46727. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46728. switch (loopMode) {
  46729. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46730. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46731. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46732. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46733. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46734. }
  46735. // Color3
  46736. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46737. switch (loopMode) {
  46738. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46739. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46740. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46741. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46742. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46743. }
  46744. // Matrix
  46745. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46746. switch (loopMode) {
  46747. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46748. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46749. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46750. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46751. }
  46752. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46753. return startValue;
  46754. }
  46755. default:
  46756. break;
  46757. }
  46758. break;
  46759. }
  46760. }
  46761. return this._getKeyValue(keys[keys.length - 1].value);
  46762. };
  46763. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46764. if (blend === void 0) { blend = false; }
  46765. // Set value
  46766. var path;
  46767. var destination;
  46768. var targetPropertyPath = this._animation.targetPropertyPath;
  46769. if (targetPropertyPath.length > 1) {
  46770. var property = this._target[targetPropertyPath[0]];
  46771. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46772. property = property[targetPropertyPath[index]];
  46773. }
  46774. path = targetPropertyPath[targetPropertyPath.length - 1];
  46775. destination = property;
  46776. }
  46777. else {
  46778. path = targetPropertyPath[0];
  46779. destination = this._target;
  46780. }
  46781. // Blending
  46782. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46783. if (!this._originalBlendValue) {
  46784. if (destination[path].clone) {
  46785. this._originalBlendValue = destination[path].clone();
  46786. }
  46787. else {
  46788. this._originalBlendValue = destination[path];
  46789. }
  46790. }
  46791. if (this._originalBlendValue.prototype) {
  46792. if (this._originalBlendValue.prototype.Lerp) {
  46793. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46794. }
  46795. else {
  46796. destination[path] = currentValue;
  46797. }
  46798. }
  46799. else if (this._originalBlendValue.m) {
  46800. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46801. }
  46802. else {
  46803. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46804. }
  46805. this._blendingFactor += this._animation.blendingSpeed;
  46806. }
  46807. else {
  46808. destination[path] = currentValue;
  46809. }
  46810. if (this._target.markAsDirty) {
  46811. this._target.markAsDirty(this._animation.targetProperty);
  46812. }
  46813. };
  46814. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46815. var keys = this._animation.getKeys();
  46816. if (frame < keys[0].frame) {
  46817. frame = keys[0].frame;
  46818. }
  46819. else if (frame > keys[keys.length - 1].frame) {
  46820. frame = keys[keys.length - 1].frame;
  46821. }
  46822. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46823. this.setValue(currentValue);
  46824. };
  46825. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46826. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46827. this._ratioOffset = this._previousRatio - newRatio;
  46828. };
  46829. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46830. if (blend === void 0) { blend = false; }
  46831. var targetPropertyPath = this._animation.targetPropertyPath;
  46832. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46833. this._stopped = true;
  46834. return false;
  46835. }
  46836. var returnValue = true;
  46837. var keys = this._animation.getKeys();
  46838. // Adding a start key at frame 0 if missing
  46839. if (keys[0].frame !== 0) {
  46840. var newKey = { frame: 0, value: keys[0].value };
  46841. keys.splice(0, 0, newKey);
  46842. }
  46843. // Check limits
  46844. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46845. from = keys[0].frame;
  46846. }
  46847. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46848. to = keys[keys.length - 1].frame;
  46849. }
  46850. //to and from cannot be the same key
  46851. if (from === to) {
  46852. if (from > keys[0].frame) {
  46853. from--;
  46854. }
  46855. else if (to < keys[keys.length - 1].frame) {
  46856. to++;
  46857. }
  46858. }
  46859. // Compute ratio
  46860. var range = to - from;
  46861. var offsetValue;
  46862. // ratio represents the frame delta between from and to
  46863. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46864. var highLimitValue = 0;
  46865. this._previousDelay = delay;
  46866. this._previousRatio = ratio;
  46867. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46868. returnValue = false;
  46869. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46870. }
  46871. else {
  46872. // Get max value if required
  46873. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46874. var keyOffset = to.toString() + from.toString();
  46875. if (!this._offsetsCache[keyOffset]) {
  46876. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46877. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46878. switch (this._animation.dataType) {
  46879. // Float
  46880. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46881. this._offsetsCache[keyOffset] = toValue - fromValue;
  46882. break;
  46883. // Quaternion
  46884. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46885. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46886. break;
  46887. // Vector3
  46888. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46889. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46890. // Vector2
  46891. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46892. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46893. // Size
  46894. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46895. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46896. // Color3
  46897. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46898. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46899. default:
  46900. break;
  46901. }
  46902. this._highLimitsCache[keyOffset] = toValue;
  46903. }
  46904. highLimitValue = this._highLimitsCache[keyOffset];
  46905. offsetValue = this._offsetsCache[keyOffset];
  46906. }
  46907. }
  46908. if (offsetValue === undefined) {
  46909. switch (this._animation.dataType) {
  46910. // Float
  46911. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46912. offsetValue = 0;
  46913. break;
  46914. // Quaternion
  46915. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46916. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46917. break;
  46918. // Vector3
  46919. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46920. offsetValue = BABYLON.Vector3.Zero();
  46921. break;
  46922. // Vector2
  46923. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46924. offsetValue = BABYLON.Vector2.Zero();
  46925. break;
  46926. // Size
  46927. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46928. offsetValue = BABYLON.Size.Zero();
  46929. break;
  46930. // Color3
  46931. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46932. offsetValue = BABYLON.Color3.Black();
  46933. }
  46934. }
  46935. // Compute value
  46936. var repeatCount = (ratio / range) >> 0;
  46937. var currentFrame = returnValue ? from + ratio % range : to;
  46938. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46939. // Set value
  46940. this.setValue(currentValue);
  46941. // Check events
  46942. var events = this._animation.getEvents();
  46943. for (var index = 0; index < events.length; index++) {
  46944. // Make sure current frame has passed event frame and that event frame is within the current range
  46945. // Also, handle both forward and reverse animations
  46946. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46947. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46948. var event = events[index];
  46949. if (!event.isDone) {
  46950. // If event should be done only once, remove it.
  46951. if (event.onlyOnce) {
  46952. events.splice(index, 1);
  46953. index--;
  46954. }
  46955. event.isDone = true;
  46956. event.action();
  46957. } // Don't do anything if the event has already be done.
  46958. }
  46959. else if (events[index].isDone && !events[index].onlyOnce) {
  46960. // reset event, the animation is looping
  46961. events[index].isDone = false;
  46962. }
  46963. }
  46964. if (!returnValue) {
  46965. this._stopped = true;
  46966. }
  46967. return returnValue;
  46968. };
  46969. return RuntimeAnimation;
  46970. }());
  46971. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46972. })(BABYLON || (BABYLON = {}));
  46973. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46974. var BABYLON;
  46975. (function (BABYLON) {
  46976. var Animatable = /** @class */ (function () {
  46977. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46978. if (fromFrame === void 0) { fromFrame = 0; }
  46979. if (toFrame === void 0) { toFrame = 100; }
  46980. if (loopAnimation === void 0) { loopAnimation = false; }
  46981. if (speedRatio === void 0) { speedRatio = 1.0; }
  46982. this.target = target;
  46983. this.fromFrame = fromFrame;
  46984. this.toFrame = toFrame;
  46985. this.loopAnimation = loopAnimation;
  46986. this.onAnimationEnd = onAnimationEnd;
  46987. this._localDelayOffset = null;
  46988. this._pausedDelay = null;
  46989. this._runtimeAnimations = new Array();
  46990. this._paused = false;
  46991. this._speedRatio = 1;
  46992. this.animationStarted = false;
  46993. if (animations) {
  46994. this.appendAnimations(target, animations);
  46995. }
  46996. this._speedRatio = speedRatio;
  46997. this._scene = scene;
  46998. scene._activeAnimatables.push(this);
  46999. }
  47000. Object.defineProperty(Animatable.prototype, "speedRatio", {
  47001. get: function () {
  47002. return this._speedRatio;
  47003. },
  47004. set: function (value) {
  47005. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  47006. var animation = this._runtimeAnimations[index];
  47007. animation._prepareForSpeedRatioChange(value);
  47008. }
  47009. this._speedRatio = value;
  47010. },
  47011. enumerable: true,
  47012. configurable: true
  47013. });
  47014. // Methods
  47015. Animatable.prototype.getAnimations = function () {
  47016. return this._runtimeAnimations;
  47017. };
  47018. Animatable.prototype.appendAnimations = function (target, animations) {
  47019. for (var index = 0; index < animations.length; index++) {
  47020. var animation = animations[index];
  47021. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  47022. }
  47023. };
  47024. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  47025. var runtimeAnimations = this._runtimeAnimations;
  47026. for (var index = 0; index < runtimeAnimations.length; index++) {
  47027. if (runtimeAnimations[index].animation.targetProperty === property) {
  47028. return runtimeAnimations[index].animation;
  47029. }
  47030. }
  47031. return null;
  47032. };
  47033. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  47034. var runtimeAnimations = this._runtimeAnimations;
  47035. for (var index = 0; index < runtimeAnimations.length; index++) {
  47036. if (runtimeAnimations[index].animation.targetProperty === property) {
  47037. return runtimeAnimations[index];
  47038. }
  47039. }
  47040. return null;
  47041. };
  47042. Animatable.prototype.reset = function () {
  47043. var runtimeAnimations = this._runtimeAnimations;
  47044. for (var index = 0; index < runtimeAnimations.length; index++) {
  47045. runtimeAnimations[index].reset();
  47046. }
  47047. // Reset to original value
  47048. for (index = 0; index < runtimeAnimations.length; index++) {
  47049. var animation = runtimeAnimations[index];
  47050. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  47051. }
  47052. this._localDelayOffset = null;
  47053. this._pausedDelay = null;
  47054. };
  47055. Animatable.prototype.enableBlending = function (blendingSpeed) {
  47056. var runtimeAnimations = this._runtimeAnimations;
  47057. for (var index = 0; index < runtimeAnimations.length; index++) {
  47058. runtimeAnimations[index].animation.enableBlending = true;
  47059. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  47060. }
  47061. };
  47062. Animatable.prototype.disableBlending = function () {
  47063. var runtimeAnimations = this._runtimeAnimations;
  47064. for (var index = 0; index < runtimeAnimations.length; index++) {
  47065. runtimeAnimations[index].animation.enableBlending = false;
  47066. }
  47067. };
  47068. Animatable.prototype.goToFrame = function (frame) {
  47069. var runtimeAnimations = this._runtimeAnimations;
  47070. if (runtimeAnimations[0]) {
  47071. var fps = runtimeAnimations[0].animation.framePerSecond;
  47072. var currentFrame = runtimeAnimations[0].currentFrame;
  47073. var adjustTime = frame - currentFrame;
  47074. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  47075. if (this._localDelayOffset === null) {
  47076. this._localDelayOffset = 0;
  47077. }
  47078. this._localDelayOffset -= delay;
  47079. }
  47080. for (var index = 0; index < runtimeAnimations.length; index++) {
  47081. runtimeAnimations[index].goToFrame(frame);
  47082. }
  47083. };
  47084. Animatable.prototype.pause = function () {
  47085. if (this._paused) {
  47086. return;
  47087. }
  47088. this._paused = true;
  47089. };
  47090. Animatable.prototype.restart = function () {
  47091. this._paused = false;
  47092. };
  47093. Animatable.prototype.stop = function (animationName) {
  47094. if (animationName) {
  47095. var idx = this._scene._activeAnimatables.indexOf(this);
  47096. if (idx > -1) {
  47097. var runtimeAnimations = this._runtimeAnimations;
  47098. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47099. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47100. continue;
  47101. }
  47102. runtimeAnimations[index].dispose();
  47103. runtimeAnimations.splice(index, 1);
  47104. }
  47105. if (runtimeAnimations.length == 0) {
  47106. this._scene._activeAnimatables.splice(idx, 1);
  47107. if (this.onAnimationEnd) {
  47108. this.onAnimationEnd();
  47109. }
  47110. }
  47111. }
  47112. }
  47113. else {
  47114. var index = this._scene._activeAnimatables.indexOf(this);
  47115. if (index > -1) {
  47116. this._scene._activeAnimatables.splice(index, 1);
  47117. var runtimeAnimations = this._runtimeAnimations;
  47118. for (var index = 0; index < runtimeAnimations.length; index++) {
  47119. runtimeAnimations[index].dispose();
  47120. }
  47121. if (this.onAnimationEnd) {
  47122. this.onAnimationEnd();
  47123. }
  47124. }
  47125. }
  47126. };
  47127. Animatable.prototype._animate = function (delay) {
  47128. if (this._paused) {
  47129. this.animationStarted = false;
  47130. if (this._pausedDelay === null) {
  47131. this._pausedDelay = delay;
  47132. }
  47133. return true;
  47134. }
  47135. if (this._localDelayOffset === null) {
  47136. this._localDelayOffset = delay;
  47137. this._pausedDelay = null;
  47138. }
  47139. else if (this._pausedDelay !== null) {
  47140. this._localDelayOffset += delay - this._pausedDelay;
  47141. this._pausedDelay = null;
  47142. }
  47143. // Animating
  47144. var running = false;
  47145. var runtimeAnimations = this._runtimeAnimations;
  47146. var index;
  47147. for (index = 0; index < runtimeAnimations.length; index++) {
  47148. var animation = runtimeAnimations[index];
  47149. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47150. running = running || isRunning;
  47151. }
  47152. this.animationStarted = running;
  47153. if (!running) {
  47154. // Remove from active animatables
  47155. index = this._scene._activeAnimatables.indexOf(this);
  47156. this._scene._activeAnimatables.splice(index, 1);
  47157. // Dispose all runtime animations
  47158. for (index = 0; index < runtimeAnimations.length; index++) {
  47159. runtimeAnimations[index].dispose();
  47160. }
  47161. }
  47162. if (!running && this.onAnimationEnd) {
  47163. this.onAnimationEnd();
  47164. this.onAnimationEnd = null;
  47165. }
  47166. return running;
  47167. };
  47168. return Animatable;
  47169. }());
  47170. BABYLON.Animatable = Animatable;
  47171. })(BABYLON || (BABYLON = {}));
  47172. //# sourceMappingURL=babylon.animatable.js.map
  47173. var BABYLON;
  47174. (function (BABYLON) {
  47175. var EasingFunction = /** @class */ (function () {
  47176. function EasingFunction() {
  47177. // Properties
  47178. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47179. }
  47180. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47181. get: function () {
  47182. return EasingFunction._EASINGMODE_EASEIN;
  47183. },
  47184. enumerable: true,
  47185. configurable: true
  47186. });
  47187. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47188. get: function () {
  47189. return EasingFunction._EASINGMODE_EASEOUT;
  47190. },
  47191. enumerable: true,
  47192. configurable: true
  47193. });
  47194. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47195. get: function () {
  47196. return EasingFunction._EASINGMODE_EASEINOUT;
  47197. },
  47198. enumerable: true,
  47199. configurable: true
  47200. });
  47201. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47202. var n = Math.min(Math.max(easingMode, 0), 2);
  47203. this._easingMode = n;
  47204. };
  47205. EasingFunction.prototype.getEasingMode = function () {
  47206. return this._easingMode;
  47207. };
  47208. EasingFunction.prototype.easeInCore = function (gradient) {
  47209. throw new Error('You must implement this method');
  47210. };
  47211. EasingFunction.prototype.ease = function (gradient) {
  47212. switch (this._easingMode) {
  47213. case EasingFunction.EASINGMODE_EASEIN:
  47214. return this.easeInCore(gradient);
  47215. case EasingFunction.EASINGMODE_EASEOUT:
  47216. return (1 - this.easeInCore(1 - gradient));
  47217. }
  47218. if (gradient >= 0.5) {
  47219. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47220. }
  47221. return (this.easeInCore(gradient * 2) * 0.5);
  47222. };
  47223. //Statics
  47224. EasingFunction._EASINGMODE_EASEIN = 0;
  47225. EasingFunction._EASINGMODE_EASEOUT = 1;
  47226. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47227. return EasingFunction;
  47228. }());
  47229. BABYLON.EasingFunction = EasingFunction;
  47230. var CircleEase = /** @class */ (function (_super) {
  47231. __extends(CircleEase, _super);
  47232. function CircleEase() {
  47233. return _super !== null && _super.apply(this, arguments) || this;
  47234. }
  47235. CircleEase.prototype.easeInCore = function (gradient) {
  47236. gradient = Math.max(0, Math.min(1, gradient));
  47237. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47238. };
  47239. return CircleEase;
  47240. }(EasingFunction));
  47241. BABYLON.CircleEase = CircleEase;
  47242. var BackEase = /** @class */ (function (_super) {
  47243. __extends(BackEase, _super);
  47244. function BackEase(amplitude) {
  47245. if (amplitude === void 0) { amplitude = 1; }
  47246. var _this = _super.call(this) || this;
  47247. _this.amplitude = amplitude;
  47248. return _this;
  47249. }
  47250. BackEase.prototype.easeInCore = function (gradient) {
  47251. var num = Math.max(0, this.amplitude);
  47252. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47253. };
  47254. return BackEase;
  47255. }(EasingFunction));
  47256. BABYLON.BackEase = BackEase;
  47257. var BounceEase = /** @class */ (function (_super) {
  47258. __extends(BounceEase, _super);
  47259. function BounceEase(bounces, bounciness) {
  47260. if (bounces === void 0) { bounces = 3; }
  47261. if (bounciness === void 0) { bounciness = 2; }
  47262. var _this = _super.call(this) || this;
  47263. _this.bounces = bounces;
  47264. _this.bounciness = bounciness;
  47265. return _this;
  47266. }
  47267. BounceEase.prototype.easeInCore = function (gradient) {
  47268. var y = Math.max(0.0, this.bounces);
  47269. var bounciness = this.bounciness;
  47270. if (bounciness <= 1.0) {
  47271. bounciness = 1.001;
  47272. }
  47273. var num9 = Math.pow(bounciness, y);
  47274. var num5 = 1.0 - bounciness;
  47275. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47276. var num15 = gradient * num4;
  47277. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47278. var num3 = Math.floor(num65);
  47279. var num13 = num3 + 1.0;
  47280. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47281. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47282. var num7 = (num8 + num12) * 0.5;
  47283. var num6 = gradient - num7;
  47284. var num2 = num7 - num8;
  47285. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47286. };
  47287. return BounceEase;
  47288. }(EasingFunction));
  47289. BABYLON.BounceEase = BounceEase;
  47290. var CubicEase = /** @class */ (function (_super) {
  47291. __extends(CubicEase, _super);
  47292. function CubicEase() {
  47293. return _super !== null && _super.apply(this, arguments) || this;
  47294. }
  47295. CubicEase.prototype.easeInCore = function (gradient) {
  47296. return (gradient * gradient * gradient);
  47297. };
  47298. return CubicEase;
  47299. }(EasingFunction));
  47300. BABYLON.CubicEase = CubicEase;
  47301. var ElasticEase = /** @class */ (function (_super) {
  47302. __extends(ElasticEase, _super);
  47303. function ElasticEase(oscillations, springiness) {
  47304. if (oscillations === void 0) { oscillations = 3; }
  47305. if (springiness === void 0) { springiness = 3; }
  47306. var _this = _super.call(this) || this;
  47307. _this.oscillations = oscillations;
  47308. _this.springiness = springiness;
  47309. return _this;
  47310. }
  47311. ElasticEase.prototype.easeInCore = function (gradient) {
  47312. var num2;
  47313. var num3 = Math.max(0.0, this.oscillations);
  47314. var num = Math.max(0.0, this.springiness);
  47315. if (num == 0) {
  47316. num2 = gradient;
  47317. }
  47318. else {
  47319. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47320. }
  47321. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47322. };
  47323. return ElasticEase;
  47324. }(EasingFunction));
  47325. BABYLON.ElasticEase = ElasticEase;
  47326. var ExponentialEase = /** @class */ (function (_super) {
  47327. __extends(ExponentialEase, _super);
  47328. function ExponentialEase(exponent) {
  47329. if (exponent === void 0) { exponent = 2; }
  47330. var _this = _super.call(this) || this;
  47331. _this.exponent = exponent;
  47332. return _this;
  47333. }
  47334. ExponentialEase.prototype.easeInCore = function (gradient) {
  47335. if (this.exponent <= 0) {
  47336. return gradient;
  47337. }
  47338. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47339. };
  47340. return ExponentialEase;
  47341. }(EasingFunction));
  47342. BABYLON.ExponentialEase = ExponentialEase;
  47343. var PowerEase = /** @class */ (function (_super) {
  47344. __extends(PowerEase, _super);
  47345. function PowerEase(power) {
  47346. if (power === void 0) { power = 2; }
  47347. var _this = _super.call(this) || this;
  47348. _this.power = power;
  47349. return _this;
  47350. }
  47351. PowerEase.prototype.easeInCore = function (gradient) {
  47352. var y = Math.max(0.0, this.power);
  47353. return Math.pow(gradient, y);
  47354. };
  47355. return PowerEase;
  47356. }(EasingFunction));
  47357. BABYLON.PowerEase = PowerEase;
  47358. var QuadraticEase = /** @class */ (function (_super) {
  47359. __extends(QuadraticEase, _super);
  47360. function QuadraticEase() {
  47361. return _super !== null && _super.apply(this, arguments) || this;
  47362. }
  47363. QuadraticEase.prototype.easeInCore = function (gradient) {
  47364. return (gradient * gradient);
  47365. };
  47366. return QuadraticEase;
  47367. }(EasingFunction));
  47368. BABYLON.QuadraticEase = QuadraticEase;
  47369. var QuarticEase = /** @class */ (function (_super) {
  47370. __extends(QuarticEase, _super);
  47371. function QuarticEase() {
  47372. return _super !== null && _super.apply(this, arguments) || this;
  47373. }
  47374. QuarticEase.prototype.easeInCore = function (gradient) {
  47375. return (gradient * gradient * gradient * gradient);
  47376. };
  47377. return QuarticEase;
  47378. }(EasingFunction));
  47379. BABYLON.QuarticEase = QuarticEase;
  47380. var QuinticEase = /** @class */ (function (_super) {
  47381. __extends(QuinticEase, _super);
  47382. function QuinticEase() {
  47383. return _super !== null && _super.apply(this, arguments) || this;
  47384. }
  47385. QuinticEase.prototype.easeInCore = function (gradient) {
  47386. return (gradient * gradient * gradient * gradient * gradient);
  47387. };
  47388. return QuinticEase;
  47389. }(EasingFunction));
  47390. BABYLON.QuinticEase = QuinticEase;
  47391. var SineEase = /** @class */ (function (_super) {
  47392. __extends(SineEase, _super);
  47393. function SineEase() {
  47394. return _super !== null && _super.apply(this, arguments) || this;
  47395. }
  47396. SineEase.prototype.easeInCore = function (gradient) {
  47397. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47398. };
  47399. return SineEase;
  47400. }(EasingFunction));
  47401. BABYLON.SineEase = SineEase;
  47402. var BezierCurveEase = /** @class */ (function (_super) {
  47403. __extends(BezierCurveEase, _super);
  47404. function BezierCurveEase(x1, y1, x2, y2) {
  47405. if (x1 === void 0) { x1 = 0; }
  47406. if (y1 === void 0) { y1 = 0; }
  47407. if (x2 === void 0) { x2 = 1; }
  47408. if (y2 === void 0) { y2 = 1; }
  47409. var _this = _super.call(this) || this;
  47410. _this.x1 = x1;
  47411. _this.y1 = y1;
  47412. _this.x2 = x2;
  47413. _this.y2 = y2;
  47414. return _this;
  47415. }
  47416. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47417. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47418. };
  47419. return BezierCurveEase;
  47420. }(EasingFunction));
  47421. BABYLON.BezierCurveEase = BezierCurveEase;
  47422. })(BABYLON || (BABYLON = {}));
  47423. //# sourceMappingURL=babylon.easing.js.map
  47424. var BABYLON;
  47425. (function (BABYLON) {
  47426. var Condition = /** @class */ (function () {
  47427. function Condition(actionManager) {
  47428. this._actionManager = actionManager;
  47429. }
  47430. Condition.prototype.isValid = function () {
  47431. return true;
  47432. };
  47433. Condition.prototype._getProperty = function (propertyPath) {
  47434. return this._actionManager._getProperty(propertyPath);
  47435. };
  47436. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47437. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47438. };
  47439. Condition.prototype.serialize = function () {
  47440. };
  47441. Condition.prototype._serialize = function (serializedCondition) {
  47442. return {
  47443. type: 2,
  47444. children: [],
  47445. name: serializedCondition.name,
  47446. properties: serializedCondition.properties
  47447. };
  47448. };
  47449. return Condition;
  47450. }());
  47451. BABYLON.Condition = Condition;
  47452. var ValueCondition = /** @class */ (function (_super) {
  47453. __extends(ValueCondition, _super);
  47454. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47455. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47456. var _this = _super.call(this, actionManager) || this;
  47457. _this.propertyPath = propertyPath;
  47458. _this.value = value;
  47459. _this.operator = operator;
  47460. _this._target = target;
  47461. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47462. _this._property = _this._getProperty(_this.propertyPath);
  47463. return _this;
  47464. }
  47465. Object.defineProperty(ValueCondition, "IsEqual", {
  47466. get: function () {
  47467. return ValueCondition._IsEqual;
  47468. },
  47469. enumerable: true,
  47470. configurable: true
  47471. });
  47472. Object.defineProperty(ValueCondition, "IsDifferent", {
  47473. get: function () {
  47474. return ValueCondition._IsDifferent;
  47475. },
  47476. enumerable: true,
  47477. configurable: true
  47478. });
  47479. Object.defineProperty(ValueCondition, "IsGreater", {
  47480. get: function () {
  47481. return ValueCondition._IsGreater;
  47482. },
  47483. enumerable: true,
  47484. configurable: true
  47485. });
  47486. Object.defineProperty(ValueCondition, "IsLesser", {
  47487. get: function () {
  47488. return ValueCondition._IsLesser;
  47489. },
  47490. enumerable: true,
  47491. configurable: true
  47492. });
  47493. // Methods
  47494. ValueCondition.prototype.isValid = function () {
  47495. switch (this.operator) {
  47496. case ValueCondition.IsGreater:
  47497. return this._effectiveTarget[this._property] > this.value;
  47498. case ValueCondition.IsLesser:
  47499. return this._effectiveTarget[this._property] < this.value;
  47500. case ValueCondition.IsEqual:
  47501. case ValueCondition.IsDifferent:
  47502. var check;
  47503. if (this.value.equals) {
  47504. check = this.value.equals(this._effectiveTarget[this._property]);
  47505. }
  47506. else {
  47507. check = this.value === this._effectiveTarget[this._property];
  47508. }
  47509. return this.operator === ValueCondition.IsEqual ? check : !check;
  47510. }
  47511. return false;
  47512. };
  47513. ValueCondition.prototype.serialize = function () {
  47514. return this._serialize({
  47515. name: "ValueCondition",
  47516. properties: [
  47517. BABYLON.Action._GetTargetProperty(this._target),
  47518. { name: "propertyPath", value: this.propertyPath },
  47519. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47520. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47521. ]
  47522. });
  47523. };
  47524. ValueCondition.GetOperatorName = function (operator) {
  47525. switch (operator) {
  47526. case ValueCondition._IsEqual: return "IsEqual";
  47527. case ValueCondition._IsDifferent: return "IsDifferent";
  47528. case ValueCondition._IsGreater: return "IsGreater";
  47529. case ValueCondition._IsLesser: return "IsLesser";
  47530. default: return "";
  47531. }
  47532. };
  47533. // Statics
  47534. ValueCondition._IsEqual = 0;
  47535. ValueCondition._IsDifferent = 1;
  47536. ValueCondition._IsGreater = 2;
  47537. ValueCondition._IsLesser = 3;
  47538. return ValueCondition;
  47539. }(Condition));
  47540. BABYLON.ValueCondition = ValueCondition;
  47541. var PredicateCondition = /** @class */ (function (_super) {
  47542. __extends(PredicateCondition, _super);
  47543. function PredicateCondition(actionManager, predicate) {
  47544. var _this = _super.call(this, actionManager) || this;
  47545. _this.predicate = predicate;
  47546. return _this;
  47547. }
  47548. PredicateCondition.prototype.isValid = function () {
  47549. return this.predicate();
  47550. };
  47551. return PredicateCondition;
  47552. }(Condition));
  47553. BABYLON.PredicateCondition = PredicateCondition;
  47554. var StateCondition = /** @class */ (function (_super) {
  47555. __extends(StateCondition, _super);
  47556. function StateCondition(actionManager, target, value) {
  47557. var _this = _super.call(this, actionManager) || this;
  47558. _this.value = value;
  47559. _this._target = target;
  47560. return _this;
  47561. }
  47562. // Methods
  47563. StateCondition.prototype.isValid = function () {
  47564. return this._target.state === this.value;
  47565. };
  47566. StateCondition.prototype.serialize = function () {
  47567. return this._serialize({
  47568. name: "StateCondition",
  47569. properties: [
  47570. BABYLON.Action._GetTargetProperty(this._target),
  47571. { name: "value", value: this.value }
  47572. ]
  47573. });
  47574. };
  47575. return StateCondition;
  47576. }(Condition));
  47577. BABYLON.StateCondition = StateCondition;
  47578. })(BABYLON || (BABYLON = {}));
  47579. //# sourceMappingURL=babylon.condition.js.map
  47580. var BABYLON;
  47581. (function (BABYLON) {
  47582. var Action = /** @class */ (function () {
  47583. function Action(triggerOptions, condition) {
  47584. this.triggerOptions = triggerOptions;
  47585. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47586. if (triggerOptions.parameter) {
  47587. this.trigger = triggerOptions.trigger;
  47588. this._triggerParameter = triggerOptions.parameter;
  47589. }
  47590. else {
  47591. this.trigger = triggerOptions;
  47592. }
  47593. this._nextActiveAction = this;
  47594. this._condition = condition;
  47595. }
  47596. // Methods
  47597. Action.prototype._prepare = function () {
  47598. };
  47599. Action.prototype.getTriggerParameter = function () {
  47600. return this._triggerParameter;
  47601. };
  47602. Action.prototype._executeCurrent = function (evt) {
  47603. if (this._nextActiveAction._condition) {
  47604. var condition = this._nextActiveAction._condition;
  47605. var currentRenderId = this._actionManager.getScene().getRenderId();
  47606. // We cache the current evaluation for the current frame
  47607. if (condition._evaluationId === currentRenderId) {
  47608. if (!condition._currentResult) {
  47609. return;
  47610. }
  47611. }
  47612. else {
  47613. condition._evaluationId = currentRenderId;
  47614. if (!condition.isValid()) {
  47615. condition._currentResult = false;
  47616. return;
  47617. }
  47618. condition._currentResult = true;
  47619. }
  47620. }
  47621. this.onBeforeExecuteObservable.notifyObservers(this);
  47622. this._nextActiveAction.execute(evt);
  47623. this.skipToNextActiveAction();
  47624. };
  47625. Action.prototype.execute = function (evt) {
  47626. };
  47627. Action.prototype.skipToNextActiveAction = function () {
  47628. if (this._nextActiveAction._child) {
  47629. if (!this._nextActiveAction._child._actionManager) {
  47630. this._nextActiveAction._child._actionManager = this._actionManager;
  47631. }
  47632. this._nextActiveAction = this._nextActiveAction._child;
  47633. }
  47634. else {
  47635. this._nextActiveAction = this;
  47636. }
  47637. };
  47638. Action.prototype.then = function (action) {
  47639. this._child = action;
  47640. action._actionManager = this._actionManager;
  47641. action._prepare();
  47642. return action;
  47643. };
  47644. Action.prototype._getProperty = function (propertyPath) {
  47645. return this._actionManager._getProperty(propertyPath);
  47646. };
  47647. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47648. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47649. };
  47650. Action.prototype.serialize = function (parent) {
  47651. };
  47652. // Called by BABYLON.Action objects in serialize(...). Internal use
  47653. Action.prototype._serialize = function (serializedAction, parent) {
  47654. var serializationObject = {
  47655. type: 1,
  47656. children: [],
  47657. name: serializedAction.name,
  47658. properties: serializedAction.properties || []
  47659. };
  47660. // Serialize child
  47661. if (this._child) {
  47662. this._child.serialize(serializationObject);
  47663. }
  47664. // Check if "this" has a condition
  47665. if (this._condition) {
  47666. var serializedCondition = this._condition.serialize();
  47667. serializedCondition.children.push(serializationObject);
  47668. if (parent) {
  47669. parent.children.push(serializedCondition);
  47670. }
  47671. return serializedCondition;
  47672. }
  47673. if (parent) {
  47674. parent.children.push(serializationObject);
  47675. }
  47676. return serializationObject;
  47677. };
  47678. Action._SerializeValueAsString = function (value) {
  47679. if (typeof value === "number") {
  47680. return value.toString();
  47681. }
  47682. if (typeof value === "boolean") {
  47683. return value ? "true" : "false";
  47684. }
  47685. if (value instanceof BABYLON.Vector2) {
  47686. return value.x + ", " + value.y;
  47687. }
  47688. if (value instanceof BABYLON.Vector3) {
  47689. return value.x + ", " + value.y + ", " + value.z;
  47690. }
  47691. if (value instanceof BABYLON.Color3) {
  47692. return value.r + ", " + value.g + ", " + value.b;
  47693. }
  47694. if (value instanceof BABYLON.Color4) {
  47695. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47696. }
  47697. return value; // string
  47698. };
  47699. Action._GetTargetProperty = function (target) {
  47700. return {
  47701. name: "target",
  47702. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47703. : target instanceof BABYLON.Light ? "LightProperties"
  47704. : target instanceof BABYLON.Camera ? "CameraProperties"
  47705. : "SceneProperties",
  47706. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47707. };
  47708. };
  47709. return Action;
  47710. }());
  47711. BABYLON.Action = Action;
  47712. })(BABYLON || (BABYLON = {}));
  47713. //# sourceMappingURL=babylon.action.js.map
  47714. var BABYLON;
  47715. (function (BABYLON) {
  47716. /**
  47717. * ActionEvent is the event beint sent when an action is triggered.
  47718. */
  47719. var ActionEvent = /** @class */ (function () {
  47720. /**
  47721. * @param source The mesh or sprite that triggered the action.
  47722. * @param pointerX The X mouse cursor position at the time of the event
  47723. * @param pointerY The Y mouse cursor position at the time of the event
  47724. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47725. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47726. */
  47727. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47728. this.source = source;
  47729. this.pointerX = pointerX;
  47730. this.pointerY = pointerY;
  47731. this.meshUnderPointer = meshUnderPointer;
  47732. this.sourceEvent = sourceEvent;
  47733. this.additionalData = additionalData;
  47734. }
  47735. /**
  47736. * Helper function to auto-create an ActionEvent from a source mesh.
  47737. * @param source The source mesh that triggered the event
  47738. * @param evt {Event} The original (browser) event
  47739. */
  47740. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47741. var scene = source.getScene();
  47742. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47743. };
  47744. /**
  47745. * Helper function to auto-create an ActionEvent from a source mesh.
  47746. * @param source The source sprite that triggered the event
  47747. * @param scene Scene associated with the sprite
  47748. * @param evt {Event} The original (browser) event
  47749. */
  47750. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47751. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47752. };
  47753. /**
  47754. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47755. * @param scene the scene where the event occurred
  47756. * @param evt {Event} The original (browser) event
  47757. */
  47758. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47759. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47760. };
  47761. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47762. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47763. };
  47764. return ActionEvent;
  47765. }());
  47766. BABYLON.ActionEvent = ActionEvent;
  47767. /**
  47768. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47769. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47770. */
  47771. var ActionManager = /** @class */ (function () {
  47772. function ActionManager(scene) {
  47773. // Members
  47774. this.actions = new Array();
  47775. this.hoverCursor = '';
  47776. this._scene = scene;
  47777. scene._actionManagers.push(this);
  47778. }
  47779. Object.defineProperty(ActionManager, "NothingTrigger", {
  47780. get: function () {
  47781. return ActionManager._NothingTrigger;
  47782. },
  47783. enumerable: true,
  47784. configurable: true
  47785. });
  47786. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47787. get: function () {
  47788. return ActionManager._OnPickTrigger;
  47789. },
  47790. enumerable: true,
  47791. configurable: true
  47792. });
  47793. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47794. get: function () {
  47795. return ActionManager._OnLeftPickTrigger;
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47801. get: function () {
  47802. return ActionManager._OnRightPickTrigger;
  47803. },
  47804. enumerable: true,
  47805. configurable: true
  47806. });
  47807. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47808. get: function () {
  47809. return ActionManager._OnCenterPickTrigger;
  47810. },
  47811. enumerable: true,
  47812. configurable: true
  47813. });
  47814. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47815. get: function () {
  47816. return ActionManager._OnPickDownTrigger;
  47817. },
  47818. enumerable: true,
  47819. configurable: true
  47820. });
  47821. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47822. get: function () {
  47823. return ActionManager._OnDoublePickTrigger;
  47824. },
  47825. enumerable: true,
  47826. configurable: true
  47827. });
  47828. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47829. get: function () {
  47830. return ActionManager._OnPickUpTrigger;
  47831. },
  47832. enumerable: true,
  47833. configurable: true
  47834. });
  47835. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47836. /// This trigger will only be raised if you also declared a OnPickDown
  47837. get: function () {
  47838. return ActionManager._OnPickOutTrigger;
  47839. },
  47840. enumerable: true,
  47841. configurable: true
  47842. });
  47843. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47844. get: function () {
  47845. return ActionManager._OnLongPressTrigger;
  47846. },
  47847. enumerable: true,
  47848. configurable: true
  47849. });
  47850. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47851. get: function () {
  47852. return ActionManager._OnPointerOverTrigger;
  47853. },
  47854. enumerable: true,
  47855. configurable: true
  47856. });
  47857. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47858. get: function () {
  47859. return ActionManager._OnPointerOutTrigger;
  47860. },
  47861. enumerable: true,
  47862. configurable: true
  47863. });
  47864. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47865. get: function () {
  47866. return ActionManager._OnEveryFrameTrigger;
  47867. },
  47868. enumerable: true,
  47869. configurable: true
  47870. });
  47871. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47872. get: function () {
  47873. return ActionManager._OnIntersectionEnterTrigger;
  47874. },
  47875. enumerable: true,
  47876. configurable: true
  47877. });
  47878. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47879. get: function () {
  47880. return ActionManager._OnIntersectionExitTrigger;
  47881. },
  47882. enumerable: true,
  47883. configurable: true
  47884. });
  47885. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47886. get: function () {
  47887. return ActionManager._OnKeyDownTrigger;
  47888. },
  47889. enumerable: true,
  47890. configurable: true
  47891. });
  47892. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47893. get: function () {
  47894. return ActionManager._OnKeyUpTrigger;
  47895. },
  47896. enumerable: true,
  47897. configurable: true
  47898. });
  47899. // Methods
  47900. ActionManager.prototype.dispose = function () {
  47901. var index = this._scene._actionManagers.indexOf(this);
  47902. for (var i = 0; i < this.actions.length; i++) {
  47903. var action = this.actions[i];
  47904. ActionManager.Triggers[action.trigger]--;
  47905. if (ActionManager.Triggers[action.trigger] === 0) {
  47906. delete ActionManager.Triggers[action.trigger];
  47907. }
  47908. }
  47909. if (index > -1) {
  47910. this._scene._actionManagers.splice(index, 1);
  47911. }
  47912. };
  47913. ActionManager.prototype.getScene = function () {
  47914. return this._scene;
  47915. };
  47916. /**
  47917. * Does this action manager handles actions of any of the given triggers
  47918. * @param {number[]} triggers - the triggers to be tested
  47919. * @return {boolean} whether one (or more) of the triggers is handeled
  47920. */
  47921. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47922. for (var index = 0; index < this.actions.length; index++) {
  47923. var action = this.actions[index];
  47924. if (triggers.indexOf(action.trigger) > -1) {
  47925. return true;
  47926. }
  47927. }
  47928. return false;
  47929. };
  47930. /**
  47931. * Does this action manager handles actions of a given trigger
  47932. * @param {number} trigger - the trigger to be tested
  47933. * @return {boolean} whether the trigger is handeled
  47934. */
  47935. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47936. for (var index = 0; index < this.actions.length; index++) {
  47937. var action = this.actions[index];
  47938. if (action.trigger === trigger) {
  47939. return true;
  47940. }
  47941. }
  47942. return false;
  47943. };
  47944. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47945. /**
  47946. * Does this action manager has pointer triggers
  47947. * @return {boolean} whether or not it has pointer triggers
  47948. */
  47949. get: function () {
  47950. for (var index = 0; index < this.actions.length; index++) {
  47951. var action = this.actions[index];
  47952. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47953. return true;
  47954. }
  47955. }
  47956. return false;
  47957. },
  47958. enumerable: true,
  47959. configurable: true
  47960. });
  47961. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47962. /**
  47963. * Does this action manager has pick triggers
  47964. * @return {boolean} whether or not it has pick triggers
  47965. */
  47966. get: function () {
  47967. for (var index = 0; index < this.actions.length; index++) {
  47968. var action = this.actions[index];
  47969. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47970. return true;
  47971. }
  47972. }
  47973. return false;
  47974. },
  47975. enumerable: true,
  47976. configurable: true
  47977. });
  47978. Object.defineProperty(ActionManager, "HasTriggers", {
  47979. /**
  47980. * Does exist one action manager with at least one trigger
  47981. * @return {boolean} whether or not it exists one action manager with one trigger
  47982. **/
  47983. get: function () {
  47984. for (var t in ActionManager.Triggers) {
  47985. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47986. return true;
  47987. }
  47988. }
  47989. return false;
  47990. },
  47991. enumerable: true,
  47992. configurable: true
  47993. });
  47994. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47995. /**
  47996. * Does exist one action manager with at least one pick trigger
  47997. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47998. **/
  47999. get: function () {
  48000. for (var t in ActionManager.Triggers) {
  48001. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48002. var t_int = parseInt(t);
  48003. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  48004. return true;
  48005. }
  48006. }
  48007. }
  48008. return false;
  48009. },
  48010. enumerable: true,
  48011. configurable: true
  48012. });
  48013. /**
  48014. * Does exist one action manager that handles actions of a given trigger
  48015. * @param {number} trigger - the trigger to be tested
  48016. * @return {boolean} whether the trigger is handeled by at least one action manager
  48017. **/
  48018. ActionManager.HasSpecificTrigger = function (trigger) {
  48019. for (var t in ActionManager.Triggers) {
  48020. if (ActionManager.Triggers.hasOwnProperty(t)) {
  48021. var t_int = parseInt(t);
  48022. if (t_int === trigger) {
  48023. return true;
  48024. }
  48025. }
  48026. }
  48027. return false;
  48028. };
  48029. /**
  48030. * Registers an action to this action manager
  48031. * @param {BABYLON.Action} action - the action to be registered
  48032. * @return {BABYLON.Action} the action amended (prepared) after registration
  48033. */
  48034. ActionManager.prototype.registerAction = function (action) {
  48035. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  48036. if (this.getScene().actionManager !== this) {
  48037. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  48038. return null;
  48039. }
  48040. }
  48041. this.actions.push(action);
  48042. if (ActionManager.Triggers[action.trigger]) {
  48043. ActionManager.Triggers[action.trigger]++;
  48044. }
  48045. else {
  48046. ActionManager.Triggers[action.trigger] = 1;
  48047. }
  48048. action._actionManager = this;
  48049. action._prepare();
  48050. return action;
  48051. };
  48052. /**
  48053. * Unregisters an action to this action manager
  48054. * @param action The action to be unregistered
  48055. * @return whether the action has been unregistered
  48056. */
  48057. ActionManager.prototype.unregisterAction = function (action) {
  48058. var index = this.actions.indexOf(action);
  48059. if (index !== -1) {
  48060. this.actions.splice(index, 1);
  48061. ActionManager.Triggers[action.trigger] -= 1;
  48062. if (ActionManager.Triggers[action.trigger] === 0) {
  48063. delete ActionManager.Triggers[action.trigger];
  48064. }
  48065. delete action._actionManager;
  48066. return true;
  48067. }
  48068. return false;
  48069. };
  48070. /**
  48071. * Process a specific trigger
  48072. * @param {number} trigger - the trigger to process
  48073. * @param evt {BABYLON.ActionEvent} the event details to be processed
  48074. */
  48075. ActionManager.prototype.processTrigger = function (trigger, evt) {
  48076. for (var index = 0; index < this.actions.length; index++) {
  48077. var action = this.actions[index];
  48078. if (action.trigger === trigger) {
  48079. if (evt) {
  48080. if (trigger === ActionManager.OnKeyUpTrigger
  48081. || trigger === ActionManager.OnKeyDownTrigger) {
  48082. var parameter = action.getTriggerParameter();
  48083. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48084. if (!parameter.toLowerCase) {
  48085. continue;
  48086. }
  48087. var lowerCase = parameter.toLowerCase();
  48088. if (lowerCase !== evt.sourceEvent.key) {
  48089. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48090. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48091. if (actualkey !== lowerCase) {
  48092. continue;
  48093. }
  48094. }
  48095. }
  48096. }
  48097. }
  48098. action._executeCurrent(evt);
  48099. }
  48100. }
  48101. };
  48102. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48103. var properties = propertyPath.split(".");
  48104. for (var index = 0; index < properties.length - 1; index++) {
  48105. target = target[properties[index]];
  48106. }
  48107. return target;
  48108. };
  48109. ActionManager.prototype._getProperty = function (propertyPath) {
  48110. var properties = propertyPath.split(".");
  48111. return properties[properties.length - 1];
  48112. };
  48113. ActionManager.prototype.serialize = function (name) {
  48114. var root = {
  48115. children: new Array(),
  48116. name: name,
  48117. type: 3,
  48118. properties: new Array() // Empty for root but required
  48119. };
  48120. for (var i = 0; i < this.actions.length; i++) {
  48121. var triggerObject = {
  48122. type: 0,
  48123. children: new Array(),
  48124. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48125. properties: new Array()
  48126. };
  48127. var triggerOptions = this.actions[i].triggerOptions;
  48128. if (triggerOptions && typeof triggerOptions !== "number") {
  48129. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48130. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48131. }
  48132. else {
  48133. var parameter = {};
  48134. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48135. if (triggerOptions.parameter.mesh) {
  48136. parameter._meshId = triggerOptions.parameter.mesh.id;
  48137. }
  48138. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48139. }
  48140. }
  48141. // Serialize child action, recursively
  48142. this.actions[i].serialize(triggerObject);
  48143. // Add serialized trigger
  48144. root.children.push(triggerObject);
  48145. }
  48146. return root;
  48147. };
  48148. ActionManager.Parse = function (parsedActions, object, scene) {
  48149. var actionManager = new ActionManager(scene);
  48150. if (object === null)
  48151. scene.actionManager = actionManager;
  48152. else
  48153. object.actionManager = actionManager;
  48154. // instanciate a new object
  48155. var instanciate = function (name, params) {
  48156. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48157. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48158. newInstance.constructor.apply(newInstance, params);
  48159. return newInstance;
  48160. };
  48161. var parseParameter = function (name, value, target, propertyPath) {
  48162. if (propertyPath === null) {
  48163. // String, boolean or float
  48164. var floatValue = parseFloat(value);
  48165. if (value === "true" || value === "false")
  48166. return value === "true";
  48167. else
  48168. return isNaN(floatValue) ? value : floatValue;
  48169. }
  48170. var effectiveTarget = propertyPath.split(".");
  48171. var values = value.split(",");
  48172. // Get effective Target
  48173. for (var i = 0; i < effectiveTarget.length; i++) {
  48174. target = target[effectiveTarget[i]];
  48175. }
  48176. // Return appropriate value with its type
  48177. if (typeof (target) === "boolean")
  48178. return values[0] === "true";
  48179. if (typeof (target) === "string")
  48180. return values[0];
  48181. // Parameters with multiple values such as Vector3 etc.
  48182. var split = new Array();
  48183. for (var i = 0; i < values.length; i++)
  48184. split.push(parseFloat(values[i]));
  48185. if (target instanceof BABYLON.Vector3)
  48186. return BABYLON.Vector3.FromArray(split);
  48187. if (target instanceof BABYLON.Vector4)
  48188. return BABYLON.Vector4.FromArray(split);
  48189. if (target instanceof BABYLON.Color3)
  48190. return BABYLON.Color3.FromArray(split);
  48191. if (target instanceof BABYLON.Color4)
  48192. return BABYLON.Color4.FromArray(split);
  48193. return parseFloat(values[0]);
  48194. };
  48195. // traverse graph per trigger
  48196. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48197. if (combineArray === void 0) { combineArray = null; }
  48198. if (parsedAction.detached)
  48199. return;
  48200. var parameters = new Array();
  48201. var target = null;
  48202. var propertyPath = null;
  48203. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48204. // Parameters
  48205. if (parsedAction.type === 2)
  48206. parameters.push(actionManager);
  48207. else
  48208. parameters.push(trigger);
  48209. if (combine) {
  48210. var actions = new Array();
  48211. for (var j = 0; j < parsedAction.combine.length; j++) {
  48212. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48213. }
  48214. parameters.push(actions);
  48215. }
  48216. else {
  48217. for (var i = 0; i < parsedAction.properties.length; i++) {
  48218. var value = parsedAction.properties[i].value;
  48219. var name = parsedAction.properties[i].name;
  48220. var targetType = parsedAction.properties[i].targetType;
  48221. if (name === "target")
  48222. if (targetType !== null && targetType === "SceneProperties")
  48223. value = target = scene;
  48224. else
  48225. value = target = scene.getNodeByName(value);
  48226. else if (name === "parent")
  48227. value = scene.getNodeByName(value);
  48228. else if (name === "sound")
  48229. value = scene.getSoundByName(value);
  48230. else if (name !== "propertyPath") {
  48231. if (parsedAction.type === 2 && name === "operator")
  48232. value = BABYLON.ValueCondition[value];
  48233. else
  48234. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48235. }
  48236. else {
  48237. propertyPath = value;
  48238. }
  48239. parameters.push(value);
  48240. }
  48241. }
  48242. if (combineArray === null) {
  48243. parameters.push(condition);
  48244. }
  48245. else {
  48246. parameters.push(null);
  48247. }
  48248. // If interpolate value action
  48249. if (parsedAction.name === "InterpolateValueAction") {
  48250. var param = parameters[parameters.length - 2];
  48251. parameters[parameters.length - 1] = param;
  48252. parameters[parameters.length - 2] = condition;
  48253. }
  48254. // Action or condition(s) and not CombineAction
  48255. var newAction = instanciate(parsedAction.name, parameters);
  48256. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48257. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48258. if (action)
  48259. action.then(nothing);
  48260. else
  48261. actionManager.registerAction(nothing);
  48262. action = nothing;
  48263. }
  48264. if (combineArray === null) {
  48265. if (newAction instanceof BABYLON.Condition) {
  48266. condition = newAction;
  48267. newAction = action;
  48268. }
  48269. else {
  48270. condition = null;
  48271. if (action)
  48272. action.then(newAction);
  48273. else
  48274. actionManager.registerAction(newAction);
  48275. }
  48276. }
  48277. else {
  48278. combineArray.push(newAction);
  48279. }
  48280. for (var i = 0; i < parsedAction.children.length; i++)
  48281. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48282. };
  48283. // triggers
  48284. for (var i = 0; i < parsedActions.children.length; i++) {
  48285. var triggerParams;
  48286. var trigger = parsedActions.children[i];
  48287. if (trigger.properties.length > 0) {
  48288. var param = trigger.properties[0].value;
  48289. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48290. if (value._meshId) {
  48291. value.mesh = scene.getMeshByID(value._meshId);
  48292. }
  48293. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48294. }
  48295. else
  48296. triggerParams = ActionManager[trigger.name];
  48297. for (var j = 0; j < trigger.children.length; j++) {
  48298. if (!trigger.detached)
  48299. traverse(trigger.children[j], triggerParams, null, null);
  48300. }
  48301. }
  48302. };
  48303. ActionManager.GetTriggerName = function (trigger) {
  48304. switch (trigger) {
  48305. case 0: return "NothingTrigger";
  48306. case 1: return "OnPickTrigger";
  48307. case 2: return "OnLeftPickTrigger";
  48308. case 3: return "OnRightPickTrigger";
  48309. case 4: return "OnCenterPickTrigger";
  48310. case 5: return "OnPickDownTrigger";
  48311. case 6: return "OnPickUpTrigger";
  48312. case 7: return "OnLongPressTrigger";
  48313. case 8: return "OnPointerOverTrigger";
  48314. case 9: return "OnPointerOutTrigger";
  48315. case 10: return "OnEveryFrameTrigger";
  48316. case 11: return "OnIntersectionEnterTrigger";
  48317. case 12: return "OnIntersectionExitTrigger";
  48318. case 13: return "OnKeyDownTrigger";
  48319. case 14: return "OnKeyUpTrigger";
  48320. case 15: return "OnPickOutTrigger";
  48321. default: return "";
  48322. }
  48323. };
  48324. // Statics
  48325. ActionManager._NothingTrigger = 0;
  48326. ActionManager._OnPickTrigger = 1;
  48327. ActionManager._OnLeftPickTrigger = 2;
  48328. ActionManager._OnRightPickTrigger = 3;
  48329. ActionManager._OnCenterPickTrigger = 4;
  48330. ActionManager._OnPickDownTrigger = 5;
  48331. ActionManager._OnDoublePickTrigger = 6;
  48332. ActionManager._OnPickUpTrigger = 7;
  48333. ActionManager._OnLongPressTrigger = 8;
  48334. ActionManager._OnPointerOverTrigger = 9;
  48335. ActionManager._OnPointerOutTrigger = 10;
  48336. ActionManager._OnEveryFrameTrigger = 11;
  48337. ActionManager._OnIntersectionEnterTrigger = 12;
  48338. ActionManager._OnIntersectionExitTrigger = 13;
  48339. ActionManager._OnKeyDownTrigger = 14;
  48340. ActionManager._OnKeyUpTrigger = 15;
  48341. ActionManager._OnPickOutTrigger = 16;
  48342. ActionManager.Triggers = {};
  48343. return ActionManager;
  48344. }());
  48345. BABYLON.ActionManager = ActionManager;
  48346. })(BABYLON || (BABYLON = {}));
  48347. //# sourceMappingURL=babylon.actionManager.js.map
  48348. var BABYLON;
  48349. (function (BABYLON) {
  48350. var InterpolateValueAction = /** @class */ (function (_super) {
  48351. __extends(InterpolateValueAction, _super);
  48352. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48353. if (duration === void 0) { duration = 1000; }
  48354. var _this = _super.call(this, triggerOptions, condition) || this;
  48355. _this.propertyPath = propertyPath;
  48356. _this.value = value;
  48357. _this.duration = duration;
  48358. _this.stopOtherAnimations = stopOtherAnimations;
  48359. _this.onInterpolationDone = onInterpolationDone;
  48360. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48361. _this._target = _this._effectiveTarget = target;
  48362. return _this;
  48363. }
  48364. InterpolateValueAction.prototype._prepare = function () {
  48365. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48366. this._property = this._getProperty(this.propertyPath);
  48367. };
  48368. InterpolateValueAction.prototype.execute = function () {
  48369. var _this = this;
  48370. var scene = this._actionManager.getScene();
  48371. var keys = [
  48372. {
  48373. frame: 0,
  48374. value: this._effectiveTarget[this._property]
  48375. }, {
  48376. frame: 100,
  48377. value: this.value
  48378. }
  48379. ];
  48380. var dataType;
  48381. if (typeof this.value === "number") {
  48382. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48383. }
  48384. else if (this.value instanceof BABYLON.Color3) {
  48385. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48386. }
  48387. else if (this.value instanceof BABYLON.Vector3) {
  48388. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48389. }
  48390. else if (this.value instanceof BABYLON.Matrix) {
  48391. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48392. }
  48393. else if (this.value instanceof BABYLON.Quaternion) {
  48394. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48395. }
  48396. else {
  48397. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48398. return;
  48399. }
  48400. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48401. animation.setKeys(keys);
  48402. if (this.stopOtherAnimations) {
  48403. scene.stopAnimation(this._effectiveTarget);
  48404. }
  48405. var wrapper = function () {
  48406. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48407. if (_this.onInterpolationDone) {
  48408. _this.onInterpolationDone();
  48409. }
  48410. };
  48411. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48412. };
  48413. InterpolateValueAction.prototype.serialize = function (parent) {
  48414. return _super.prototype._serialize.call(this, {
  48415. name: "InterpolateValueAction",
  48416. properties: [
  48417. BABYLON.Action._GetTargetProperty(this._target),
  48418. { name: "propertyPath", value: this.propertyPath },
  48419. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48420. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48421. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48422. ]
  48423. }, parent);
  48424. };
  48425. return InterpolateValueAction;
  48426. }(BABYLON.Action));
  48427. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48428. })(BABYLON || (BABYLON = {}));
  48429. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48430. var BABYLON;
  48431. (function (BABYLON) {
  48432. var SwitchBooleanAction = /** @class */ (function (_super) {
  48433. __extends(SwitchBooleanAction, _super);
  48434. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48435. var _this = _super.call(this, triggerOptions, condition) || this;
  48436. _this.propertyPath = propertyPath;
  48437. _this._target = _this._effectiveTarget = target;
  48438. return _this;
  48439. }
  48440. SwitchBooleanAction.prototype._prepare = function () {
  48441. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48442. this._property = this._getProperty(this.propertyPath);
  48443. };
  48444. SwitchBooleanAction.prototype.execute = function () {
  48445. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48446. };
  48447. SwitchBooleanAction.prototype.serialize = function (parent) {
  48448. return _super.prototype._serialize.call(this, {
  48449. name: "SwitchBooleanAction",
  48450. properties: [
  48451. BABYLON.Action._GetTargetProperty(this._target),
  48452. { name: "propertyPath", value: this.propertyPath }
  48453. ]
  48454. }, parent);
  48455. };
  48456. return SwitchBooleanAction;
  48457. }(BABYLON.Action));
  48458. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48459. var SetStateAction = /** @class */ (function (_super) {
  48460. __extends(SetStateAction, _super);
  48461. function SetStateAction(triggerOptions, target, value, condition) {
  48462. var _this = _super.call(this, triggerOptions, condition) || this;
  48463. _this.value = value;
  48464. _this._target = target;
  48465. return _this;
  48466. }
  48467. SetStateAction.prototype.execute = function () {
  48468. this._target.state = this.value;
  48469. };
  48470. SetStateAction.prototype.serialize = function (parent) {
  48471. return _super.prototype._serialize.call(this, {
  48472. name: "SetStateAction",
  48473. properties: [
  48474. BABYLON.Action._GetTargetProperty(this._target),
  48475. { name: "value", value: this.value }
  48476. ]
  48477. }, parent);
  48478. };
  48479. return SetStateAction;
  48480. }(BABYLON.Action));
  48481. BABYLON.SetStateAction = SetStateAction;
  48482. var SetValueAction = /** @class */ (function (_super) {
  48483. __extends(SetValueAction, _super);
  48484. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48485. var _this = _super.call(this, triggerOptions, condition) || this;
  48486. _this.propertyPath = propertyPath;
  48487. _this.value = value;
  48488. _this._target = _this._effectiveTarget = target;
  48489. return _this;
  48490. }
  48491. SetValueAction.prototype._prepare = function () {
  48492. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48493. this._property = this._getProperty(this.propertyPath);
  48494. };
  48495. SetValueAction.prototype.execute = function () {
  48496. this._effectiveTarget[this._property] = this.value;
  48497. if (this._target.markAsDirty) {
  48498. this._target.markAsDirty(this._property);
  48499. }
  48500. };
  48501. SetValueAction.prototype.serialize = function (parent) {
  48502. return _super.prototype._serialize.call(this, {
  48503. name: "SetValueAction",
  48504. properties: [
  48505. BABYLON.Action._GetTargetProperty(this._target),
  48506. { name: "propertyPath", value: this.propertyPath },
  48507. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48508. ]
  48509. }, parent);
  48510. };
  48511. return SetValueAction;
  48512. }(BABYLON.Action));
  48513. BABYLON.SetValueAction = SetValueAction;
  48514. var IncrementValueAction = /** @class */ (function (_super) {
  48515. __extends(IncrementValueAction, _super);
  48516. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48517. var _this = _super.call(this, triggerOptions, condition) || this;
  48518. _this.propertyPath = propertyPath;
  48519. _this.value = value;
  48520. _this._target = _this._effectiveTarget = target;
  48521. return _this;
  48522. }
  48523. IncrementValueAction.prototype._prepare = function () {
  48524. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48525. this._property = this._getProperty(this.propertyPath);
  48526. if (typeof this._effectiveTarget[this._property] !== "number") {
  48527. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48528. }
  48529. };
  48530. IncrementValueAction.prototype.execute = function () {
  48531. this._effectiveTarget[this._property] += this.value;
  48532. if (this._target.markAsDirty) {
  48533. this._target.markAsDirty(this._property);
  48534. }
  48535. };
  48536. IncrementValueAction.prototype.serialize = function (parent) {
  48537. return _super.prototype._serialize.call(this, {
  48538. name: "IncrementValueAction",
  48539. properties: [
  48540. BABYLON.Action._GetTargetProperty(this._target),
  48541. { name: "propertyPath", value: this.propertyPath },
  48542. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48543. ]
  48544. }, parent);
  48545. };
  48546. return IncrementValueAction;
  48547. }(BABYLON.Action));
  48548. BABYLON.IncrementValueAction = IncrementValueAction;
  48549. var PlayAnimationAction = /** @class */ (function (_super) {
  48550. __extends(PlayAnimationAction, _super);
  48551. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48552. var _this = _super.call(this, triggerOptions, condition) || this;
  48553. _this.from = from;
  48554. _this.to = to;
  48555. _this.loop = loop;
  48556. _this._target = target;
  48557. return _this;
  48558. }
  48559. PlayAnimationAction.prototype._prepare = function () {
  48560. };
  48561. PlayAnimationAction.prototype.execute = function () {
  48562. var scene = this._actionManager.getScene();
  48563. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48564. };
  48565. PlayAnimationAction.prototype.serialize = function (parent) {
  48566. return _super.prototype._serialize.call(this, {
  48567. name: "PlayAnimationAction",
  48568. properties: [
  48569. BABYLON.Action._GetTargetProperty(this._target),
  48570. { name: "from", value: String(this.from) },
  48571. { name: "to", value: String(this.to) },
  48572. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48573. ]
  48574. }, parent);
  48575. };
  48576. return PlayAnimationAction;
  48577. }(BABYLON.Action));
  48578. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48579. var StopAnimationAction = /** @class */ (function (_super) {
  48580. __extends(StopAnimationAction, _super);
  48581. function StopAnimationAction(triggerOptions, target, condition) {
  48582. var _this = _super.call(this, triggerOptions, condition) || this;
  48583. _this._target = target;
  48584. return _this;
  48585. }
  48586. StopAnimationAction.prototype._prepare = function () {
  48587. };
  48588. StopAnimationAction.prototype.execute = function () {
  48589. var scene = this._actionManager.getScene();
  48590. scene.stopAnimation(this._target);
  48591. };
  48592. StopAnimationAction.prototype.serialize = function (parent) {
  48593. return _super.prototype._serialize.call(this, {
  48594. name: "StopAnimationAction",
  48595. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48596. }, parent);
  48597. };
  48598. return StopAnimationAction;
  48599. }(BABYLON.Action));
  48600. BABYLON.StopAnimationAction = StopAnimationAction;
  48601. var DoNothingAction = /** @class */ (function (_super) {
  48602. __extends(DoNothingAction, _super);
  48603. function DoNothingAction(triggerOptions, condition) {
  48604. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48605. return _super.call(this, triggerOptions, condition) || this;
  48606. }
  48607. DoNothingAction.prototype.execute = function () {
  48608. };
  48609. DoNothingAction.prototype.serialize = function (parent) {
  48610. return _super.prototype._serialize.call(this, {
  48611. name: "DoNothingAction",
  48612. properties: []
  48613. }, parent);
  48614. };
  48615. return DoNothingAction;
  48616. }(BABYLON.Action));
  48617. BABYLON.DoNothingAction = DoNothingAction;
  48618. var CombineAction = /** @class */ (function (_super) {
  48619. __extends(CombineAction, _super);
  48620. function CombineAction(triggerOptions, children, condition) {
  48621. var _this = _super.call(this, triggerOptions, condition) || this;
  48622. _this.children = children;
  48623. return _this;
  48624. }
  48625. CombineAction.prototype._prepare = function () {
  48626. for (var index = 0; index < this.children.length; index++) {
  48627. this.children[index]._actionManager = this._actionManager;
  48628. this.children[index]._prepare();
  48629. }
  48630. };
  48631. CombineAction.prototype.execute = function (evt) {
  48632. for (var index = 0; index < this.children.length; index++) {
  48633. this.children[index].execute(evt);
  48634. }
  48635. };
  48636. CombineAction.prototype.serialize = function (parent) {
  48637. var serializationObject = _super.prototype._serialize.call(this, {
  48638. name: "CombineAction",
  48639. properties: [],
  48640. combine: []
  48641. }, parent);
  48642. for (var i = 0; i < this.children.length; i++) {
  48643. serializationObject.combine.push(this.children[i].serialize(null));
  48644. }
  48645. return serializationObject;
  48646. };
  48647. return CombineAction;
  48648. }(BABYLON.Action));
  48649. BABYLON.CombineAction = CombineAction;
  48650. var ExecuteCodeAction = /** @class */ (function (_super) {
  48651. __extends(ExecuteCodeAction, _super);
  48652. function ExecuteCodeAction(triggerOptions, func, condition) {
  48653. var _this = _super.call(this, triggerOptions, condition) || this;
  48654. _this.func = func;
  48655. return _this;
  48656. }
  48657. ExecuteCodeAction.prototype.execute = function (evt) {
  48658. this.func(evt);
  48659. };
  48660. return ExecuteCodeAction;
  48661. }(BABYLON.Action));
  48662. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48663. var SetParentAction = /** @class */ (function (_super) {
  48664. __extends(SetParentAction, _super);
  48665. function SetParentAction(triggerOptions, target, parent, condition) {
  48666. var _this = _super.call(this, triggerOptions, condition) || this;
  48667. _this._target = target;
  48668. _this._parent = parent;
  48669. return _this;
  48670. }
  48671. SetParentAction.prototype._prepare = function () {
  48672. };
  48673. SetParentAction.prototype.execute = function () {
  48674. if (this._target.parent === this._parent) {
  48675. return;
  48676. }
  48677. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48678. invertParentWorldMatrix.invert();
  48679. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48680. this._target.parent = this._parent;
  48681. };
  48682. SetParentAction.prototype.serialize = function (parent) {
  48683. return _super.prototype._serialize.call(this, {
  48684. name: "SetParentAction",
  48685. properties: [
  48686. BABYLON.Action._GetTargetProperty(this._target),
  48687. BABYLON.Action._GetTargetProperty(this._parent),
  48688. ]
  48689. }, parent);
  48690. };
  48691. return SetParentAction;
  48692. }(BABYLON.Action));
  48693. BABYLON.SetParentAction = SetParentAction;
  48694. var PlaySoundAction = /** @class */ (function (_super) {
  48695. __extends(PlaySoundAction, _super);
  48696. function PlaySoundAction(triggerOptions, sound, condition) {
  48697. var _this = _super.call(this, triggerOptions, condition) || this;
  48698. _this._sound = sound;
  48699. return _this;
  48700. }
  48701. PlaySoundAction.prototype._prepare = function () {
  48702. };
  48703. PlaySoundAction.prototype.execute = function () {
  48704. if (this._sound !== undefined)
  48705. this._sound.play();
  48706. };
  48707. PlaySoundAction.prototype.serialize = function (parent) {
  48708. return _super.prototype._serialize.call(this, {
  48709. name: "PlaySoundAction",
  48710. properties: [{ name: "sound", value: this._sound.name }]
  48711. }, parent);
  48712. };
  48713. return PlaySoundAction;
  48714. }(BABYLON.Action));
  48715. BABYLON.PlaySoundAction = PlaySoundAction;
  48716. var StopSoundAction = /** @class */ (function (_super) {
  48717. __extends(StopSoundAction, _super);
  48718. function StopSoundAction(triggerOptions, sound, condition) {
  48719. var _this = _super.call(this, triggerOptions, condition) || this;
  48720. _this._sound = sound;
  48721. return _this;
  48722. }
  48723. StopSoundAction.prototype._prepare = function () {
  48724. };
  48725. StopSoundAction.prototype.execute = function () {
  48726. if (this._sound !== undefined)
  48727. this._sound.stop();
  48728. };
  48729. StopSoundAction.prototype.serialize = function (parent) {
  48730. return _super.prototype._serialize.call(this, {
  48731. name: "StopSoundAction",
  48732. properties: [{ name: "sound", value: this._sound.name }]
  48733. }, parent);
  48734. };
  48735. return StopSoundAction;
  48736. }(BABYLON.Action));
  48737. BABYLON.StopSoundAction = StopSoundAction;
  48738. })(BABYLON || (BABYLON = {}));
  48739. //# sourceMappingURL=babylon.directActions.js.map
  48740. var BABYLON;
  48741. (function (BABYLON) {
  48742. var SpriteManager = /** @class */ (function () {
  48743. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48744. if (epsilon === void 0) { epsilon = 0.01; }
  48745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48746. this.name = name;
  48747. this.sprites = new Array();
  48748. this.renderingGroupId = 0;
  48749. this.layerMask = 0x0FFFFFFF;
  48750. this.fogEnabled = true;
  48751. this.isPickable = false;
  48752. /**
  48753. * An event triggered when the manager is disposed.
  48754. * @type {BABYLON.Observable}
  48755. */
  48756. this.onDisposeObservable = new BABYLON.Observable();
  48757. this._vertexBuffers = {};
  48758. this._capacity = capacity;
  48759. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48760. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48761. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48762. if (cellSize.width && cellSize.height) {
  48763. this.cellWidth = cellSize.width;
  48764. this.cellHeight = cellSize.height;
  48765. }
  48766. else if (cellSize !== undefined) {
  48767. this.cellWidth = cellSize;
  48768. this.cellHeight = cellSize;
  48769. }
  48770. else {
  48771. return;
  48772. }
  48773. this._epsilon = epsilon;
  48774. this._scene = scene;
  48775. this._scene.spriteManagers.push(this);
  48776. var indices = [];
  48777. var index = 0;
  48778. for (var count = 0; count < capacity; count++) {
  48779. indices.push(index);
  48780. indices.push(index + 1);
  48781. indices.push(index + 2);
  48782. indices.push(index);
  48783. indices.push(index + 2);
  48784. indices.push(index + 3);
  48785. index += 4;
  48786. }
  48787. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48788. // VBO
  48789. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48790. this._vertexData = new Float32Array(capacity * 16 * 4);
  48791. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48792. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48793. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48794. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48795. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48796. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48797. this._vertexBuffers["options"] = options;
  48798. this._vertexBuffers["cellInfo"] = cellInfo;
  48799. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48800. // Effects
  48801. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48802. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48803. }
  48804. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48805. set: function (callback) {
  48806. if (this._onDisposeObserver) {
  48807. this.onDisposeObservable.remove(this._onDisposeObserver);
  48808. }
  48809. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48810. },
  48811. enumerable: true,
  48812. configurable: true
  48813. });
  48814. Object.defineProperty(SpriteManager.prototype, "texture", {
  48815. get: function () {
  48816. return this._spriteTexture;
  48817. },
  48818. set: function (value) {
  48819. this._spriteTexture = value;
  48820. },
  48821. enumerable: true,
  48822. configurable: true
  48823. });
  48824. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48825. var arrayOffset = index * 16;
  48826. if (offsetX === 0)
  48827. offsetX = this._epsilon;
  48828. else if (offsetX === 1)
  48829. offsetX = 1 - this._epsilon;
  48830. if (offsetY === 0)
  48831. offsetY = this._epsilon;
  48832. else if (offsetY === 1)
  48833. offsetY = 1 - this._epsilon;
  48834. this._vertexData[arrayOffset] = sprite.position.x;
  48835. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48836. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48837. this._vertexData[arrayOffset + 3] = sprite.angle;
  48838. this._vertexData[arrayOffset + 4] = sprite.width;
  48839. this._vertexData[arrayOffset + 5] = sprite.height;
  48840. this._vertexData[arrayOffset + 6] = offsetX;
  48841. this._vertexData[arrayOffset + 7] = offsetY;
  48842. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48843. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48844. var offset = (sprite.cellIndex / rowSize) >> 0;
  48845. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48846. this._vertexData[arrayOffset + 11] = offset;
  48847. // Color
  48848. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48849. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48850. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48851. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48852. };
  48853. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48854. var count = Math.min(this._capacity, this.sprites.length);
  48855. var min = BABYLON.Vector3.Zero();
  48856. var max = BABYLON.Vector3.Zero();
  48857. var distance = Number.MAX_VALUE;
  48858. var currentSprite = null;
  48859. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48860. var cameraView = camera.getViewMatrix();
  48861. for (var index = 0; index < count; index++) {
  48862. var sprite = this.sprites[index];
  48863. if (!sprite) {
  48864. continue;
  48865. }
  48866. if (predicate) {
  48867. if (!predicate(sprite)) {
  48868. continue;
  48869. }
  48870. }
  48871. else if (!sprite.isPickable) {
  48872. continue;
  48873. }
  48874. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48875. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48876. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48877. if (ray.intersectsBoxMinMax(min, max)) {
  48878. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48879. if (distance > currentDistance) {
  48880. distance = currentDistance;
  48881. currentSprite = sprite;
  48882. if (fastCheck) {
  48883. break;
  48884. }
  48885. }
  48886. }
  48887. }
  48888. if (currentSprite) {
  48889. var result = new BABYLON.PickingInfo();
  48890. result.hit = true;
  48891. result.pickedSprite = currentSprite;
  48892. result.distance = distance;
  48893. return result;
  48894. }
  48895. return null;
  48896. };
  48897. SpriteManager.prototype.render = function () {
  48898. // Check
  48899. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48900. return;
  48901. var engine = this._scene.getEngine();
  48902. var baseSize = this._spriteTexture.getBaseSize();
  48903. // Sprites
  48904. var deltaTime = engine.getDeltaTime();
  48905. var max = Math.min(this._capacity, this.sprites.length);
  48906. var rowSize = baseSize.width / this.cellWidth;
  48907. var offset = 0;
  48908. for (var index = 0; index < max; index++) {
  48909. var sprite = this.sprites[index];
  48910. if (!sprite) {
  48911. continue;
  48912. }
  48913. sprite._animate(deltaTime);
  48914. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48915. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48916. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48917. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48918. }
  48919. this._buffer.update(this._vertexData);
  48920. // Render
  48921. var effect = this._effectBase;
  48922. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48923. effect = this._effectFog;
  48924. }
  48925. engine.enableEffect(effect);
  48926. var viewMatrix = this._scene.getViewMatrix();
  48927. effect.setTexture("diffuseSampler", this._spriteTexture);
  48928. effect.setMatrix("view", viewMatrix);
  48929. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48930. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48931. // Fog
  48932. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48933. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48934. effect.setColor3("vFogColor", this._scene.fogColor);
  48935. }
  48936. // VBOs
  48937. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48938. // Draw order
  48939. engine.setDepthFunctionToLessOrEqual();
  48940. effect.setBool("alphaTest", true);
  48941. engine.setColorWrite(false);
  48942. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48943. engine.setColorWrite(true);
  48944. effect.setBool("alphaTest", false);
  48945. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48946. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48947. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48948. };
  48949. SpriteManager.prototype.dispose = function () {
  48950. if (this._buffer) {
  48951. this._buffer.dispose();
  48952. this._buffer = null;
  48953. }
  48954. if (this._indexBuffer) {
  48955. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48956. this._indexBuffer = null;
  48957. }
  48958. if (this._spriteTexture) {
  48959. this._spriteTexture.dispose();
  48960. this._spriteTexture = null;
  48961. }
  48962. // Remove from scene
  48963. var index = this._scene.spriteManagers.indexOf(this);
  48964. this._scene.spriteManagers.splice(index, 1);
  48965. // Callback
  48966. this.onDisposeObservable.notifyObservers(this);
  48967. this.onDisposeObservable.clear();
  48968. };
  48969. return SpriteManager;
  48970. }());
  48971. BABYLON.SpriteManager = SpriteManager;
  48972. })(BABYLON || (BABYLON = {}));
  48973. //# sourceMappingURL=babylon.spriteManager.js.map
  48974. var BABYLON;
  48975. (function (BABYLON) {
  48976. var Sprite = /** @class */ (function () {
  48977. function Sprite(name, manager) {
  48978. this.name = name;
  48979. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48980. this.width = 1.0;
  48981. this.height = 1.0;
  48982. this.angle = 0;
  48983. this.cellIndex = 0;
  48984. this.invertU = 0;
  48985. this.invertV = 0;
  48986. this.animations = new Array();
  48987. this.isPickable = false;
  48988. this._animationStarted = false;
  48989. this._loopAnimation = false;
  48990. this._fromIndex = 0;
  48991. this._toIndex = 0;
  48992. this._delay = 0;
  48993. this._direction = 1;
  48994. this._time = 0;
  48995. this._manager = manager;
  48996. this._manager.sprites.push(this);
  48997. this.position = BABYLON.Vector3.Zero();
  48998. }
  48999. Object.defineProperty(Sprite.prototype, "size", {
  49000. get: function () {
  49001. return this.width;
  49002. },
  49003. set: function (value) {
  49004. this.width = value;
  49005. this.height = value;
  49006. },
  49007. enumerable: true,
  49008. configurable: true
  49009. });
  49010. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  49011. this._fromIndex = from;
  49012. this._toIndex = to;
  49013. this._loopAnimation = loop;
  49014. this._delay = delay;
  49015. this._animationStarted = true;
  49016. this._direction = from < to ? 1 : -1;
  49017. this.cellIndex = from;
  49018. this._time = 0;
  49019. this._onAnimationEnd = onAnimationEnd;
  49020. };
  49021. Sprite.prototype.stopAnimation = function () {
  49022. this._animationStarted = false;
  49023. };
  49024. Sprite.prototype._animate = function (deltaTime) {
  49025. if (!this._animationStarted)
  49026. return;
  49027. this._time += deltaTime;
  49028. if (this._time > this._delay) {
  49029. this._time = this._time % this._delay;
  49030. this.cellIndex += this._direction;
  49031. if (this.cellIndex > this._toIndex) {
  49032. if (this._loopAnimation) {
  49033. this.cellIndex = this._fromIndex;
  49034. }
  49035. else {
  49036. this.cellIndex = this._toIndex;
  49037. this._animationStarted = false;
  49038. if (this._onAnimationEnd) {
  49039. this._onAnimationEnd();
  49040. }
  49041. if (this.disposeWhenFinishedAnimating) {
  49042. this.dispose();
  49043. }
  49044. }
  49045. }
  49046. }
  49047. };
  49048. Sprite.prototype.dispose = function () {
  49049. for (var i = 0; i < this._manager.sprites.length; i++) {
  49050. if (this._manager.sprites[i] == this) {
  49051. this._manager.sprites.splice(i, 1);
  49052. }
  49053. }
  49054. };
  49055. return Sprite;
  49056. }());
  49057. BABYLON.Sprite = Sprite;
  49058. })(BABYLON || (BABYLON = {}));
  49059. //# sourceMappingURL=babylon.sprite.js.map
  49060. var BABYLON;
  49061. (function (BABYLON) {
  49062. var IntersectionInfo = /** @class */ (function () {
  49063. function IntersectionInfo(bu, bv, distance) {
  49064. this.bu = bu;
  49065. this.bv = bv;
  49066. this.distance = distance;
  49067. this.faceId = 0;
  49068. this.subMeshId = 0;
  49069. }
  49070. return IntersectionInfo;
  49071. }());
  49072. BABYLON.IntersectionInfo = IntersectionInfo;
  49073. var PickingInfo = /** @class */ (function () {
  49074. function PickingInfo() {
  49075. this.hit = false;
  49076. this.distance = 0;
  49077. this.pickedPoint = null;
  49078. this.pickedMesh = null;
  49079. this.bu = 0;
  49080. this.bv = 0;
  49081. this.faceId = -1;
  49082. this.subMeshId = 0;
  49083. this.pickedSprite = null;
  49084. }
  49085. // Methods
  49086. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49087. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49088. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49089. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49090. return null;
  49091. }
  49092. var indices = this.pickedMesh.getIndices();
  49093. if (!indices) {
  49094. return null;
  49095. }
  49096. var result;
  49097. if (useVerticesNormals) {
  49098. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49099. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49100. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49101. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49102. normal0 = normal0.scale(this.bu);
  49103. normal1 = normal1.scale(this.bv);
  49104. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49105. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49106. }
  49107. else {
  49108. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49109. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49110. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49111. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49112. var p1p2 = vertex1.subtract(vertex2);
  49113. var p3p2 = vertex3.subtract(vertex2);
  49114. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49115. }
  49116. if (useWorldCoordinates) {
  49117. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49118. }
  49119. return BABYLON.Vector3.Normalize(result);
  49120. };
  49121. PickingInfo.prototype.getTextureCoordinates = function () {
  49122. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49123. return null;
  49124. }
  49125. var indices = this.pickedMesh.getIndices();
  49126. if (!indices) {
  49127. return null;
  49128. }
  49129. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49130. if (!uvs) {
  49131. return null;
  49132. }
  49133. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49134. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49135. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49136. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49137. uv1 = uv1.scale(this.bu);
  49138. uv2 = uv2.scale(this.bv);
  49139. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49140. };
  49141. return PickingInfo;
  49142. }());
  49143. BABYLON.PickingInfo = PickingInfo;
  49144. })(BABYLON || (BABYLON = {}));
  49145. //# sourceMappingURL=babylon.pickingInfo.js.map
  49146. var BABYLON;
  49147. (function (BABYLON) {
  49148. var Ray = /** @class */ (function () {
  49149. function Ray(origin, direction, length) {
  49150. if (length === void 0) { length = Number.MAX_VALUE; }
  49151. this.origin = origin;
  49152. this.direction = direction;
  49153. this.length = length;
  49154. }
  49155. // Methods
  49156. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49157. var d = 0.0;
  49158. var maxValue = Number.MAX_VALUE;
  49159. var inv;
  49160. var min;
  49161. var max;
  49162. var temp;
  49163. if (Math.abs(this.direction.x) < 0.0000001) {
  49164. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49165. return false;
  49166. }
  49167. }
  49168. else {
  49169. inv = 1.0 / this.direction.x;
  49170. min = (minimum.x - this.origin.x) * inv;
  49171. max = (maximum.x - this.origin.x) * inv;
  49172. if (max === -Infinity) {
  49173. max = Infinity;
  49174. }
  49175. if (min > max) {
  49176. temp = min;
  49177. min = max;
  49178. max = temp;
  49179. }
  49180. d = Math.max(min, d);
  49181. maxValue = Math.min(max, maxValue);
  49182. if (d > maxValue) {
  49183. return false;
  49184. }
  49185. }
  49186. if (Math.abs(this.direction.y) < 0.0000001) {
  49187. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49188. return false;
  49189. }
  49190. }
  49191. else {
  49192. inv = 1.0 / this.direction.y;
  49193. min = (minimum.y - this.origin.y) * inv;
  49194. max = (maximum.y - this.origin.y) * inv;
  49195. if (max === -Infinity) {
  49196. max = Infinity;
  49197. }
  49198. if (min > max) {
  49199. temp = min;
  49200. min = max;
  49201. max = temp;
  49202. }
  49203. d = Math.max(min, d);
  49204. maxValue = Math.min(max, maxValue);
  49205. if (d > maxValue) {
  49206. return false;
  49207. }
  49208. }
  49209. if (Math.abs(this.direction.z) < 0.0000001) {
  49210. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49211. return false;
  49212. }
  49213. }
  49214. else {
  49215. inv = 1.0 / this.direction.z;
  49216. min = (minimum.z - this.origin.z) * inv;
  49217. max = (maximum.z - this.origin.z) * inv;
  49218. if (max === -Infinity) {
  49219. max = Infinity;
  49220. }
  49221. if (min > max) {
  49222. temp = min;
  49223. min = max;
  49224. max = temp;
  49225. }
  49226. d = Math.max(min, d);
  49227. maxValue = Math.min(max, maxValue);
  49228. if (d > maxValue) {
  49229. return false;
  49230. }
  49231. }
  49232. return true;
  49233. };
  49234. Ray.prototype.intersectsBox = function (box) {
  49235. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49236. };
  49237. Ray.prototype.intersectsSphere = function (sphere) {
  49238. var x = sphere.center.x - this.origin.x;
  49239. var y = sphere.center.y - this.origin.y;
  49240. var z = sphere.center.z - this.origin.z;
  49241. var pyth = (x * x) + (y * y) + (z * z);
  49242. var rr = sphere.radius * sphere.radius;
  49243. if (pyth <= rr) {
  49244. return true;
  49245. }
  49246. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49247. if (dot < 0.0) {
  49248. return false;
  49249. }
  49250. var temp = pyth - (dot * dot);
  49251. return temp <= rr;
  49252. };
  49253. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49254. if (!this._edge1) {
  49255. this._edge1 = BABYLON.Vector3.Zero();
  49256. this._edge2 = BABYLON.Vector3.Zero();
  49257. this._pvec = BABYLON.Vector3.Zero();
  49258. this._tvec = BABYLON.Vector3.Zero();
  49259. this._qvec = BABYLON.Vector3.Zero();
  49260. }
  49261. vertex1.subtractToRef(vertex0, this._edge1);
  49262. vertex2.subtractToRef(vertex0, this._edge2);
  49263. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49264. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49265. if (det === 0) {
  49266. return null;
  49267. }
  49268. var invdet = 1 / det;
  49269. this.origin.subtractToRef(vertex0, this._tvec);
  49270. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49271. if (bu < 0 || bu > 1.0) {
  49272. return null;
  49273. }
  49274. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49275. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49276. if (bv < 0 || bu + bv > 1.0) {
  49277. return null;
  49278. }
  49279. //check if the distance is longer than the predefined length.
  49280. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49281. if (distance > this.length) {
  49282. return null;
  49283. }
  49284. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49285. };
  49286. Ray.prototype.intersectsPlane = function (plane) {
  49287. var distance;
  49288. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49289. if (Math.abs(result1) < 9.99999997475243E-07) {
  49290. return null;
  49291. }
  49292. else {
  49293. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49294. distance = (-plane.d - result2) / result1;
  49295. if (distance < 0.0) {
  49296. if (distance < -9.99999997475243E-07) {
  49297. return null;
  49298. }
  49299. else {
  49300. return 0;
  49301. }
  49302. }
  49303. return distance;
  49304. }
  49305. };
  49306. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49307. var tm = BABYLON.Tmp.Matrix[0];
  49308. mesh.getWorldMatrix().invertToRef(tm);
  49309. if (this._tmpRay) {
  49310. Ray.TransformToRef(this, tm, this._tmpRay);
  49311. }
  49312. else {
  49313. this._tmpRay = Ray.Transform(this, tm);
  49314. }
  49315. return mesh.intersects(this._tmpRay, fastCheck);
  49316. };
  49317. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49318. if (results) {
  49319. results.length = 0;
  49320. }
  49321. else {
  49322. results = [];
  49323. }
  49324. for (var i = 0; i < meshes.length; i++) {
  49325. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49326. if (pickInfo.hit) {
  49327. results.push(pickInfo);
  49328. }
  49329. }
  49330. results.sort(this._comparePickingInfo);
  49331. return results;
  49332. };
  49333. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49334. if (pickingInfoA.distance < pickingInfoB.distance) {
  49335. return -1;
  49336. }
  49337. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49338. return 1;
  49339. }
  49340. else {
  49341. return 0;
  49342. }
  49343. };
  49344. /**
  49345. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49346. * @param sega the first point of the segment to test the intersection against
  49347. * @param segb the second point of the segment to test the intersection against
  49348. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49349. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49350. */
  49351. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49352. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49353. var u = segb.subtract(sega);
  49354. var v = rsegb.subtract(this.origin);
  49355. var w = sega.subtract(this.origin);
  49356. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49357. var b = BABYLON.Vector3.Dot(u, v);
  49358. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49359. var d = BABYLON.Vector3.Dot(u, w);
  49360. var e = BABYLON.Vector3.Dot(v, w);
  49361. var D = a * c - b * b; // always >= 0
  49362. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49363. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49364. // compute the line parameters of the two closest points
  49365. if (D < Ray.smallnum) {
  49366. sN = 0.0; // force using point P0 on segment S1
  49367. sD = 1.0; // to prevent possible division by 0.0 later
  49368. tN = e;
  49369. tD = c;
  49370. }
  49371. else {
  49372. sN = (b * e - c * d);
  49373. tN = (a * e - b * d);
  49374. if (sN < 0.0) {
  49375. sN = 0.0;
  49376. tN = e;
  49377. tD = c;
  49378. }
  49379. else if (sN > sD) {
  49380. sN = sD;
  49381. tN = e + b;
  49382. tD = c;
  49383. }
  49384. }
  49385. if (tN < 0.0) {
  49386. tN = 0.0;
  49387. // recompute sc for this edge
  49388. if (-d < 0.0) {
  49389. sN = 0.0;
  49390. }
  49391. else if (-d > a)
  49392. sN = sD;
  49393. else {
  49394. sN = -d;
  49395. sD = a;
  49396. }
  49397. }
  49398. else if (tN > tD) {
  49399. tN = tD;
  49400. // recompute sc for this edge
  49401. if ((-d + b) < 0.0) {
  49402. sN = 0;
  49403. }
  49404. else if ((-d + b) > a) {
  49405. sN = sD;
  49406. }
  49407. else {
  49408. sN = (-d + b);
  49409. sD = a;
  49410. }
  49411. }
  49412. // finally do the division to get sc and tc
  49413. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49414. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49415. // get the difference of the two closest points
  49416. var qtc = v.multiplyByFloats(tc, tc, tc);
  49417. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49418. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49419. if (isIntersected) {
  49420. return qtc.length();
  49421. }
  49422. return -1;
  49423. };
  49424. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49425. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49426. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49427. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49428. this.direction.normalize();
  49429. return this;
  49430. };
  49431. // Statics
  49432. Ray.Zero = function () {
  49433. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49434. };
  49435. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49436. var result = Ray.Zero();
  49437. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49438. };
  49439. /**
  49440. * 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
  49441. * transformed to the given world matrix.
  49442. * @param origin The origin point
  49443. * @param end The end point
  49444. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49445. */
  49446. Ray.CreateNewFromTo = function (origin, end, world) {
  49447. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49448. var direction = end.subtract(origin);
  49449. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49450. direction.normalize();
  49451. return Ray.Transform(new Ray(origin, direction, length), world);
  49452. };
  49453. Ray.Transform = function (ray, matrix) {
  49454. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49455. Ray.TransformToRef(ray, matrix, result);
  49456. return result;
  49457. };
  49458. Ray.TransformToRef = function (ray, matrix, result) {
  49459. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49460. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49461. result.length = ray.length;
  49462. var dir = result.direction;
  49463. var len = dir.length();
  49464. if (!(len === 0 || len === 1)) {
  49465. var num = 1.0 / len;
  49466. dir.x *= num;
  49467. dir.y *= num;
  49468. dir.z *= num;
  49469. result.length *= len;
  49470. }
  49471. };
  49472. Ray.smallnum = 0.00000001;
  49473. Ray.rayl = 10e8;
  49474. return Ray;
  49475. }());
  49476. BABYLON.Ray = Ray;
  49477. })(BABYLON || (BABYLON = {}));
  49478. //# sourceMappingURL=babylon.ray.js.map
  49479. var BABYLON;
  49480. (function (BABYLON) {
  49481. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49482. if (boxMin.x > sphereCenter.x + sphereRadius)
  49483. return false;
  49484. if (sphereCenter.x - sphereRadius > boxMax.x)
  49485. return false;
  49486. if (boxMin.y > sphereCenter.y + sphereRadius)
  49487. return false;
  49488. if (sphereCenter.y - sphereRadius > boxMax.y)
  49489. return false;
  49490. if (boxMin.z > sphereCenter.z + sphereRadius)
  49491. return false;
  49492. if (sphereCenter.z - sphereRadius > boxMax.z)
  49493. return false;
  49494. return true;
  49495. };
  49496. var getLowestRoot = (function () {
  49497. var result = { root: 0, found: false };
  49498. return function (a, b, c, maxR) {
  49499. result.root = 0;
  49500. result.found = false;
  49501. var determinant = b * b - 4.0 * a * c;
  49502. if (determinant < 0)
  49503. return result;
  49504. var sqrtD = Math.sqrt(determinant);
  49505. var r1 = (-b - sqrtD) / (2.0 * a);
  49506. var r2 = (-b + sqrtD) / (2.0 * a);
  49507. if (r1 > r2) {
  49508. var temp = r2;
  49509. r2 = r1;
  49510. r1 = temp;
  49511. }
  49512. if (r1 > 0 && r1 < maxR) {
  49513. result.root = r1;
  49514. result.found = true;
  49515. return result;
  49516. }
  49517. if (r2 > 0 && r2 < maxR) {
  49518. result.root = r2;
  49519. result.found = true;
  49520. return result;
  49521. }
  49522. return result;
  49523. };
  49524. })();
  49525. var Collider = /** @class */ (function () {
  49526. function Collider() {
  49527. this._collisionPoint = BABYLON.Vector3.Zero();
  49528. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49529. this._tempVector = BABYLON.Vector3.Zero();
  49530. this._tempVector2 = BABYLON.Vector3.Zero();
  49531. this._tempVector3 = BABYLON.Vector3.Zero();
  49532. this._tempVector4 = BABYLON.Vector3.Zero();
  49533. this._edge = BABYLON.Vector3.Zero();
  49534. this._baseToVertex = BABYLON.Vector3.Zero();
  49535. this._destinationPoint = BABYLON.Vector3.Zero();
  49536. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49537. this._displacementVector = BABYLON.Vector3.Zero();
  49538. this._radius = BABYLON.Vector3.One();
  49539. this._retry = 0;
  49540. this._basePointWorld = BABYLON.Vector3.Zero();
  49541. this._velocityWorld = BABYLON.Vector3.Zero();
  49542. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49543. this._collisionMask = -1;
  49544. }
  49545. Object.defineProperty(Collider.prototype, "collisionMask", {
  49546. get: function () {
  49547. return this._collisionMask;
  49548. },
  49549. set: function (mask) {
  49550. this._collisionMask = !isNaN(mask) ? mask : -1;
  49551. },
  49552. enumerable: true,
  49553. configurable: true
  49554. });
  49555. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49556. /**
  49557. * Gets the plane normal used to compute the sliding response (in local space)
  49558. */
  49559. get: function () {
  49560. return this._slidePlaneNormal;
  49561. },
  49562. enumerable: true,
  49563. configurable: true
  49564. });
  49565. // Methods
  49566. Collider.prototype._initialize = function (source, dir, e) {
  49567. this._velocity = dir;
  49568. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49569. this._basePoint = source;
  49570. source.multiplyToRef(this._radius, this._basePointWorld);
  49571. dir.multiplyToRef(this._radius, this._velocityWorld);
  49572. this._velocityWorldLength = this._velocityWorld.length();
  49573. this._epsilon = e;
  49574. this.collisionFound = false;
  49575. };
  49576. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49577. pa.subtractToRef(point, this._tempVector);
  49578. pb.subtractToRef(point, this._tempVector2);
  49579. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49580. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49581. if (d < 0)
  49582. return false;
  49583. pc.subtractToRef(point, this._tempVector3);
  49584. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49585. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49586. if (d < 0)
  49587. return false;
  49588. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49589. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49590. return d >= 0;
  49591. };
  49592. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49593. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49594. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49595. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49596. return false;
  49597. }
  49598. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49599. return false;
  49600. return true;
  49601. };
  49602. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49603. var t0;
  49604. var embeddedInPlane = false;
  49605. //defensive programming, actually not needed.
  49606. if (!trianglePlaneArray) {
  49607. trianglePlaneArray = [];
  49608. }
  49609. if (!trianglePlaneArray[faceIndex]) {
  49610. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49611. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49612. }
  49613. var trianglePlane = trianglePlaneArray[faceIndex];
  49614. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49615. return;
  49616. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49617. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49618. if (normalDotVelocity == 0) {
  49619. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49620. return;
  49621. embeddedInPlane = true;
  49622. t0 = 0;
  49623. }
  49624. else {
  49625. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49626. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49627. if (t0 > t1) {
  49628. var temp = t1;
  49629. t1 = t0;
  49630. t0 = temp;
  49631. }
  49632. if (t0 > 1.0 || t1 < 0.0)
  49633. return;
  49634. if (t0 < 0)
  49635. t0 = 0;
  49636. if (t0 > 1.0)
  49637. t0 = 1.0;
  49638. }
  49639. this._collisionPoint.copyFromFloats(0, 0, 0);
  49640. var found = false;
  49641. var t = 1.0;
  49642. if (!embeddedInPlane) {
  49643. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49644. this._velocity.scaleToRef(t0, this._tempVector);
  49645. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49646. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49647. found = true;
  49648. t = t0;
  49649. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49650. }
  49651. }
  49652. if (!found) {
  49653. var velocitySquaredLength = this._velocity.lengthSquared();
  49654. var a = velocitySquaredLength;
  49655. this._basePoint.subtractToRef(p1, this._tempVector);
  49656. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49657. var c = this._tempVector.lengthSquared() - 1.0;
  49658. var lowestRoot = getLowestRoot(a, b, c, t);
  49659. if (lowestRoot.found) {
  49660. t = lowestRoot.root;
  49661. found = true;
  49662. this._collisionPoint.copyFrom(p1);
  49663. }
  49664. this._basePoint.subtractToRef(p2, this._tempVector);
  49665. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49666. c = this._tempVector.lengthSquared() - 1.0;
  49667. lowestRoot = getLowestRoot(a, b, c, t);
  49668. if (lowestRoot.found) {
  49669. t = lowestRoot.root;
  49670. found = true;
  49671. this._collisionPoint.copyFrom(p2);
  49672. }
  49673. this._basePoint.subtractToRef(p3, this._tempVector);
  49674. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49675. c = this._tempVector.lengthSquared() - 1.0;
  49676. lowestRoot = getLowestRoot(a, b, c, t);
  49677. if (lowestRoot.found) {
  49678. t = lowestRoot.root;
  49679. found = true;
  49680. this._collisionPoint.copyFrom(p3);
  49681. }
  49682. p2.subtractToRef(p1, this._edge);
  49683. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49684. var edgeSquaredLength = this._edge.lengthSquared();
  49685. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49686. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49687. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49688. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49689. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49690. lowestRoot = getLowestRoot(a, b, c, t);
  49691. if (lowestRoot.found) {
  49692. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49693. if (f >= 0.0 && f <= 1.0) {
  49694. t = lowestRoot.root;
  49695. found = true;
  49696. this._edge.scaleInPlace(f);
  49697. p1.addToRef(this._edge, this._collisionPoint);
  49698. }
  49699. }
  49700. p3.subtractToRef(p2, this._edge);
  49701. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49702. edgeSquaredLength = this._edge.lengthSquared();
  49703. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49704. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49705. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49706. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49707. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49708. lowestRoot = getLowestRoot(a, b, c, t);
  49709. if (lowestRoot.found) {
  49710. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49711. if (f >= 0.0 && f <= 1.0) {
  49712. t = lowestRoot.root;
  49713. found = true;
  49714. this._edge.scaleInPlace(f);
  49715. p2.addToRef(this._edge, this._collisionPoint);
  49716. }
  49717. }
  49718. p1.subtractToRef(p3, this._edge);
  49719. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49720. edgeSquaredLength = this._edge.lengthSquared();
  49721. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49722. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49723. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49724. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49725. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49726. lowestRoot = getLowestRoot(a, b, c, t);
  49727. if (lowestRoot.found) {
  49728. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49729. if (f >= 0.0 && f <= 1.0) {
  49730. t = lowestRoot.root;
  49731. found = true;
  49732. this._edge.scaleInPlace(f);
  49733. p3.addToRef(this._edge, this._collisionPoint);
  49734. }
  49735. }
  49736. }
  49737. if (found) {
  49738. var distToCollision = t * this._velocity.length();
  49739. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49740. if (!this.intersectionPoint) {
  49741. this.intersectionPoint = this._collisionPoint.clone();
  49742. }
  49743. else {
  49744. this.intersectionPoint.copyFrom(this._collisionPoint);
  49745. }
  49746. this._nearestDistance = distToCollision;
  49747. this.collisionFound = true;
  49748. }
  49749. }
  49750. };
  49751. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49752. for (var i = indexStart; i < indexEnd; i += 3) {
  49753. var p1 = pts[indices[i] - decal];
  49754. var p2 = pts[indices[i + 1] - decal];
  49755. var p3 = pts[indices[i + 2] - decal];
  49756. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49757. }
  49758. };
  49759. Collider.prototype._getResponse = function (pos, vel) {
  49760. pos.addToRef(vel, this._destinationPoint);
  49761. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49762. this._basePoint.addToRef(vel, pos);
  49763. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49764. this._slidePlaneNormal.normalize();
  49765. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49766. pos.addInPlace(this._displacementVector);
  49767. this.intersectionPoint.addInPlace(this._displacementVector);
  49768. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49769. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49770. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49771. };
  49772. return Collider;
  49773. }());
  49774. BABYLON.Collider = Collider;
  49775. })(BABYLON || (BABYLON = {}));
  49776. //# sourceMappingURL=babylon.collider.js.map
  49777. var BABYLON;
  49778. (function (BABYLON) {
  49779. //WebWorker code will be inserted to this variable.
  49780. BABYLON.CollisionWorker = "";
  49781. var WorkerTaskType;
  49782. (function (WorkerTaskType) {
  49783. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49784. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49785. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49786. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49787. var WorkerReplyType;
  49788. (function (WorkerReplyType) {
  49789. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49790. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49791. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49792. var CollisionCoordinatorWorker = /** @class */ (function () {
  49793. function CollisionCoordinatorWorker() {
  49794. var _this = this;
  49795. this._scaledPosition = BABYLON.Vector3.Zero();
  49796. this._scaledVelocity = BABYLON.Vector3.Zero();
  49797. this.onMeshUpdated = function (transformNode) {
  49798. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49799. };
  49800. this.onGeometryUpdated = function (geometry) {
  49801. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49802. };
  49803. this._afterRender = function () {
  49804. if (!_this._init)
  49805. return;
  49806. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49807. return;
  49808. }
  49809. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49810. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49811. if (_this._runningUpdated > 4) {
  49812. return;
  49813. }
  49814. ++_this._runningUpdated;
  49815. var payload = {
  49816. updatedMeshes: _this._addUpdateMeshesList,
  49817. updatedGeometries: _this._addUpdateGeometriesList,
  49818. removedGeometries: _this._toRemoveGeometryArray,
  49819. removedMeshes: _this._toRemoveMeshesArray
  49820. };
  49821. var message = {
  49822. payload: payload,
  49823. taskType: WorkerTaskType.UPDATE
  49824. };
  49825. var serializable = [];
  49826. for (var id in payload.updatedGeometries) {
  49827. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49828. //prepare transferables
  49829. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49830. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49831. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49832. }
  49833. }
  49834. _this._worker.postMessage(message, serializable);
  49835. _this._addUpdateMeshesList = {};
  49836. _this._addUpdateGeometriesList = {};
  49837. _this._toRemoveGeometryArray = [];
  49838. _this._toRemoveMeshesArray = [];
  49839. };
  49840. this._onMessageFromWorker = function (e) {
  49841. var returnData = e.data;
  49842. if (returnData.error != WorkerReplyType.SUCCESS) {
  49843. //TODO what errors can be returned from the worker?
  49844. BABYLON.Tools.Warn("error returned from worker!");
  49845. return;
  49846. }
  49847. switch (returnData.taskType) {
  49848. case WorkerTaskType.INIT:
  49849. _this._init = true;
  49850. //Update the worked with ALL of the scene's current state
  49851. _this._scene.meshes.forEach(function (mesh) {
  49852. _this.onMeshAdded(mesh);
  49853. });
  49854. _this._scene.getGeometries().forEach(function (geometry) {
  49855. _this.onGeometryAdded(geometry);
  49856. });
  49857. break;
  49858. case WorkerTaskType.UPDATE:
  49859. _this._runningUpdated--;
  49860. break;
  49861. case WorkerTaskType.COLLIDE:
  49862. var returnPayload = returnData.payload;
  49863. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49864. return;
  49865. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49866. if (callback) {
  49867. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49868. if (mesh) {
  49869. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49870. }
  49871. }
  49872. //cleanup
  49873. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49874. break;
  49875. }
  49876. };
  49877. this._collisionsCallbackArray = [];
  49878. this._init = false;
  49879. this._runningUpdated = 0;
  49880. this._addUpdateMeshesList = {};
  49881. this._addUpdateGeometriesList = {};
  49882. this._toRemoveGeometryArray = [];
  49883. this._toRemoveMeshesArray = [];
  49884. }
  49885. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49886. if (!this._init)
  49887. return;
  49888. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49889. return;
  49890. position.divideToRef(collider._radius, this._scaledPosition);
  49891. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49892. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49893. var payload = {
  49894. collider: {
  49895. position: this._scaledPosition.asArray(),
  49896. velocity: this._scaledVelocity.asArray(),
  49897. radius: collider._radius.asArray()
  49898. },
  49899. collisionId: collisionIndex,
  49900. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49901. maximumRetry: maximumRetry
  49902. };
  49903. var message = {
  49904. payload: payload,
  49905. taskType: WorkerTaskType.COLLIDE
  49906. };
  49907. this._worker.postMessage(message);
  49908. };
  49909. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49910. this._scene = scene;
  49911. this._scene.registerAfterRender(this._afterRender);
  49912. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49913. this._worker = new Worker(workerUrl);
  49914. this._worker.onmessage = this._onMessageFromWorker;
  49915. var message = {
  49916. payload: {},
  49917. taskType: WorkerTaskType.INIT
  49918. };
  49919. this._worker.postMessage(message);
  49920. };
  49921. CollisionCoordinatorWorker.prototype.destroy = function () {
  49922. this._scene.unregisterAfterRender(this._afterRender);
  49923. this._worker.terminate();
  49924. };
  49925. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49926. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49927. this.onMeshUpdated(mesh);
  49928. };
  49929. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49930. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49931. };
  49932. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49933. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49934. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49935. this.onGeometryUpdated(geometry);
  49936. };
  49937. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49938. this._toRemoveGeometryArray.push(geometry.id);
  49939. };
  49940. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49941. var submeshes = [];
  49942. if (mesh.subMeshes) {
  49943. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49944. var boundingInfo = sm.getBoundingInfo();
  49945. return {
  49946. position: idx,
  49947. verticesStart: sm.verticesStart,
  49948. verticesCount: sm.verticesCount,
  49949. indexStart: sm.indexStart,
  49950. indexCount: sm.indexCount,
  49951. hasMaterial: !!sm.getMaterial(),
  49952. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49953. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49954. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49955. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49956. };
  49957. });
  49958. }
  49959. var geometryId = null;
  49960. if (mesh instanceof BABYLON.Mesh) {
  49961. var geometry = mesh.geometry;
  49962. geometryId = geometry ? geometry.id : null;
  49963. }
  49964. else if (mesh instanceof BABYLON.InstancedMesh) {
  49965. var geometry = mesh.sourceMesh.geometry;
  49966. geometryId = geometry ? geometry.id : null;
  49967. }
  49968. var boundingInfo = mesh.getBoundingInfo();
  49969. return {
  49970. uniqueId: mesh.uniqueId,
  49971. id: mesh.id,
  49972. name: mesh.name,
  49973. geometryId: geometryId,
  49974. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49975. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49976. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49977. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49978. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49979. subMeshes: submeshes,
  49980. checkCollisions: mesh.checkCollisions
  49981. };
  49982. };
  49983. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49984. return {
  49985. id: geometry.id,
  49986. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49987. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49988. indices: new Uint32Array(geometry.getIndices() || []),
  49989. };
  49990. };
  49991. return CollisionCoordinatorWorker;
  49992. }());
  49993. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49994. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49995. function CollisionCoordinatorLegacy() {
  49996. this._scaledPosition = BABYLON.Vector3.Zero();
  49997. this._scaledVelocity = BABYLON.Vector3.Zero();
  49998. this._finalPosition = BABYLON.Vector3.Zero();
  49999. }
  50000. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  50001. position.divideToRef(collider._radius, this._scaledPosition);
  50002. displacement.divideToRef(collider._radius, this._scaledVelocity);
  50003. collider.collidedMesh = null;
  50004. collider._retry = 0;
  50005. collider._initialVelocity = this._scaledVelocity;
  50006. collider._initialPosition = this._scaledPosition;
  50007. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  50008. this._finalPosition.multiplyInPlace(collider._radius);
  50009. //run the callback
  50010. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  50011. };
  50012. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  50013. this._scene = scene;
  50014. };
  50015. CollisionCoordinatorLegacy.prototype.destroy = function () {
  50016. //Legacy need no destruction method.
  50017. };
  50018. //No update in legacy mode
  50019. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  50020. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  50021. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  50022. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  50023. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  50024. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  50025. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  50026. if (excludedMesh === void 0) { excludedMesh = null; }
  50027. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  50028. if (collider._retry >= maximumRetry) {
  50029. finalPosition.copyFrom(position);
  50030. return;
  50031. }
  50032. // Check if this is a mesh else camera or -1
  50033. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  50034. collider._initialize(position, velocity, closeDistance);
  50035. // Check all meshes
  50036. for (var index = 0; index < this._scene.meshes.length; index++) {
  50037. var mesh = this._scene.meshes[index];
  50038. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  50039. mesh._checkCollision(collider);
  50040. }
  50041. }
  50042. if (!collider.collisionFound) {
  50043. position.addToRef(velocity, finalPosition);
  50044. return;
  50045. }
  50046. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  50047. collider._getResponse(position, velocity);
  50048. }
  50049. if (velocity.length() <= closeDistance) {
  50050. finalPosition.copyFrom(position);
  50051. return;
  50052. }
  50053. collider._retry++;
  50054. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  50055. };
  50056. return CollisionCoordinatorLegacy;
  50057. }());
  50058. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  50059. })(BABYLON || (BABYLON = {}));
  50060. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  50061. var BABYLON;
  50062. (function (BABYLON) {
  50063. /**
  50064. * A particle represents one of the element emitted by a particle system.
  50065. * This is mainly define by its coordinates, direction, velocity and age.
  50066. */
  50067. var Particle = /** @class */ (function () {
  50068. /**
  50069. * Creates a new instance of @see Particle
  50070. * @param particleSystem the particle system the particle belongs to
  50071. */
  50072. function Particle(particleSystem) {
  50073. this.particleSystem = particleSystem;
  50074. /**
  50075. * The world position of the particle in the scene.
  50076. */
  50077. this.position = BABYLON.Vector3.Zero();
  50078. /**
  50079. * The world direction of the particle in the scene.
  50080. */
  50081. this.direction = BABYLON.Vector3.Zero();
  50082. /**
  50083. * The color of the particle.
  50084. */
  50085. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50086. /**
  50087. * The color change of the particle per step.
  50088. */
  50089. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50090. /**
  50091. * Defines how long will the life of the particle be.
  50092. */
  50093. this.lifeTime = 1.0;
  50094. /**
  50095. * The current age of the particle.
  50096. */
  50097. this.age = 0;
  50098. /**
  50099. * The current size of the particle.
  50100. */
  50101. this.size = 0;
  50102. /**
  50103. * The current angle of the particle.
  50104. */
  50105. this.angle = 0;
  50106. /**
  50107. * Defines how fast is the angle changing.
  50108. */
  50109. this.angularSpeed = 0;
  50110. /**
  50111. * Defines the cell index used by the particle to be rendered from a sprite.
  50112. */
  50113. this.cellIndex = 0;
  50114. this._currentFrameCounter = 0;
  50115. if (!this.particleSystem.isAnimationSheetEnabled) {
  50116. return;
  50117. }
  50118. this.cellIndex = this.particleSystem.startSpriteCellID;
  50119. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50120. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50121. }
  50122. else {
  50123. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50124. }
  50125. }
  50126. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50127. // (ageOffset / scaledUpdateSpeed) / available cells
  50128. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50129. this._currentFrameCounter += scaledUpdateSpeed;
  50130. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50131. this._currentFrameCounter = 0;
  50132. this.cellIndex++;
  50133. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50134. this.cellIndex = this.particleSystem.endSpriteCellID;
  50135. }
  50136. }
  50137. };
  50138. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50139. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50140. this.cellIndex++;
  50141. this._currentFrameCounter = 0;
  50142. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50143. if (this.particleSystem.spriteCellLoop) {
  50144. this.cellIndex = this.particleSystem.startSpriteCellID;
  50145. }
  50146. else {
  50147. this.cellIndex = this.particleSystem.endSpriteCellID;
  50148. }
  50149. }
  50150. }
  50151. else {
  50152. this._currentFrameCounter++;
  50153. }
  50154. };
  50155. /**
  50156. * Copy the properties of particle to another one.
  50157. * @param other the particle to copy the information to.
  50158. */
  50159. Particle.prototype.copyTo = function (other) {
  50160. other.position.copyFrom(this.position);
  50161. other.direction.copyFrom(this.direction);
  50162. other.color.copyFrom(this.color);
  50163. other.colorStep.copyFrom(this.colorStep);
  50164. other.lifeTime = this.lifeTime;
  50165. other.age = this.age;
  50166. other.size = this.size;
  50167. other.angle = this.angle;
  50168. other.angularSpeed = this.angularSpeed;
  50169. other.particleSystem = this.particleSystem;
  50170. other.cellIndex = this.cellIndex;
  50171. };
  50172. return Particle;
  50173. }());
  50174. BABYLON.Particle = Particle;
  50175. })(BABYLON || (BABYLON = {}));
  50176. //# sourceMappingURL=babylon.particle.js.map
  50177. var BABYLON;
  50178. (function (BABYLON) {
  50179. /**
  50180. * This represents a particle system in Babylon.
  50181. * 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.
  50182. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50183. * @example https://doc.babylonjs.com/babylon101/particles
  50184. */
  50185. var ParticleSystem = /** @class */ (function () {
  50186. /**
  50187. * Instantiates a particle system.
  50188. * 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.
  50189. * @param name The name of the particle system
  50190. * @param capacity The max number of particles alive at the same time
  50191. * @param scene The scene the particle system belongs to
  50192. * @param customEffect a custom effect used to change the way particles are rendered by default
  50193. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50194. * @param epsilon Offset used to render the particles
  50195. */
  50196. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50197. if (customEffect === void 0) { customEffect = null; }
  50198. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50199. if (epsilon === void 0) { epsilon = 0.01; }
  50200. var _this = this;
  50201. /**
  50202. * List of animations used by the particle system.
  50203. */
  50204. this.animations = [];
  50205. /**
  50206. * The rendering group used by the Particle system to chose when to render.
  50207. */
  50208. this.renderingGroupId = 0;
  50209. /**
  50210. * The emitter represents the Mesh or position we are attaching the particle system to.
  50211. */
  50212. this.emitter = null;
  50213. /**
  50214. * The maximum number of particles to emit per frame
  50215. */
  50216. this.emitRate = 10;
  50217. /**
  50218. * If you want to launch only a few particles at once, that can be done, as well.
  50219. */
  50220. this.manualEmitCount = -1;
  50221. /**
  50222. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50223. */
  50224. this.updateSpeed = 0.01;
  50225. /**
  50226. * The amount of time the particle system is running (depends of the overall speed above).
  50227. */
  50228. this.targetStopDuration = 0;
  50229. /**
  50230. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50231. */
  50232. this.disposeOnStop = false;
  50233. /**
  50234. * Minimum power of emitting particles.
  50235. */
  50236. this.minEmitPower = 1;
  50237. /**
  50238. * Maximum power of emitting particles.
  50239. */
  50240. this.maxEmitPower = 1;
  50241. /**
  50242. * Minimum life time of emitting particles.
  50243. */
  50244. this.minLifeTime = 1;
  50245. /**
  50246. * Maximum life time of emitting particles.
  50247. */
  50248. this.maxLifeTime = 1;
  50249. /**
  50250. * Minimum Size of emitting particles.
  50251. */
  50252. this.minSize = 1;
  50253. /**
  50254. * Maximum Size of emitting particles.
  50255. */
  50256. this.maxSize = 1;
  50257. /**
  50258. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50259. */
  50260. this.minAngularSpeed = 0;
  50261. /**
  50262. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50263. */
  50264. this.maxAngularSpeed = 0;
  50265. /**
  50266. * The layer mask we are rendering the particles through.
  50267. */
  50268. this.layerMask = 0x0FFFFFFF;
  50269. /**
  50270. * This can help using your own shader to render the particle system.
  50271. * The according effect will be created
  50272. */
  50273. this.customShader = null;
  50274. /**
  50275. * By default particle system starts as soon as they are created. This prevents the
  50276. * automatic start to happen and let you decide when to start emitting particles.
  50277. */
  50278. this.preventAutoStart = false;
  50279. /**
  50280. * Callback triggered when the particle animation is ending.
  50281. */
  50282. this.onAnimationEnd = null;
  50283. /**
  50284. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50285. */
  50286. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50287. /**
  50288. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50289. * to override the particles.
  50290. */
  50291. this.forceDepthWrite = false;
  50292. /**
  50293. * You can use gravity if you want to give an orientation to your particles.
  50294. */
  50295. this.gravity = BABYLON.Vector3.Zero();
  50296. /**
  50297. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50298. */
  50299. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  50300. /**
  50301. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50302. */
  50303. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  50304. /**
  50305. * 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.
  50306. */
  50307. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  50308. /**
  50309. * 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.
  50310. */
  50311. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  50312. /**
  50313. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50314. */
  50315. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50316. /**
  50317. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50318. */
  50319. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50320. /**
  50321. * Color the particle will have at the end of its lifetime.
  50322. */
  50323. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50324. /**
  50325. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50326. */
  50327. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50328. /**
  50329. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50330. */
  50331. this.spriteCellLoop = true;
  50332. /**
  50333. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50334. */
  50335. this.spriteCellChangeSpeed = 0;
  50336. /**
  50337. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50338. */
  50339. this.startSpriteCellID = 0;
  50340. /**
  50341. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50342. */
  50343. this.endSpriteCellID = 0;
  50344. /**
  50345. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50346. */
  50347. this.spriteCellWidth = 0;
  50348. /**
  50349. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50350. */
  50351. this.spriteCellHeight = 0;
  50352. /**
  50353. * An event triggered when the system is disposed.
  50354. */
  50355. this.onDisposeObservable = new BABYLON.Observable();
  50356. this._particles = new Array();
  50357. this._stockParticles = new Array();
  50358. this._newPartsExcess = 0;
  50359. this._vertexBuffers = {};
  50360. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50361. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50362. this._scaledDirection = BABYLON.Vector3.Zero();
  50363. this._scaledGravity = BABYLON.Vector3.Zero();
  50364. this._currentRenderId = -1;
  50365. this._started = false;
  50366. this._stopped = false;
  50367. this._actualFrame = 0;
  50368. this._vertexBufferSize = 11;
  50369. this._appendParticleVertexes = null;
  50370. this.id = name;
  50371. this.name = name;
  50372. this._capacity = capacity;
  50373. this._epsilon = epsilon;
  50374. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50375. if (isAnimationSheetEnabled) {
  50376. this._vertexBufferSize = 12;
  50377. }
  50378. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50379. this._customEffect = customEffect;
  50380. scene.particleSystems.push(this);
  50381. this._createIndexBuffer();
  50382. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50383. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50384. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50385. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50386. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50387. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50388. if (this._isAnimationSheetEnabled) {
  50389. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50390. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50391. }
  50392. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50393. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50394. this._vertexBuffers["options"] = options;
  50395. // Default behaviors
  50396. this.particleEmitterType = new BABYLON.BoxParticleEmitter(this);
  50397. this.updateFunction = function (particles) {
  50398. for (var index = 0; index < particles.length; index++) {
  50399. var particle = particles[index];
  50400. particle.age += _this._scaledUpdateSpeed;
  50401. if (particle.age >= particle.lifeTime) {
  50402. _this.recycleParticle(particle);
  50403. index--;
  50404. continue;
  50405. }
  50406. else {
  50407. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50408. particle.color.addInPlace(_this._scaledColorStep);
  50409. if (particle.color.a < 0)
  50410. particle.color.a = 0;
  50411. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50412. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50413. particle.position.addInPlace(_this._scaledDirection);
  50414. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50415. particle.direction.addInPlace(_this._scaledGravity);
  50416. if (_this._isAnimationSheetEnabled) {
  50417. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50418. }
  50419. }
  50420. }
  50421. };
  50422. }
  50423. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50424. /**
  50425. * Sets a callback that will be triggered when the system is disposed.
  50426. */
  50427. set: function (callback) {
  50428. if (this._onDisposeObserver) {
  50429. this.onDisposeObservable.remove(this._onDisposeObserver);
  50430. }
  50431. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50432. },
  50433. enumerable: true,
  50434. configurable: true
  50435. });
  50436. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50437. /**
  50438. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50439. */
  50440. get: function () {
  50441. return this._isAnimationSheetEnabled;
  50442. },
  50443. enumerable: true,
  50444. configurable: true
  50445. });
  50446. ParticleSystem.prototype._createIndexBuffer = function () {
  50447. var indices = [];
  50448. var index = 0;
  50449. for (var count = 0; count < this._capacity; count++) {
  50450. indices.push(index);
  50451. indices.push(index + 1);
  50452. indices.push(index + 2);
  50453. indices.push(index);
  50454. indices.push(index + 2);
  50455. indices.push(index + 3);
  50456. index += 4;
  50457. }
  50458. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50459. };
  50460. /**
  50461. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50462. * Its lifetime will start back at 0.
  50463. * @param particle The particle to recycle
  50464. */
  50465. ParticleSystem.prototype.recycleParticle = function (particle) {
  50466. var lastParticle = this._particles.pop();
  50467. if (lastParticle !== particle) {
  50468. lastParticle.copyTo(particle);
  50469. this._stockParticles.push(lastParticle);
  50470. }
  50471. };
  50472. /**
  50473. * Gets the maximum number of particles active at the same time.
  50474. * @returns The max number of active particles.
  50475. */
  50476. ParticleSystem.prototype.getCapacity = function () {
  50477. return this._capacity;
  50478. };
  50479. /**
  50480. * Gets Wether there are still active particles in the system.
  50481. * @returns True if it is alive, otherwise false.
  50482. */
  50483. ParticleSystem.prototype.isAlive = function () {
  50484. return this._alive;
  50485. };
  50486. /**
  50487. * Gets Wether the system has been started.
  50488. * @returns True if it has been started, otherwise false.
  50489. */
  50490. ParticleSystem.prototype.isStarted = function () {
  50491. return this._started;
  50492. };
  50493. /**
  50494. * Starts the particle system and begins to emit.
  50495. */
  50496. ParticleSystem.prototype.start = function () {
  50497. this._started = true;
  50498. this._stopped = false;
  50499. this._actualFrame = 0;
  50500. };
  50501. /**
  50502. * Stops the particle system.
  50503. */
  50504. ParticleSystem.prototype.stop = function () {
  50505. this._stopped = true;
  50506. };
  50507. /**
  50508. * Remove all active particles
  50509. */
  50510. ParticleSystem.prototype.reset = function () {
  50511. this._stockParticles = [];
  50512. this._particles = [];
  50513. };
  50514. /**
  50515. * @ignore (for internal use only)
  50516. */
  50517. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50518. var offset = index * this._vertexBufferSize;
  50519. this._vertexData[offset] = particle.position.x;
  50520. this._vertexData[offset + 1] = particle.position.y;
  50521. this._vertexData[offset + 2] = particle.position.z;
  50522. this._vertexData[offset + 3] = particle.color.r;
  50523. this._vertexData[offset + 4] = particle.color.g;
  50524. this._vertexData[offset + 5] = particle.color.b;
  50525. this._vertexData[offset + 6] = particle.color.a;
  50526. this._vertexData[offset + 7] = particle.angle;
  50527. this._vertexData[offset + 8] = particle.size;
  50528. this._vertexData[offset + 9] = offsetX;
  50529. this._vertexData[offset + 10] = offsetY;
  50530. };
  50531. /**
  50532. * @ignore (for internal use only)
  50533. */
  50534. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50535. if (offsetX === 0)
  50536. offsetX = this._epsilon;
  50537. else if (offsetX === 1)
  50538. offsetX = 1 - this._epsilon;
  50539. if (offsetY === 0)
  50540. offsetY = this._epsilon;
  50541. else if (offsetY === 1)
  50542. offsetY = 1 - this._epsilon;
  50543. var offset = index * this._vertexBufferSize;
  50544. this._vertexData[offset] = particle.position.x;
  50545. this._vertexData[offset + 1] = particle.position.y;
  50546. this._vertexData[offset + 2] = particle.position.z;
  50547. this._vertexData[offset + 3] = particle.color.r;
  50548. this._vertexData[offset + 4] = particle.color.g;
  50549. this._vertexData[offset + 5] = particle.color.b;
  50550. this._vertexData[offset + 6] = particle.color.a;
  50551. this._vertexData[offset + 7] = particle.angle;
  50552. this._vertexData[offset + 8] = particle.size;
  50553. this._vertexData[offset + 9] = offsetX;
  50554. this._vertexData[offset + 10] = offsetY;
  50555. this._vertexData[offset + 11] = particle.cellIndex;
  50556. };
  50557. ParticleSystem.prototype._update = function (newParticles) {
  50558. // Update current
  50559. this._alive = this._particles.length > 0;
  50560. this.updateFunction(this._particles);
  50561. // Add new ones
  50562. var worldMatrix;
  50563. if (this.emitter.position) {
  50564. var emitterMesh = this.emitter;
  50565. worldMatrix = emitterMesh.getWorldMatrix();
  50566. }
  50567. else {
  50568. var emitterPosition = this.emitter;
  50569. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50570. }
  50571. var particle;
  50572. for (var index = 0; index < newParticles; index++) {
  50573. if (this._particles.length === this._capacity) {
  50574. break;
  50575. }
  50576. if (this._stockParticles.length !== 0) {
  50577. particle = this._stockParticles.pop();
  50578. particle.age = 0;
  50579. particle.cellIndex = this.startSpriteCellID;
  50580. }
  50581. else {
  50582. particle = new BABYLON.Particle(this);
  50583. }
  50584. this._particles.push(particle);
  50585. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50586. if (this.startPositionFunction) {
  50587. this.startPositionFunction(worldMatrix, particle.position, particle);
  50588. }
  50589. else {
  50590. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50591. }
  50592. if (this.startDirectionFunction) {
  50593. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50594. }
  50595. else {
  50596. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50597. }
  50598. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50599. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50600. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50601. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50602. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50603. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50604. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50605. }
  50606. };
  50607. ParticleSystem.prototype._getEffect = function () {
  50608. if (this._customEffect) {
  50609. return this._customEffect;
  50610. }
  50611. ;
  50612. var defines = [];
  50613. if (this._scene.clipPlane) {
  50614. defines.push("#define CLIPPLANE");
  50615. }
  50616. if (this._isAnimationSheetEnabled) {
  50617. defines.push("#define ANIMATESHEET");
  50618. }
  50619. // Effect
  50620. var join = defines.join("\n");
  50621. if (this._cachedDefines !== join) {
  50622. this._cachedDefines = join;
  50623. var attributesNamesOrOptions;
  50624. var effectCreationOption;
  50625. if (this._isAnimationSheetEnabled) {
  50626. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50627. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50628. }
  50629. else {
  50630. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50631. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50632. }
  50633. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50634. }
  50635. return this._effect;
  50636. };
  50637. /**
  50638. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50639. */
  50640. ParticleSystem.prototype.animate = function () {
  50641. if (!this._started)
  50642. return;
  50643. var effect = this._getEffect();
  50644. // Check
  50645. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50646. return;
  50647. if (this._currentRenderId === this._scene.getRenderId()) {
  50648. return;
  50649. }
  50650. this._currentRenderId = this._scene.getRenderId();
  50651. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50652. // determine the number of particles we need to create
  50653. var newParticles;
  50654. if (this.manualEmitCount > -1) {
  50655. newParticles = this.manualEmitCount;
  50656. this._newPartsExcess = 0;
  50657. this.manualEmitCount = 0;
  50658. }
  50659. else {
  50660. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50661. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50662. }
  50663. if (this._newPartsExcess > 1.0) {
  50664. newParticles += this._newPartsExcess >> 0;
  50665. this._newPartsExcess -= this._newPartsExcess >> 0;
  50666. }
  50667. this._alive = false;
  50668. if (!this._stopped) {
  50669. this._actualFrame += this._scaledUpdateSpeed;
  50670. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50671. this.stop();
  50672. }
  50673. else {
  50674. newParticles = 0;
  50675. }
  50676. this._update(newParticles);
  50677. // Stopped?
  50678. if (this._stopped) {
  50679. if (!this._alive) {
  50680. this._started = false;
  50681. if (this.onAnimationEnd) {
  50682. this.onAnimationEnd();
  50683. }
  50684. if (this.disposeOnStop) {
  50685. this._scene._toBeDisposed.push(this);
  50686. }
  50687. }
  50688. }
  50689. // Animation sheet
  50690. if (this._isAnimationSheetEnabled) {
  50691. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50692. }
  50693. else {
  50694. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50695. }
  50696. // Update VBO
  50697. var offset = 0;
  50698. for (var index = 0; index < this._particles.length; index++) {
  50699. var particle = this._particles[index];
  50700. this._appendParticleVertexes(offset, particle);
  50701. offset += 4;
  50702. }
  50703. if (this._vertexBuffer) {
  50704. this._vertexBuffer.update(this._vertexData);
  50705. }
  50706. };
  50707. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50708. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50709. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50710. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50711. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50712. };
  50713. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50714. this._appendParticleVertex(offset++, particle, 0, 0);
  50715. this._appendParticleVertex(offset++, particle, 1, 0);
  50716. this._appendParticleVertex(offset++, particle, 1, 1);
  50717. this._appendParticleVertex(offset++, particle, 0, 1);
  50718. };
  50719. /**
  50720. * Rebuilds the particle system.
  50721. */
  50722. ParticleSystem.prototype.rebuild = function () {
  50723. this._createIndexBuffer();
  50724. if (this._vertexBuffer) {
  50725. this._vertexBuffer._rebuild();
  50726. }
  50727. };
  50728. /**
  50729. * Renders the particle system in its current state.
  50730. * @returns the current number of particles.
  50731. */
  50732. ParticleSystem.prototype.render = function () {
  50733. var effect = this._getEffect();
  50734. // Check
  50735. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length)
  50736. return 0;
  50737. var engine = this._scene.getEngine();
  50738. // Render
  50739. engine.enableEffect(effect);
  50740. engine.setState(false);
  50741. var viewMatrix = this._scene.getViewMatrix();
  50742. effect.setTexture("diffuseSampler", this.particleTexture);
  50743. effect.setMatrix("view", viewMatrix);
  50744. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50745. if (this._isAnimationSheetEnabled) {
  50746. var baseSize = this.particleTexture.getBaseSize();
  50747. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50748. }
  50749. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50750. if (this._scene.clipPlane) {
  50751. var clipPlane = this._scene.clipPlane;
  50752. var invView = viewMatrix.clone();
  50753. invView.invert();
  50754. effect.setMatrix("invView", invView);
  50755. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50756. }
  50757. // VBOs
  50758. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50759. // Draw order
  50760. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50761. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50762. }
  50763. else {
  50764. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50765. }
  50766. if (this.forceDepthWrite) {
  50767. engine.setDepthWrite(true);
  50768. }
  50769. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50770. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50771. return this._particles.length;
  50772. };
  50773. /**
  50774. * Disposes the particle system and free the associated resources.
  50775. */
  50776. ParticleSystem.prototype.dispose = function () {
  50777. if (this._vertexBuffer) {
  50778. this._vertexBuffer.dispose();
  50779. this._vertexBuffer = null;
  50780. }
  50781. if (this._indexBuffer) {
  50782. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50783. this._indexBuffer = null;
  50784. }
  50785. if (this.particleTexture) {
  50786. this.particleTexture.dispose();
  50787. this.particleTexture = null;
  50788. }
  50789. // Remove from scene
  50790. var index = this._scene.particleSystems.indexOf(this);
  50791. if (index > -1) {
  50792. this._scene.particleSystems.splice(index, 1);
  50793. }
  50794. // Callback
  50795. this.onDisposeObservable.notifyObservers(this);
  50796. this.onDisposeObservable.clear();
  50797. };
  50798. /**
  50799. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50800. * @param radius The radius of the sphere to emit from
  50801. * @returns the emitter
  50802. */
  50803. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50804. if (radius === void 0) { radius = 1; }
  50805. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50806. this.particleEmitterType = particleEmitter;
  50807. return particleEmitter;
  50808. };
  50809. /**
  50810. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50811. * @param radius The radius of the sphere to emit from
  50812. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50813. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50814. * @returns the emitter
  50815. */
  50816. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50817. if (radius === void 0) { radius = 1; }
  50818. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50819. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50820. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50821. this.particleEmitterType = particleEmitter;
  50822. return particleEmitter;
  50823. };
  50824. /**
  50825. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50826. * @param radius The radius of the cone to emit from
  50827. * @param angle The base angle of the cone
  50828. * @returns the emitter
  50829. */
  50830. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50831. if (radius === void 0) { radius = 1; }
  50832. if (angle === void 0) { angle = Math.PI / 4; }
  50833. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50834. this.particleEmitterType = particleEmitter;
  50835. return particleEmitter;
  50836. };
  50837. // 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.
  50838. /**
  50839. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50840. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50841. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50842. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50843. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50844. * @returns the emitter
  50845. */
  50846. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50847. var particleEmitter = new BABYLON.BoxParticleEmitter(this);
  50848. this.direction1 = direction1;
  50849. this.direction2 = direction2;
  50850. this.minEmitBox = minEmitBox;
  50851. this.maxEmitBox = maxEmitBox;
  50852. this.particleEmitterType = particleEmitter;
  50853. return particleEmitter;
  50854. };
  50855. /**
  50856. * Clones the particle system.
  50857. * @param name The name of the cloned object
  50858. * @param newEmitter The new emitter to use
  50859. * @returns the cloned particle system
  50860. */
  50861. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50862. var custom = null;
  50863. var program = null;
  50864. if (this.customShader != null) {
  50865. program = this.customShader;
  50866. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50867. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50868. }
  50869. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50870. result.customShader = program;
  50871. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50872. if (newEmitter === undefined) {
  50873. newEmitter = this.emitter;
  50874. }
  50875. result.emitter = newEmitter;
  50876. if (this.particleTexture) {
  50877. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50878. }
  50879. if (!this.preventAutoStart) {
  50880. result.start();
  50881. }
  50882. return result;
  50883. };
  50884. /**
  50885. * Serializes the particle system to a JSON object.
  50886. * @returns the JSON object
  50887. */
  50888. ParticleSystem.prototype.serialize = function () {
  50889. var serializationObject = {};
  50890. serializationObject.name = this.name;
  50891. serializationObject.id = this.id;
  50892. // Emitter
  50893. if (this.emitter.position) {
  50894. var emitterMesh = this.emitter;
  50895. serializationObject.emitterId = emitterMesh.id;
  50896. }
  50897. else {
  50898. var emitterPosition = this.emitter;
  50899. serializationObject.emitter = emitterPosition.asArray();
  50900. }
  50901. serializationObject.capacity = this.getCapacity();
  50902. if (this.particleTexture) {
  50903. serializationObject.textureName = this.particleTexture.name;
  50904. }
  50905. // Animations
  50906. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50907. // Particle system
  50908. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50909. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50910. serializationObject.minSize = this.minSize;
  50911. serializationObject.maxSize = this.maxSize;
  50912. serializationObject.minEmitPower = this.minEmitPower;
  50913. serializationObject.maxEmitPower = this.maxEmitPower;
  50914. serializationObject.minLifeTime = this.minLifeTime;
  50915. serializationObject.maxLifeTime = this.maxLifeTime;
  50916. serializationObject.emitRate = this.emitRate;
  50917. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50918. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50919. serializationObject.gravity = this.gravity.asArray();
  50920. serializationObject.direction1 = this.direction1.asArray();
  50921. serializationObject.direction2 = this.direction2.asArray();
  50922. serializationObject.color1 = this.color1.asArray();
  50923. serializationObject.color2 = this.color2.asArray();
  50924. serializationObject.colorDead = this.colorDead.asArray();
  50925. serializationObject.updateSpeed = this.updateSpeed;
  50926. serializationObject.targetStopDuration = this.targetStopDuration;
  50927. serializationObject.textureMask = this.textureMask.asArray();
  50928. serializationObject.blendMode = this.blendMode;
  50929. serializationObject.customShader = this.customShader;
  50930. serializationObject.preventAutoStart = this.preventAutoStart;
  50931. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50932. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50933. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50934. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50935. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50936. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50937. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50938. return serializationObject;
  50939. };
  50940. /**
  50941. * Parses a JSON object to create a particle system.
  50942. * @param parsedParticleSystem The JSON object to parse
  50943. * @param scene The scene to create the particle system in
  50944. * @param rootUrl The root url to use to load external dependencies like texture
  50945. * @returns the Parsed particle system
  50946. */
  50947. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50948. var name = parsedParticleSystem.name;
  50949. var custom = null;
  50950. var program = null;
  50951. if (parsedParticleSystem.customShader) {
  50952. program = parsedParticleSystem.customShader;
  50953. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50954. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50955. }
  50956. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50957. particleSystem.customShader = program;
  50958. if (parsedParticleSystem.id) {
  50959. particleSystem.id = parsedParticleSystem.id;
  50960. }
  50961. // Auto start
  50962. if (parsedParticleSystem.preventAutoStart) {
  50963. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50964. }
  50965. // Texture
  50966. if (parsedParticleSystem.textureName) {
  50967. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50968. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50969. }
  50970. // Emitter
  50971. if (parsedParticleSystem.emitterId) {
  50972. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50973. }
  50974. else {
  50975. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50976. }
  50977. // Animations
  50978. if (parsedParticleSystem.animations) {
  50979. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50980. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50981. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50982. }
  50983. }
  50984. if (parsedParticleSystem.autoAnimate) {
  50985. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50986. }
  50987. // Particle system
  50988. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50989. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50990. particleSystem.minSize = parsedParticleSystem.minSize;
  50991. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50992. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50993. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50994. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50995. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50996. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50997. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50998. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50999. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  51000. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  51001. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  51002. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  51003. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  51004. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51005. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51006. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51007. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51008. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51009. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51010. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51011. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51012. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51013. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51014. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51015. if (!particleSystem.preventAutoStart) {
  51016. particleSystem.start();
  51017. }
  51018. return particleSystem;
  51019. };
  51020. /**
  51021. * Source color is added to the destination color without alpha affecting the result.
  51022. */
  51023. ParticleSystem.BLENDMODE_ONEONE = 0;
  51024. /**
  51025. * Blend current color and particle color using particle’s alpha.
  51026. */
  51027. ParticleSystem.BLENDMODE_STANDARD = 1;
  51028. return ParticleSystem;
  51029. }());
  51030. BABYLON.ParticleSystem = ParticleSystem;
  51031. })(BABYLON || (BABYLON = {}));
  51032. //# sourceMappingURL=babylon.particleSystem.js.map
  51033. var BABYLON;
  51034. (function (BABYLON) {
  51035. /**
  51036. * Particle emitter emitting particles from the inside of a box.
  51037. * It emits the particles randomly between 2 given directions.
  51038. */
  51039. var BoxParticleEmitter = /** @class */ (function () {
  51040. // to be updated like the rest of emitters when breaking changes.
  51041. // all property should be come public variables and passed through constructor.
  51042. /**
  51043. * Creates a new instance of @see BoxParticleEmitter
  51044. * @param _particleSystem the particle system associated with the emitter
  51045. */
  51046. function BoxParticleEmitter(_particleSystem) {
  51047. this._particleSystem = _particleSystem;
  51048. }
  51049. Object.defineProperty(BoxParticleEmitter.prototype, "direction1", {
  51050. /**
  51051. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51052. */
  51053. get: function () {
  51054. return this._particleSystem.direction1;
  51055. },
  51056. /**
  51057. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51058. */
  51059. set: function (value) {
  51060. this._particleSystem.direction1 = value;
  51061. },
  51062. enumerable: true,
  51063. configurable: true
  51064. });
  51065. Object.defineProperty(BoxParticleEmitter.prototype, "direction2", {
  51066. /**
  51067. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51068. */
  51069. get: function () {
  51070. return this._particleSystem.direction2;
  51071. },
  51072. /**
  51073. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51074. */
  51075. set: function (value) {
  51076. this._particleSystem.direction2 = value;
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. Object.defineProperty(BoxParticleEmitter.prototype, "minEmitBox", {
  51082. /**
  51083. * 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.
  51084. */
  51085. get: function () {
  51086. return this._particleSystem.minEmitBox;
  51087. },
  51088. /**
  51089. * 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.
  51090. */
  51091. set: function (value) {
  51092. this._particleSystem.minEmitBox = value;
  51093. },
  51094. enumerable: true,
  51095. configurable: true
  51096. });
  51097. Object.defineProperty(BoxParticleEmitter.prototype, "maxEmitBox", {
  51098. /**
  51099. * 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.
  51100. */
  51101. get: function () {
  51102. return this._particleSystem.maxEmitBox;
  51103. },
  51104. /**
  51105. * 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.
  51106. */
  51107. set: function (value) {
  51108. this._particleSystem.maxEmitBox = value;
  51109. },
  51110. enumerable: true,
  51111. configurable: true
  51112. });
  51113. /**
  51114. * Called by the particle System when the direction is computed for the created particle.
  51115. * @param emitPower is the power of the particle (speed)
  51116. * @param worldMatrix is the world matrix of the particle system
  51117. * @param directionToUpdate is the direction vector to update with the result
  51118. * @param particle is the particle we are computed the direction for
  51119. */
  51120. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51121. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51122. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51123. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51124. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51125. };
  51126. /**
  51127. * Called by the particle System when the position is computed for the created particle.
  51128. * @param worldMatrix is the world matrix of the particle system
  51129. * @param positionToUpdate is the position vector to update with the result
  51130. * @param particle is the particle we are computed the position for
  51131. */
  51132. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51133. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51134. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51135. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51136. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51137. };
  51138. /**
  51139. * Clones the current emitter and returns a copy of it
  51140. * @returns the new emitter
  51141. */
  51142. BoxParticleEmitter.prototype.clone = function () {
  51143. var newOne = new BoxParticleEmitter(this._particleSystem);
  51144. BABYLON.Tools.DeepCopy(this, newOne);
  51145. return newOne;
  51146. };
  51147. return BoxParticleEmitter;
  51148. }());
  51149. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51150. })(BABYLON || (BABYLON = {}));
  51151. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51152. var BABYLON;
  51153. (function (BABYLON) {
  51154. /**
  51155. * Particle emitter emitting particles from the inside of a cone.
  51156. * It emits the particles alongside the cone volume from the base to the particle.
  51157. * The emission direction might be randomized.
  51158. */
  51159. var ConeParticleEmitter = /** @class */ (function () {
  51160. /**
  51161. * Creates a new instance of @see ConeParticleEmitter
  51162. * @param radius the radius of the emission cone
  51163. * @param angles the cone base angle
  51164. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51165. */
  51166. function ConeParticleEmitter(radius,
  51167. /**
  51168. * The radius of the emission cone.
  51169. */
  51170. angle,
  51171. /**
  51172. * The cone base angle.
  51173. */
  51174. directionRandomizer) {
  51175. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51176. this.angle = angle;
  51177. this.directionRandomizer = directionRandomizer;
  51178. this.radius = radius;
  51179. }
  51180. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51181. /**
  51182. * Gets the radius of the emission cone.
  51183. */
  51184. get: function () {
  51185. return this._radius;
  51186. },
  51187. /**
  51188. * Sets the radius of the emission cone.
  51189. */
  51190. set: function (value) {
  51191. this._radius = value;
  51192. if (this.angle !== 0) {
  51193. this._height = value / Math.tan(this.angle / 2);
  51194. }
  51195. else {
  51196. this._height = 1;
  51197. }
  51198. },
  51199. enumerable: true,
  51200. configurable: true
  51201. });
  51202. /**
  51203. * Called by the particle System when the direction is computed for the created particle.
  51204. * @param emitPower is the power of the particle (speed)
  51205. * @param worldMatrix is the world matrix of the particle system
  51206. * @param directionToUpdate is the direction vector to update with the result
  51207. * @param particle is the particle we are computed the direction for
  51208. */
  51209. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51210. if (this.angle === 0) {
  51211. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51212. }
  51213. else {
  51214. // measure the direction Vector from the emitter to the particle.
  51215. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51216. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51217. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51218. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51219. direction.x += randX;
  51220. direction.y += randY;
  51221. direction.z += randZ;
  51222. direction.normalize();
  51223. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51224. }
  51225. };
  51226. /**
  51227. * Called by the particle System when the position is computed for the created particle.
  51228. * @param worldMatrix is the world matrix of the particle system
  51229. * @param positionToUpdate is the position vector to update with the result
  51230. * @param particle is the particle we are computed the position for
  51231. */
  51232. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51233. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51234. var h = BABYLON.Scalar.RandomRange(0, 1);
  51235. // Better distribution in a cone at normal angles.
  51236. h = 1 - h * h;
  51237. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51238. radius = radius * h / this._height;
  51239. var randX = radius * Math.sin(s);
  51240. var randZ = radius * Math.cos(s);
  51241. var randY = h;
  51242. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51243. };
  51244. /**
  51245. * Clones the current emitter and returns a copy of it
  51246. * @returns the new emitter
  51247. */
  51248. ConeParticleEmitter.prototype.clone = function () {
  51249. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51250. BABYLON.Tools.DeepCopy(this, newOne);
  51251. return newOne;
  51252. };
  51253. return ConeParticleEmitter;
  51254. }());
  51255. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51256. })(BABYLON || (BABYLON = {}));
  51257. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51258. var BABYLON;
  51259. (function (BABYLON) {
  51260. /**
  51261. * Particle emitter emitting particles from the inside of a sphere.
  51262. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51263. */
  51264. var SphereParticleEmitter = /** @class */ (function () {
  51265. /**
  51266. * Creates a new instance of @see SphereParticleEmitter
  51267. * @param radius the radius of the emission sphere
  51268. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51269. */
  51270. function SphereParticleEmitter(
  51271. /**
  51272. * The radius of the emission sphere.
  51273. */
  51274. radius,
  51275. /**
  51276. * How much to randomize the particle direction [0-1].
  51277. */
  51278. directionRandomizer) {
  51279. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51280. this.radius = radius;
  51281. this.directionRandomizer = directionRandomizer;
  51282. }
  51283. /**
  51284. * Called by the particle System when the direction is computed for the created particle.
  51285. * @param emitPower is the power of the particle (speed)
  51286. * @param worldMatrix is the world matrix of the particle system
  51287. * @param directionToUpdate is the direction vector to update with the result
  51288. * @param particle is the particle we are computed the direction for
  51289. */
  51290. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51291. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51292. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51293. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51294. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51295. direction.x += randX;
  51296. direction.y += randY;
  51297. direction.z += randZ;
  51298. direction.normalize();
  51299. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51300. };
  51301. /**
  51302. * Called by the particle System when the position is computed for the created particle.
  51303. * @param worldMatrix is the world matrix of the particle system
  51304. * @param positionToUpdate is the position vector to update with the result
  51305. * @param particle is the particle we are computed the position for
  51306. */
  51307. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51308. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51309. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51310. var randX = this.radius * Math.cos(phi) * Math.sin(theta);
  51311. var randY = this.radius * Math.cos(theta);
  51312. var randZ = this.radius * Math.sin(phi) * Math.sin(theta);
  51313. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51314. };
  51315. /**
  51316. * Clones the current emitter and returns a copy of it
  51317. * @returns the new emitter
  51318. */
  51319. SphereParticleEmitter.prototype.clone = function () {
  51320. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51321. BABYLON.Tools.DeepCopy(this, newOne);
  51322. return newOne;
  51323. };
  51324. return SphereParticleEmitter;
  51325. }());
  51326. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51327. /**
  51328. * Particle emitter emitting particles from the inside of a sphere.
  51329. * It emits the particles randomly between two vectors.
  51330. */
  51331. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51332. __extends(SphereDirectedParticleEmitter, _super);
  51333. /**
  51334. * Creates a new instance of @see SphereDirectedParticleEmitter
  51335. * @param radius the radius of the emission sphere
  51336. * @param direction1 the min limit of the emission direction
  51337. * @param direction2 the max limit of the emission direction
  51338. */
  51339. function SphereDirectedParticleEmitter(radius,
  51340. /**
  51341. * The min limit of the emission direction.
  51342. */
  51343. direction1,
  51344. /**
  51345. * The max limit of the emission direction.
  51346. */
  51347. direction2) {
  51348. var _this = _super.call(this, radius) || this;
  51349. _this.direction1 = direction1;
  51350. _this.direction2 = direction2;
  51351. return _this;
  51352. }
  51353. /**
  51354. * Called by the particle System when the direction is computed for the created particle.
  51355. * @param emitPower is the power of the particle (speed)
  51356. * @param worldMatrix is the world matrix of the particle system
  51357. * @param directionToUpdate is the direction vector to update with the result
  51358. * @param particle is the particle we are computed the direction for
  51359. */
  51360. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51361. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51362. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51363. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51364. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51365. };
  51366. /**
  51367. * Clones the current emitter and returns a copy of it
  51368. * @returns the new emitter
  51369. */
  51370. SphereDirectedParticleEmitter.prototype.clone = function () {
  51371. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51372. BABYLON.Tools.DeepCopy(this, newOne);
  51373. return newOne;
  51374. };
  51375. return SphereDirectedParticleEmitter;
  51376. }(SphereParticleEmitter));
  51377. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51378. })(BABYLON || (BABYLON = {}));
  51379. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51380. //# sourceMappingURL=babylon.iParticleEmitterType.js.map
  51381. var BABYLON;
  51382. (function (BABYLON) {
  51383. /**
  51384. * This represents a GPU particle system in Babylon.
  51385. * This os the fastest particle system in Babylon as it uses the GPU to update the individual particle data.
  51386. */
  51387. var GPUParticleSystem = /** @class */ (function () {
  51388. /**
  51389. * Instantiates a GPU particle system.
  51390. * 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.
  51391. * @param name The name of the particle system
  51392. * @param capacity The max number of particles alive at the same time
  51393. * @param scene The scene the particle system belongs to
  51394. */
  51395. function GPUParticleSystem(name, capacity, scene) {
  51396. /**
  51397. * The emitter represents the Mesh or position we are attaching the particle system to.
  51398. */
  51399. this.emitter = null;
  51400. /**
  51401. * The rendering group used by the Particle system to chose when to render.
  51402. */
  51403. this.renderingGroupId = 0;
  51404. /**
  51405. * The layer mask we are rendering the particles through.
  51406. */
  51407. this.layerMask = 0x0FFFFFFF; // TODO
  51408. this._updateVAO = new Array();
  51409. this._renderVAO = new Array();
  51410. this._targetIndex = 0;
  51411. this._currentRenderId = -1;
  51412. this._started = false;
  51413. this._timeDelta = 0;
  51414. this._attributesStrideSize = 14;
  51415. /**
  51416. * An event triggered when the system is disposed.
  51417. */
  51418. this.onDisposeObservable = new BABYLON.Observable();
  51419. /**
  51420. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51421. */
  51422. this.updateSpeed = 0.01;
  51423. /**
  51424. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51425. */
  51426. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  51427. /**
  51428. * Minimum life time of emitting particles.
  51429. */
  51430. this.minLifeTime = 1;
  51431. /**
  51432. * Maximum life time of emitting particles.
  51433. */
  51434. this.maxLifeTime = 1;
  51435. /**
  51436. * Minimum Size of emitting particles.
  51437. */
  51438. this.minSize = 1;
  51439. /**
  51440. * Maximum Size of emitting particles.
  51441. */
  51442. this.maxSize = 1;
  51443. /**
  51444. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51445. */
  51446. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51447. /**
  51448. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51449. */
  51450. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51451. /**
  51452. * Color the particle will have at the end of its lifetime.
  51453. */
  51454. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  51455. /**
  51456. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  51457. */
  51458. this.emitRate = 100;
  51459. /**
  51460. * You can use gravity if you want to give an orientation to your particles.
  51461. */
  51462. this.gravity = BABYLON.Vector3.Zero();
  51463. this.id = name;
  51464. this.name = name;
  51465. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51466. this._capacity = capacity;
  51467. this._activeCount = capacity;
  51468. this._currentActiveCount = 0;
  51469. this._engine = this._scene.getEngine();
  51470. this._scene.particleSystems.push(this);
  51471. var updateEffectOptions = {
  51472. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  51473. uniformsNames: ["currentCount", "timeDelta", "generalRandom", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity"],
  51474. uniformBuffersNames: [],
  51475. samplers: ["randomSampler"],
  51476. defines: "",
  51477. fallbacks: null,
  51478. onCompiled: null,
  51479. onError: null,
  51480. indexParameters: null,
  51481. maxSimultaneousLights: 0,
  51482. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  51483. };
  51484. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  51485. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead"], ["textureSampler"], this._scene.getEngine());
  51486. // Random data
  51487. var maxTextureSize = this._engine.getCaps().maxTextureSize;
  51488. var d = [];
  51489. for (var i = 0; i < maxTextureSize; ++i) {
  51490. d.push(Math.random());
  51491. d.push(Math.random());
  51492. d.push(Math.random());
  51493. }
  51494. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGB32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  51495. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51496. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51497. }
  51498. Object.defineProperty(GPUParticleSystem.prototype, "capacity", {
  51499. /**
  51500. * Gets the maximum number of particles supported by this system
  51501. */
  51502. get: function () {
  51503. return this._capacity;
  51504. },
  51505. enumerable: true,
  51506. configurable: true
  51507. });
  51508. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  51509. /**
  51510. * Gets or set the number of active particles
  51511. */
  51512. get: function () {
  51513. return this._activeCount;
  51514. },
  51515. set: function (value) {
  51516. this._activeCount = Math.min(value, this._capacity);
  51517. },
  51518. enumerable: true,
  51519. configurable: true
  51520. });
  51521. /**
  51522. * Gets Wether the system has been started.
  51523. * @returns True if it has been started, otherwise false.
  51524. */
  51525. GPUParticleSystem.prototype.isStarted = function () {
  51526. return this._started;
  51527. };
  51528. /**
  51529. * Starts the particle system and begins to emit.
  51530. */
  51531. GPUParticleSystem.prototype.start = function () {
  51532. this._started = true;
  51533. };
  51534. /**
  51535. * Stops the particle system.
  51536. */
  51537. GPUParticleSystem.prototype.stop = function () {
  51538. this._started = false;
  51539. };
  51540. /**
  51541. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51542. */
  51543. GPUParticleSystem.prototype.animate = function () {
  51544. if (this._currentRenderId === this._scene.getRenderId()) {
  51545. return;
  51546. }
  51547. this._currentRenderId = this._scene.getRenderId();
  51548. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  51549. };
  51550. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  51551. var updateVertexBuffers = {};
  51552. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  51553. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  51554. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  51555. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  51556. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  51557. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  51558. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  51559. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  51560. this._engine.bindArrayBuffer(null);
  51561. return vao;
  51562. };
  51563. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  51564. var renderVertexBuffers = {};
  51565. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  51566. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  51567. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  51568. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  51569. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  51570. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  51571. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  51572. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  51573. this._engine.bindArrayBuffer(null);
  51574. return vao;
  51575. };
  51576. GPUParticleSystem.prototype._initialize = function () {
  51577. if (this._buffer0) {
  51578. return;
  51579. }
  51580. var engine = this._scene.getEngine();
  51581. var data = new Array();
  51582. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  51583. // position
  51584. data.push(0.0);
  51585. data.push(0.0);
  51586. data.push(0.0);
  51587. // Age and life
  51588. data.push(0.0); // create the particle as a dead one to create a new one at start
  51589. data.push(0.0);
  51590. // Seed
  51591. data.push(Math.random());
  51592. // Size
  51593. data.push(0.0);
  51594. // color
  51595. data.push(0.0);
  51596. data.push(0.0);
  51597. data.push(0.0);
  51598. data.push(0.0);
  51599. // direction
  51600. data.push(0.0);
  51601. data.push(0.0);
  51602. data.push(0.0);
  51603. }
  51604. // Sprite data
  51605. var spriteData = new Float32Array([1, 1, 1, 1,
  51606. -1, 1, 0, 1,
  51607. -1, -1, 0, 0,
  51608. 1, -1, 1, 0]);
  51609. // Buffers
  51610. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  51611. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  51612. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  51613. // Update VAO
  51614. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  51615. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  51616. // Render VAO
  51617. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  51618. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  51619. // Links
  51620. this._sourceBuffer = this._buffer0;
  51621. this._targetBuffer = this._buffer1;
  51622. };
  51623. /**
  51624. * Renders the particle system in its current state.
  51625. * @returns the current number of particles.
  51626. */
  51627. GPUParticleSystem.prototype.render = function () {
  51628. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  51629. return 0;
  51630. }
  51631. // Get everything ready to render
  51632. this._initialize();
  51633. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + this.emitRate);
  51634. // Enable update effect
  51635. this._engine.enableEffect(this._updateEffect);
  51636. this._engine.setState(false);
  51637. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  51638. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  51639. this._updateEffect.setFloat("generalRandom", Math.random());
  51640. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  51641. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  51642. this._updateEffect.setDirectColor4("color1", this.color1);
  51643. this._updateEffect.setDirectColor4("color2", this.color2);
  51644. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  51645. this._updateEffect.setVector3("gravity", this.gravity);
  51646. var emitterWM;
  51647. if (this.emitter.position) {
  51648. var emitterMesh = this.emitter;
  51649. emitterWM = emitterMesh.getWorldMatrix();
  51650. }
  51651. else {
  51652. var emitterPosition = this.emitter;
  51653. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51654. }
  51655. this._updateEffect.setMatrix("emitterWM", emitterWM);
  51656. // Bind source VAO
  51657. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  51658. // Update
  51659. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  51660. this._engine.setRasterizerState(false);
  51661. this._engine.beginTransformFeedback();
  51662. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  51663. this._engine.endTransformFeedback();
  51664. this._engine.setRasterizerState(true);
  51665. this._engine.bindTransformFeedbackBuffer(null);
  51666. // Enable render effect
  51667. this._engine.enableEffect(this._renderEffect);
  51668. this._renderEffect.setMatrix("view", this._scene.getViewMatrix());
  51669. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  51670. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  51671. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  51672. // Draw order
  51673. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  51674. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51675. }
  51676. else {
  51677. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51678. }
  51679. // Bind source VAO
  51680. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  51681. // Render
  51682. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  51683. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51684. // Switch VAOs
  51685. this._targetIndex++;
  51686. if (this._targetIndex === 2) {
  51687. this._targetIndex = 0;
  51688. }
  51689. // Switch buffers
  51690. var tmpBuffer = this._sourceBuffer;
  51691. this._sourceBuffer = this._targetBuffer;
  51692. this._targetBuffer = tmpBuffer;
  51693. return 0;
  51694. };
  51695. /**
  51696. * Rebuilds the particle system
  51697. */
  51698. GPUParticleSystem.prototype.rebuild = function () {
  51699. };
  51700. /**
  51701. * Disposes the particle system and free the associated resources.
  51702. */
  51703. GPUParticleSystem.prototype.dispose = function () {
  51704. var index = this._scene.particleSystems.indexOf(this);
  51705. if (index > -1) {
  51706. this._scene.particleSystems.splice(index, 1);
  51707. }
  51708. if (this._buffer0) {
  51709. this._buffer0.dispose();
  51710. this._buffer0 = null;
  51711. }
  51712. if (this._buffer1) {
  51713. this._buffer1.dispose();
  51714. this._buffer1 = null;
  51715. }
  51716. for (var index = 0; index < this._updateVAO.length; index++) {
  51717. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  51718. }
  51719. this._updateVAO = [];
  51720. for (var index = 0; index < this._renderVAO.length; index++) {
  51721. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  51722. }
  51723. this._renderVAO = [];
  51724. if (this._randomTexture) {
  51725. this._randomTexture.dispose();
  51726. this._randomTexture = null;
  51727. }
  51728. // Callback
  51729. this.onDisposeObservable.notifyObservers(this);
  51730. this.onDisposeObservable.clear();
  51731. };
  51732. //TODO: Clone / Parse / serialize
  51733. /**
  51734. * Clones the particle system.
  51735. * @param name The name of the cloned object
  51736. * @param newEmitter The new emitter to use
  51737. * @returns the cloned particle system
  51738. */
  51739. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  51740. return null;
  51741. };
  51742. /**
  51743. * Serializes the particle system to a JSON object.
  51744. * @returns the JSON object
  51745. */
  51746. GPUParticleSystem.prototype.serialize = function () {
  51747. };
  51748. return GPUParticleSystem;
  51749. }());
  51750. BABYLON.GPUParticleSystem = GPUParticleSystem;
  51751. })(BABYLON || (BABYLON = {}));
  51752. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  51753. var BABYLON;
  51754. (function (BABYLON) {
  51755. /**
  51756. * Represents one particle of a solid particle system.
  51757. * @see SolidParticleSystem
  51758. */
  51759. var SolidParticle = /** @class */ (function () {
  51760. /**
  51761. * Creates a Solid Particle object.
  51762. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  51763. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  51764. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  51765. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  51766. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  51767. * @param shapeId (integer) is the model shape identifier in the SPS.
  51768. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  51769. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  51770. */
  51771. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  51772. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  51773. /**
  51774. * particle global index
  51775. */
  51776. this.idx = 0;
  51777. /**
  51778. * The color of the particle
  51779. */
  51780. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51781. /**
  51782. * The world space position of the particle.
  51783. */
  51784. this.position = BABYLON.Vector3.Zero();
  51785. /**
  51786. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  51787. */
  51788. this.rotation = BABYLON.Vector3.Zero();
  51789. /**
  51790. * The scaling of the particle.
  51791. */
  51792. this.scaling = BABYLON.Vector3.One();
  51793. /**
  51794. * The uvs of the particle.
  51795. */
  51796. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  51797. /**
  51798. * The current speed of the particle.
  51799. */
  51800. this.velocity = BABYLON.Vector3.Zero();
  51801. /**
  51802. * The pivot point in the particle local space.
  51803. */
  51804. this.pivot = BABYLON.Vector3.Zero();
  51805. /**
  51806. * Must the particle be translated from its pivot point in its local space ?
  51807. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  51808. * Default : false
  51809. */
  51810. this.translateFromPivot = false;
  51811. /**
  51812. * Is the particle active or not ?
  51813. */
  51814. this.alive = true;
  51815. /**
  51816. * Is the particle visible or not ?
  51817. */
  51818. this.isVisible = true;
  51819. /**
  51820. * Index of this particle in the global "positions" array (Internal use)
  51821. */
  51822. this._pos = 0;
  51823. /**
  51824. * Index of this particle in the global "indices" array (Internal use)
  51825. */
  51826. this._ind = 0;
  51827. /**
  51828. * ModelShape id of this particle
  51829. */
  51830. this.shapeId = 0;
  51831. /**
  51832. * Index of the particle in its shape id (Internal use)
  51833. */
  51834. this.idxInShape = 0;
  51835. /**
  51836. * Still set as invisible in order to skip useless computations (Internal use)
  51837. */
  51838. this._stillInvisible = false;
  51839. /**
  51840. * Last computed particle rotation matrix
  51841. */
  51842. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  51843. /**
  51844. * Parent particle Id, if any.
  51845. * Default null.
  51846. */
  51847. this.parentId = null;
  51848. /**
  51849. * Internal global position in the SPS.
  51850. */
  51851. this._globalPosition = BABYLON.Vector3.Zero();
  51852. this.idx = particleIndex;
  51853. this._pos = positionIndex;
  51854. this._ind = indiceIndex;
  51855. this._model = model;
  51856. this.shapeId = shapeId;
  51857. this.idxInShape = idxInShape;
  51858. this._sps = sps;
  51859. if (modelBoundingInfo) {
  51860. this._modelBoundingInfo = modelBoundingInfo;
  51861. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  51862. }
  51863. }
  51864. Object.defineProperty(SolidParticle.prototype, "scale", {
  51865. /**
  51866. * Legacy support, changed scale to scaling
  51867. */
  51868. get: function () {
  51869. return this.scaling;
  51870. },
  51871. /**
  51872. * Legacy support, changed scale to scaling
  51873. */
  51874. set: function (scale) {
  51875. this.scaling = scale;
  51876. },
  51877. enumerable: true,
  51878. configurable: true
  51879. });
  51880. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  51881. /**
  51882. * Legacy support, changed quaternion to rotationQuaternion
  51883. */
  51884. get: function () {
  51885. return this.rotationQuaternion;
  51886. },
  51887. /**
  51888. * Legacy support, changed quaternion to rotationQuaternion
  51889. */
  51890. set: function (q) {
  51891. this.rotationQuaternion = q;
  51892. },
  51893. enumerable: true,
  51894. configurable: true
  51895. });
  51896. /**
  51897. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  51898. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  51899. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  51900. * @returns true if it intersects
  51901. */
  51902. SolidParticle.prototype.intersectsMesh = function (target) {
  51903. if (!this._boundingInfo || !target._boundingInfo) {
  51904. return false;
  51905. }
  51906. if (this._sps._bSphereOnly) {
  51907. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  51908. }
  51909. return this._boundingInfo.intersects(target._boundingInfo, false);
  51910. };
  51911. return SolidParticle;
  51912. }());
  51913. BABYLON.SolidParticle = SolidParticle;
  51914. /**
  51915. * Represents the shape of the model used by one particle of a solid particle system.
  51916. * SPS internal tool, don't use it manually.
  51917. * @see SolidParticleSystem
  51918. */
  51919. var ModelShape = /** @class */ (function () {
  51920. /**
  51921. * 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.
  51922. * SPS internal tool, don't use it manually.
  51923. * @ignore
  51924. */
  51925. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  51926. /**
  51927. * length of the shape in the model indices array (internal use)
  51928. */
  51929. this._indicesLength = 0;
  51930. this.shapeID = id;
  51931. this._shape = shape;
  51932. this._indicesLength = indicesLength;
  51933. this._shapeUV = shapeUV;
  51934. this._positionFunction = posFunction;
  51935. this._vertexFunction = vtxFunction;
  51936. }
  51937. return ModelShape;
  51938. }());
  51939. BABYLON.ModelShape = ModelShape;
  51940. /**
  51941. * Represents a Depth Sorted Particle in the solid particle system.
  51942. * @see SolidParticleSystem
  51943. */
  51944. var DepthSortedParticle = /** @class */ (function () {
  51945. function DepthSortedParticle() {
  51946. /**
  51947. * Index of the particle in the "indices" array
  51948. */
  51949. this.ind = 0;
  51950. /**
  51951. * Length of the particle shape in the "indices" array
  51952. */
  51953. this.indicesLength = 0;
  51954. /**
  51955. * Squared distance from the particle to the camera
  51956. */
  51957. this.sqDistance = 0.0;
  51958. }
  51959. return DepthSortedParticle;
  51960. }());
  51961. BABYLON.DepthSortedParticle = DepthSortedParticle;
  51962. })(BABYLON || (BABYLON = {}));
  51963. //# sourceMappingURL=babylon.solidParticle.js.map
  51964. var BABYLON;
  51965. (function (BABYLON) {
  51966. /**
  51967. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  51968. *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.
  51969. * The SPS is also a particle system. It provides some methods to manage the particles.
  51970. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  51971. *
  51972. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  51973. */
  51974. var SolidParticleSystem = /** @class */ (function () {
  51975. /**
  51976. * Creates a SPS (Solid Particle System) object.
  51977. * @param name (String) is the SPS name, this will be the underlying mesh name.
  51978. * @param scene (Scene) is the scene in which the SPS is added.
  51979. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  51980. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  51981. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  51982. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  51983. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  51984. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  51985. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  51986. */
  51987. function SolidParticleSystem(name, scene, options) {
  51988. /**
  51989. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  51990. * Example : var p = SPS.particles[i];
  51991. */
  51992. this.particles = new Array();
  51993. /**
  51994. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  51995. */
  51996. this.nbParticles = 0;
  51997. /**
  51998. * If the particles must ever face the camera (default false). Useful for planar particles.
  51999. */
  52000. this.billboard = false;
  52001. /**
  52002. * Recompute normals when adding a shape
  52003. */
  52004. this.recomputeNormals = true;
  52005. /**
  52006. * This a counter ofr your own usage. It's not set by any SPS functions.
  52007. */
  52008. this.counter = 0;
  52009. /**
  52010. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52011. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52012. */
  52013. this.vars = {};
  52014. /**
  52015. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52016. */
  52017. this._bSphereOnly = false;
  52018. /**
  52019. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52020. */
  52021. this._bSphereRadiusFactor = 1.0;
  52022. this._positions = new Array();
  52023. this._indices = new Array();
  52024. this._normals = new Array();
  52025. this._colors = new Array();
  52026. this._uvs = new Array();
  52027. this._index = 0; // indices index
  52028. this._updatable = true;
  52029. this._pickable = false;
  52030. this._isVisibilityBoxLocked = false;
  52031. this._alwaysVisible = false;
  52032. this._depthSort = false;
  52033. this._shapeCounter = 0;
  52034. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52035. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52036. this._computeParticleColor = true;
  52037. this._computeParticleTexture = true;
  52038. this._computeParticleRotation = true;
  52039. this._computeParticleVertex = false;
  52040. this._computeBoundingBox = false;
  52041. this._depthSortParticles = true;
  52042. this._cam_axisZ = BABYLON.Vector3.Zero();
  52043. this._cam_axisY = BABYLON.Vector3.Zero();
  52044. this._cam_axisX = BABYLON.Vector3.Zero();
  52045. this._axisZ = BABYLON.Axis.Z;
  52046. this._camDir = BABYLON.Vector3.Zero();
  52047. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52048. this._rotMatrix = new BABYLON.Matrix();
  52049. this._invertMatrix = new BABYLON.Matrix();
  52050. this._rotated = BABYLON.Vector3.Zero();
  52051. this._quaternion = new BABYLON.Quaternion();
  52052. this._vertex = BABYLON.Vector3.Zero();
  52053. this._normal = BABYLON.Vector3.Zero();
  52054. this._yaw = 0.0;
  52055. this._pitch = 0.0;
  52056. this._roll = 0.0;
  52057. this._halfroll = 0.0;
  52058. this._halfpitch = 0.0;
  52059. this._halfyaw = 0.0;
  52060. this._sinRoll = 0.0;
  52061. this._cosRoll = 0.0;
  52062. this._sinPitch = 0.0;
  52063. this._cosPitch = 0.0;
  52064. this._sinYaw = 0.0;
  52065. this._cosYaw = 0.0;
  52066. this._mustUnrotateFixedNormals = false;
  52067. this._minimum = BABYLON.Vector3.Zero();
  52068. this._maximum = BABYLON.Vector3.Zero();
  52069. this._minBbox = BABYLON.Vector3.Zero();
  52070. this._maxBbox = BABYLON.Vector3.Zero();
  52071. this._particlesIntersect = false;
  52072. this._depthSortFunction = function (p1, p2) {
  52073. return (p2.sqDistance - p1.sqDistance);
  52074. };
  52075. this._needs32Bits = false;
  52076. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52077. this._scaledPivot = BABYLON.Vector3.Zero();
  52078. this._particleHasParent = false;
  52079. this.name = name;
  52080. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52081. this._camera = scene.activeCamera;
  52082. this._pickable = options ? options.isPickable : false;
  52083. this._depthSort = options ? options.enableDepthSort : false;
  52084. this._particlesIntersect = options ? options.particleIntersection : false;
  52085. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52086. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52087. if (options && options.updatable) {
  52088. this._updatable = options.updatable;
  52089. }
  52090. else {
  52091. this._updatable = true;
  52092. }
  52093. if (this._pickable) {
  52094. this.pickedParticles = [];
  52095. }
  52096. if (this._depthSort) {
  52097. this.depthSortedParticles = [];
  52098. }
  52099. }
  52100. /**
  52101. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52102. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52103. * @returns the created mesh
  52104. */
  52105. SolidParticleSystem.prototype.buildMesh = function () {
  52106. if (this.nbParticles === 0) {
  52107. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52108. this.addShape(triangle, 1);
  52109. triangle.dispose();
  52110. }
  52111. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52112. this._positions32 = new Float32Array(this._positions);
  52113. this._uvs32 = new Float32Array(this._uvs);
  52114. this._colors32 = new Float32Array(this._colors);
  52115. if (this.recomputeNormals) {
  52116. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52117. }
  52118. this._normals32 = new Float32Array(this._normals);
  52119. this._fixedNormal32 = new Float32Array(this._normals);
  52120. if (this._mustUnrotateFixedNormals) {
  52121. this._unrotateFixedNormals();
  52122. }
  52123. var vertexData = new BABYLON.VertexData();
  52124. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52125. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52126. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52127. if (this._uvs32) {
  52128. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52129. ;
  52130. }
  52131. if (this._colors32) {
  52132. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52133. }
  52134. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52135. vertexData.applyToMesh(mesh, this._updatable);
  52136. this.mesh = mesh;
  52137. this.mesh.isPickable = this._pickable;
  52138. // free memory
  52139. if (!this._depthSort) {
  52140. this._indices = null;
  52141. }
  52142. this._positions = null;
  52143. this._normals = null;
  52144. this._uvs = null;
  52145. this._colors = null;
  52146. if (!this._updatable) {
  52147. this.particles.length = 0;
  52148. }
  52149. return mesh;
  52150. };
  52151. /**
  52152. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52153. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52154. * Thus the particles generated from `digest()` have their property `position` set yet.
  52155. * @param mesh ( Mesh ) is the mesh to be digested
  52156. * @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
  52157. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52158. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52159. * @returns the current SPS
  52160. */
  52161. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52162. var size = (options && options.facetNb) || 1;
  52163. var number = (options && options.number) || 0;
  52164. var delta = (options && options.delta) || 0;
  52165. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52166. var meshInd = mesh.getIndices();
  52167. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52168. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52169. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52170. var f = 0; // facet counter
  52171. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52172. // compute size from number
  52173. if (number) {
  52174. number = (number > totalFacets) ? totalFacets : number;
  52175. size = Math.round(totalFacets / number);
  52176. delta = 0;
  52177. }
  52178. else {
  52179. size = (size > totalFacets) ? totalFacets : size;
  52180. }
  52181. var facetPos = []; // submesh positions
  52182. var facetInd = []; // submesh indices
  52183. var facetUV = []; // submesh UV
  52184. var facetCol = []; // submesh colors
  52185. var barycenter = BABYLON.Vector3.Zero();
  52186. var sizeO = size;
  52187. while (f < totalFacets) {
  52188. size = sizeO + Math.floor((1 + delta) * Math.random());
  52189. if (f > totalFacets - size) {
  52190. size = totalFacets - f;
  52191. }
  52192. // reset temp arrays
  52193. facetPos.length = 0;
  52194. facetInd.length = 0;
  52195. facetUV.length = 0;
  52196. facetCol.length = 0;
  52197. // iterate over "size" facets
  52198. var fi = 0;
  52199. for (var j = f * 3; j < (f + size) * 3; j++) {
  52200. facetInd.push(fi);
  52201. var i = meshInd[j];
  52202. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52203. if (meshUV) {
  52204. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52205. }
  52206. if (meshCol) {
  52207. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52208. }
  52209. fi++;
  52210. }
  52211. // create a model shape for each single particle
  52212. var idx = this.nbParticles;
  52213. var shape = this._posToShape(facetPos);
  52214. var shapeUV = this._uvsToShapeUV(facetUV);
  52215. // compute the barycenter of the shape
  52216. var v;
  52217. for (v = 0; v < shape.length; v++) {
  52218. barycenter.addInPlace(shape[v]);
  52219. }
  52220. barycenter.scaleInPlace(1 / shape.length);
  52221. // shift the shape from its barycenter to the origin
  52222. for (v = 0; v < shape.length; v++) {
  52223. shape[v].subtractInPlace(barycenter);
  52224. }
  52225. var bInfo;
  52226. if (this._particlesIntersect) {
  52227. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52228. }
  52229. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52230. // add the particle in the SPS
  52231. var currentPos = this._positions.length;
  52232. var currentInd = this._indices.length;
  52233. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52234. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52235. // initialize the particle position
  52236. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52237. this._index += shape.length;
  52238. idx++;
  52239. this.nbParticles++;
  52240. this._shapeCounter++;
  52241. f += size;
  52242. }
  52243. return this;
  52244. };
  52245. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52246. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52247. var index = 0;
  52248. var idx = 0;
  52249. for (var p = 0; p < this.particles.length; p++) {
  52250. this._particle = this.particles[p];
  52251. this._shape = this._particle._model._shape;
  52252. if (this._particle.rotationQuaternion) {
  52253. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52254. }
  52255. else {
  52256. this._yaw = this._particle.rotation.y;
  52257. this._pitch = this._particle.rotation.x;
  52258. this._roll = this._particle.rotation.z;
  52259. this._quaternionRotationYPR();
  52260. }
  52261. this._quaternionToRotationMatrix();
  52262. this._rotMatrix.invertToRef(this._invertMatrix);
  52263. for (var pt = 0; pt < this._shape.length; pt++) {
  52264. idx = index + pt * 3;
  52265. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52266. this._fixedNormal32[idx] = this._normal.x;
  52267. this._fixedNormal32[idx + 1] = this._normal.y;
  52268. this._fixedNormal32[idx + 2] = this._normal.z;
  52269. }
  52270. index = idx + 3;
  52271. }
  52272. };
  52273. //reset copy
  52274. SolidParticleSystem.prototype._resetCopy = function () {
  52275. this._copy.position.x = 0;
  52276. this._copy.position.y = 0;
  52277. this._copy.position.z = 0;
  52278. this._copy.rotation.x = 0;
  52279. this._copy.rotation.y = 0;
  52280. this._copy.rotation.z = 0;
  52281. this._copy.rotationQuaternion = null;
  52282. this._copy.scaling.x = 1.0;
  52283. this._copy.scaling.y = 1.0;
  52284. this._copy.scaling.z = 1.0;
  52285. this._copy.uvs.x = 0;
  52286. this._copy.uvs.y = 0;
  52287. this._copy.uvs.z = 1.0;
  52288. this._copy.uvs.w = 1.0;
  52289. this._copy.color = null;
  52290. this._copy.translateFromPivot = false;
  52291. };
  52292. // _meshBuilder : inserts the shape model in the global SPS mesh
  52293. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52294. var i;
  52295. var u = 0;
  52296. var c = 0;
  52297. var n = 0;
  52298. this._resetCopy();
  52299. if (options && options.positionFunction) {
  52300. options.positionFunction(this._copy, idx, idxInShape);
  52301. this._mustUnrotateFixedNormals = true;
  52302. }
  52303. if (this._copy.rotationQuaternion) {
  52304. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52305. }
  52306. else {
  52307. this._yaw = this._copy.rotation.y;
  52308. this._pitch = this._copy.rotation.x;
  52309. this._roll = this._copy.rotation.z;
  52310. this._quaternionRotationYPR();
  52311. }
  52312. this._quaternionToRotationMatrix();
  52313. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52314. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52315. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52316. if (this._copy.translateFromPivot) {
  52317. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52318. }
  52319. else {
  52320. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52321. }
  52322. for (i = 0; i < shape.length; i++) {
  52323. this._vertex.x = shape[i].x;
  52324. this._vertex.y = shape[i].y;
  52325. this._vertex.z = shape[i].z;
  52326. if (options && options.vertexFunction) {
  52327. options.vertexFunction(this._copy, this._vertex, i);
  52328. }
  52329. this._vertex.x *= this._copy.scaling.x;
  52330. this._vertex.y *= this._copy.scaling.y;
  52331. this._vertex.z *= this._copy.scaling.z;
  52332. this._vertex.x -= this._scaledPivot.x;
  52333. this._vertex.y -= this._scaledPivot.y;
  52334. this._vertex.z -= this._scaledPivot.z;
  52335. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52336. this._rotated.addInPlace(this._pivotBackTranslation);
  52337. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52338. if (meshUV) {
  52339. 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);
  52340. u += 2;
  52341. }
  52342. if (this._copy.color) {
  52343. this._color = this._copy.color;
  52344. }
  52345. else if (meshCol && meshCol[c] !== undefined) {
  52346. this._color.r = meshCol[c];
  52347. this._color.g = meshCol[c + 1];
  52348. this._color.b = meshCol[c + 2];
  52349. this._color.a = meshCol[c + 3];
  52350. }
  52351. else {
  52352. this._color.r = 1.0;
  52353. this._color.g = 1.0;
  52354. this._color.b = 1.0;
  52355. this._color.a = 1.0;
  52356. }
  52357. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52358. c += 4;
  52359. if (!this.recomputeNormals && meshNor) {
  52360. this._normal.x = meshNor[n];
  52361. this._normal.y = meshNor[n + 1];
  52362. this._normal.z = meshNor[n + 2];
  52363. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52364. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52365. n += 3;
  52366. }
  52367. }
  52368. for (i = 0; i < meshInd.length; i++) {
  52369. var current_ind = p + meshInd[i];
  52370. indices.push(current_ind);
  52371. if (current_ind > 65535) {
  52372. this._needs32Bits = true;
  52373. }
  52374. }
  52375. if (this._pickable) {
  52376. var nbfaces = meshInd.length / 3;
  52377. for (i = 0; i < nbfaces; i++) {
  52378. this.pickedParticles.push({ idx: idx, faceId: i });
  52379. }
  52380. }
  52381. if (this._depthSort) {
  52382. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52383. }
  52384. return this._copy;
  52385. };
  52386. // returns a shape array from positions array
  52387. SolidParticleSystem.prototype._posToShape = function (positions) {
  52388. var shape = [];
  52389. for (var i = 0; i < positions.length; i += 3) {
  52390. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52391. }
  52392. return shape;
  52393. };
  52394. // returns a shapeUV array from a Vector4 uvs
  52395. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52396. var shapeUV = [];
  52397. if (uvs) {
  52398. for (var i = 0; i < uvs.length; i++)
  52399. shapeUV.push(uvs[i]);
  52400. }
  52401. return shapeUV;
  52402. };
  52403. // adds a new particle object in the particles array
  52404. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52405. if (bInfo === void 0) { bInfo = null; }
  52406. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52407. this.particles.push(sp);
  52408. return sp;
  52409. };
  52410. /**
  52411. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52412. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52413. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52414. * @param nb (positive integer) the number of particles to be created from this model
  52415. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52416. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52417. * @returns the number of shapes in the system
  52418. */
  52419. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52420. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52421. var meshInd = mesh.getIndices();
  52422. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52423. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52424. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52425. var bbInfo;
  52426. if (this._particlesIntersect) {
  52427. bbInfo = mesh.getBoundingInfo();
  52428. }
  52429. var shape = this._posToShape(meshPos);
  52430. var shapeUV = this._uvsToShapeUV(meshUV);
  52431. var posfunc = options ? options.positionFunction : null;
  52432. var vtxfunc = options ? options.vertexFunction : null;
  52433. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52434. // particles
  52435. var sp;
  52436. var currentCopy;
  52437. var idx = this.nbParticles;
  52438. for (var i = 0; i < nb; i++) {
  52439. var currentPos = this._positions.length;
  52440. var currentInd = this._indices.length;
  52441. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52442. if (this._updatable) {
  52443. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52444. sp.position.copyFrom(currentCopy.position);
  52445. sp.rotation.copyFrom(currentCopy.rotation);
  52446. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52447. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52448. }
  52449. if (currentCopy.color && sp.color) {
  52450. sp.color.copyFrom(currentCopy.color);
  52451. }
  52452. sp.scaling.copyFrom(currentCopy.scaling);
  52453. sp.uvs.copyFrom(currentCopy.uvs);
  52454. }
  52455. this._index += shape.length;
  52456. idx++;
  52457. }
  52458. this.nbParticles += nb;
  52459. this._shapeCounter++;
  52460. return this._shapeCounter - 1;
  52461. };
  52462. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52463. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52464. this._resetCopy();
  52465. if (particle._model._positionFunction) {
  52466. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52467. }
  52468. if (this._copy.rotationQuaternion) {
  52469. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52470. }
  52471. else {
  52472. this._yaw = this._copy.rotation.y;
  52473. this._pitch = this._copy.rotation.x;
  52474. this._roll = this._copy.rotation.z;
  52475. this._quaternionRotationYPR();
  52476. }
  52477. this._quaternionToRotationMatrix();
  52478. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52479. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52480. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52481. if (this._copy.translateFromPivot) {
  52482. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52483. }
  52484. else {
  52485. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52486. }
  52487. this._shape = particle._model._shape;
  52488. for (var pt = 0; pt < this._shape.length; pt++) {
  52489. this._vertex.x = this._shape[pt].x;
  52490. this._vertex.y = this._shape[pt].y;
  52491. this._vertex.z = this._shape[pt].z;
  52492. if (particle._model._vertexFunction) {
  52493. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52494. }
  52495. this._vertex.x *= this._copy.scaling.x;
  52496. this._vertex.y *= this._copy.scaling.y;
  52497. this._vertex.z *= this._copy.scaling.z;
  52498. this._vertex.x -= this._scaledPivot.x;
  52499. this._vertex.y -= this._scaledPivot.y;
  52500. this._vertex.z -= this._scaledPivot.z;
  52501. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52502. this._rotated.addInPlace(this._pivotBackTranslation);
  52503. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52504. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52505. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52506. }
  52507. particle.position.x = 0.0;
  52508. particle.position.y = 0.0;
  52509. particle.position.z = 0.0;
  52510. particle.rotation.x = 0.0;
  52511. particle.rotation.y = 0.0;
  52512. particle.rotation.z = 0.0;
  52513. particle.rotationQuaternion = null;
  52514. particle.scaling.x = 1.0;
  52515. particle.scaling.y = 1.0;
  52516. particle.scaling.z = 1.0;
  52517. particle.uvs.x = 0.0;
  52518. particle.uvs.y = 0.0;
  52519. particle.uvs.z = 1.0;
  52520. particle.uvs.w = 1.0;
  52521. particle.pivot.x = 0.0;
  52522. particle.pivot.y = 0.0;
  52523. particle.pivot.z = 0.0;
  52524. particle.translateFromPivot = false;
  52525. particle.parentId = null;
  52526. };
  52527. /**
  52528. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52529. * @returns the SPS.
  52530. */
  52531. SolidParticleSystem.prototype.rebuildMesh = function () {
  52532. for (var p = 0; p < this.particles.length; p++) {
  52533. this._rebuildParticle(this.particles[p]);
  52534. }
  52535. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52536. return this;
  52537. };
  52538. /**
  52539. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52540. * This method calls `updateParticle()` for each particle of the SPS.
  52541. * For an animated SPS, it is usually called within the render loop.
  52542. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52543. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52544. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52545. * @returns the SPS.
  52546. */
  52547. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52548. if (start === void 0) { start = 0; }
  52549. if (end === void 0) { end = this.nbParticles - 1; }
  52550. if (update === void 0) { update = true; }
  52551. if (!this._updatable) {
  52552. return this;
  52553. }
  52554. // custom beforeUpdate
  52555. this.beforeUpdateParticles(start, end, update);
  52556. this._cam_axisX.x = 1.0;
  52557. this._cam_axisX.y = 0.0;
  52558. this._cam_axisX.z = 0.0;
  52559. this._cam_axisY.x = 0.0;
  52560. this._cam_axisY.y = 1.0;
  52561. this._cam_axisY.z = 0.0;
  52562. this._cam_axisZ.x = 0.0;
  52563. this._cam_axisZ.y = 0.0;
  52564. this._cam_axisZ.z = 1.0;
  52565. // cases when the World Matrix is to be computed first
  52566. if (this.billboard || this._depthSort) {
  52567. this.mesh.computeWorldMatrix(true);
  52568. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  52569. }
  52570. // if the particles will always face the camera
  52571. if (this.billboard) {
  52572. // compute the camera position and un-rotate it by the current mesh rotation
  52573. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  52574. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  52575. this._cam_axisZ.normalize();
  52576. // same for camera up vector extracted from the cam view matrix
  52577. var view = this._camera.getViewMatrix(true);
  52578. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  52579. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  52580. this._cam_axisY.normalize();
  52581. this._cam_axisX.normalize();
  52582. }
  52583. // if depthSort, compute the camera global position in the mesh local system
  52584. if (this._depthSort) {
  52585. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  52586. }
  52587. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  52588. var idx = 0; // current position index in the global array positions32
  52589. var index = 0; // position start index in the global array positions32 of the current particle
  52590. var colidx = 0; // current color index in the global array colors32
  52591. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  52592. var uvidx = 0; // current uv index in the global array uvs32
  52593. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  52594. var pt = 0; // current index in the particle model shape
  52595. if (this.mesh.isFacetDataEnabled) {
  52596. this._computeBoundingBox = true;
  52597. }
  52598. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  52599. if (this._computeBoundingBox) {
  52600. if (start == 0 && end == this.nbParticles - 1) {
  52601. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  52602. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  52603. }
  52604. else {
  52605. if (this.mesh._boundingInfo) {
  52606. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  52607. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  52608. }
  52609. }
  52610. }
  52611. // particle loop
  52612. index = this.particles[start]._pos;
  52613. var vpos = (index / 3) | 0;
  52614. colorIndex = vpos * 4;
  52615. uvIndex = vpos * 2;
  52616. for (var p = start; p <= end; p++) {
  52617. this._particle = this.particles[p];
  52618. this._shape = this._particle._model._shape;
  52619. this._shapeUV = this._particle._model._shapeUV;
  52620. // call to custom user function to update the particle properties
  52621. this.updateParticle(this._particle);
  52622. // camera-particle distance for depth sorting
  52623. if (this._depthSort && this._depthSortParticles) {
  52624. var dsp = this.depthSortedParticles[p];
  52625. dsp.ind = this._particle._ind;
  52626. dsp.indicesLength = this._particle._model._indicesLength;
  52627. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  52628. }
  52629. // skip the computations for inactive or already invisible particles
  52630. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  52631. // increment indexes for the next particle
  52632. pt = this._shape.length;
  52633. index += pt * 3;
  52634. colorIndex += pt * 4;
  52635. uvIndex += pt * 2;
  52636. continue;
  52637. }
  52638. if (this._particle.isVisible) {
  52639. this._particle._stillInvisible = false; // un-mark permanent invisibility
  52640. this._particleHasParent = (this._particle.parentId !== null);
  52641. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52642. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52643. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52644. // particle rotation matrix
  52645. if (this.billboard) {
  52646. this._particle.rotation.x = 0.0;
  52647. this._particle.rotation.y = 0.0;
  52648. }
  52649. if (this._computeParticleRotation || this.billboard) {
  52650. if (this._particle.rotationQuaternion) {
  52651. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52652. }
  52653. else {
  52654. this._yaw = this._particle.rotation.y;
  52655. this._pitch = this._particle.rotation.x;
  52656. this._roll = this._particle.rotation.z;
  52657. this._quaternionRotationYPR();
  52658. }
  52659. this._quaternionToRotationMatrix();
  52660. }
  52661. if (this._particleHasParent) {
  52662. this._parent = this.particles[this._particle.parentId];
  52663. 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];
  52664. 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];
  52665. 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];
  52666. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  52667. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  52668. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  52669. if (this._computeParticleRotation || this.billboard) {
  52670. 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];
  52671. 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];
  52672. 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];
  52673. 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];
  52674. 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];
  52675. 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];
  52676. 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];
  52677. 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];
  52678. 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];
  52679. }
  52680. }
  52681. else {
  52682. this._particle._globalPosition.x = this._particle.position.x;
  52683. this._particle._globalPosition.y = this._particle.position.y;
  52684. this._particle._globalPosition.z = this._particle.position.z;
  52685. if (this._computeParticleRotation || this.billboard) {
  52686. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  52687. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  52688. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  52689. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  52690. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  52691. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  52692. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  52693. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  52694. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  52695. }
  52696. }
  52697. if (this._particle.translateFromPivot) {
  52698. this._pivotBackTranslation.x = 0.0;
  52699. this._pivotBackTranslation.y = 0.0;
  52700. this._pivotBackTranslation.z = 0.0;
  52701. }
  52702. else {
  52703. this._pivotBackTranslation.x = this._scaledPivot.x;
  52704. this._pivotBackTranslation.y = this._scaledPivot.y;
  52705. this._pivotBackTranslation.z = this._scaledPivot.z;
  52706. }
  52707. // particle vertex loop
  52708. for (pt = 0; pt < this._shape.length; pt++) {
  52709. idx = index + pt * 3;
  52710. colidx = colorIndex + pt * 4;
  52711. uvidx = uvIndex + pt * 2;
  52712. this._vertex.x = this._shape[pt].x;
  52713. this._vertex.y = this._shape[pt].y;
  52714. this._vertex.z = this._shape[pt].z;
  52715. if (this._computeParticleVertex) {
  52716. this.updateParticleVertex(this._particle, this._vertex, pt);
  52717. }
  52718. // positions
  52719. this._vertex.x *= this._particle.scaling.x;
  52720. this._vertex.y *= this._particle.scaling.y;
  52721. this._vertex.z *= this._particle.scaling.z;
  52722. this._vertex.x -= this._scaledPivot.x;
  52723. this._vertex.y -= this._scaledPivot.y;
  52724. this._vertex.z -= this._scaledPivot.z;
  52725. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52726. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52727. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52728. this._rotated.x += this._pivotBackTranslation.x;
  52729. this._rotated.y += this._pivotBackTranslation.y;
  52730. this._rotated.z += this._pivotBackTranslation.z;
  52731. 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;
  52732. 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;
  52733. 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;
  52734. if (this._computeBoundingBox) {
  52735. if (this._positions32[idx] < this._minimum.x) {
  52736. this._minimum.x = this._positions32[idx];
  52737. }
  52738. if (this._positions32[idx] > this._maximum.x) {
  52739. this._maximum.x = this._positions32[idx];
  52740. }
  52741. if (this._positions32[idx + 1] < this._minimum.y) {
  52742. this._minimum.y = this._positions32[idx + 1];
  52743. }
  52744. if (this._positions32[idx + 1] > this._maximum.y) {
  52745. this._maximum.y = this._positions32[idx + 1];
  52746. }
  52747. if (this._positions32[idx + 2] < this._minimum.z) {
  52748. this._minimum.z = this._positions32[idx + 2];
  52749. }
  52750. if (this._positions32[idx + 2] > this._maximum.z) {
  52751. this._maximum.z = this._positions32[idx + 2];
  52752. }
  52753. }
  52754. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  52755. if (!this._computeParticleVertex) {
  52756. this._normal.x = this._fixedNormal32[idx];
  52757. this._normal.y = this._fixedNormal32[idx + 1];
  52758. this._normal.z = this._fixedNormal32[idx + 2];
  52759. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  52760. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  52761. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  52762. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  52763. 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;
  52764. 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;
  52765. }
  52766. if (this._computeParticleColor && this._particle.color) {
  52767. this._colors32[colidx] = this._particle.color.r;
  52768. this._colors32[colidx + 1] = this._particle.color.g;
  52769. this._colors32[colidx + 2] = this._particle.color.b;
  52770. this._colors32[colidx + 3] = this._particle.color.a;
  52771. }
  52772. if (this._computeParticleTexture) {
  52773. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52774. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52775. }
  52776. }
  52777. }
  52778. else {
  52779. this._particle._stillInvisible = true; // mark the particle as invisible
  52780. for (pt = 0; pt < this._shape.length; pt++) {
  52781. idx = index + pt * 3;
  52782. colidx = colorIndex + pt * 4;
  52783. uvidx = uvIndex + pt * 2;
  52784. this._positions32[idx] = 0.0;
  52785. this._positions32[idx + 1] = 0.0;
  52786. this._positions32[idx + 2] = 0.0;
  52787. this._normals32[idx] = 0.0;
  52788. this._normals32[idx + 1] = 0.0;
  52789. this._normals32[idx + 2] = 0.0;
  52790. if (this._computeParticleColor && this._particle.color) {
  52791. this._colors32[colidx] = this._particle.color.r;
  52792. this._colors32[colidx + 1] = this._particle.color.g;
  52793. this._colors32[colidx + 2] = this._particle.color.b;
  52794. this._colors32[colidx + 3] = this._particle.color.a;
  52795. }
  52796. if (this._computeParticleTexture) {
  52797. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  52798. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  52799. }
  52800. }
  52801. }
  52802. // if the particle intersections must be computed : update the bbInfo
  52803. if (this._particlesIntersect) {
  52804. var bInfo = this._particle._boundingInfo;
  52805. var bBox = bInfo.boundingBox;
  52806. var bSphere = bInfo.boundingSphere;
  52807. if (!this._bSphereOnly) {
  52808. // place, scale and rotate the particle bbox within the SPS local system, then update it
  52809. for (var b = 0; b < bBox.vectors.length; b++) {
  52810. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  52811. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  52812. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  52813. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  52814. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  52815. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  52816. 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;
  52817. 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;
  52818. 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;
  52819. }
  52820. bBox._update(this.mesh._worldMatrix);
  52821. }
  52822. // place and scale the particle bouding sphere in the SPS local system, then update it
  52823. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  52824. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  52825. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  52826. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  52827. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  52828. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  52829. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  52830. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  52831. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  52832. 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));
  52833. bSphere._update(this.mesh._worldMatrix);
  52834. }
  52835. // increment indexes for the next particle
  52836. index = idx + 3;
  52837. colorIndex = colidx + 4;
  52838. uvIndex = uvidx + 2;
  52839. }
  52840. // if the VBO must be updated
  52841. if (update) {
  52842. if (this._computeParticleColor) {
  52843. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  52844. }
  52845. if (this._computeParticleTexture) {
  52846. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  52847. }
  52848. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52849. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  52850. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  52851. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  52852. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  52853. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  52854. for (var i = 0; i < this._normals32.length; i++) {
  52855. this._fixedNormal32[i] = this._normals32[i];
  52856. }
  52857. }
  52858. if (!this.mesh.areNormalsFrozen) {
  52859. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  52860. }
  52861. }
  52862. if (this._depthSort && this._depthSortParticles) {
  52863. this.depthSortedParticles.sort(this._depthSortFunction);
  52864. var dspl = this.depthSortedParticles.length;
  52865. var sorted = 0;
  52866. var lind = 0;
  52867. var sind = 0;
  52868. var sid = 0;
  52869. for (sorted = 0; sorted < dspl; sorted++) {
  52870. lind = this.depthSortedParticles[sorted].indicesLength;
  52871. sind = this.depthSortedParticles[sorted].ind;
  52872. for (var i = 0; i < lind; i++) {
  52873. this._indices32[sid] = this._indices[sind + i];
  52874. sid++;
  52875. }
  52876. }
  52877. this.mesh.updateIndices(this._indices32);
  52878. }
  52879. }
  52880. if (this._computeBoundingBox) {
  52881. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  52882. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  52883. }
  52884. this.afterUpdateParticles(start, end, update);
  52885. return this;
  52886. };
  52887. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  52888. this._halfroll = this._roll * 0.5;
  52889. this._halfpitch = this._pitch * 0.5;
  52890. this._halfyaw = this._yaw * 0.5;
  52891. this._sinRoll = Math.sin(this._halfroll);
  52892. this._cosRoll = Math.cos(this._halfroll);
  52893. this._sinPitch = Math.sin(this._halfpitch);
  52894. this._cosPitch = Math.cos(this._halfpitch);
  52895. this._sinYaw = Math.sin(this._halfyaw);
  52896. this._cosYaw = Math.cos(this._halfyaw);
  52897. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  52898. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  52899. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  52900. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  52901. };
  52902. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  52903. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  52904. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  52905. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  52906. this._rotMatrix.m[3] = 0;
  52907. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  52908. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  52909. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  52910. this._rotMatrix.m[7] = 0;
  52911. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  52912. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  52913. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  52914. this._rotMatrix.m[11] = 0;
  52915. this._rotMatrix.m[12] = 0;
  52916. this._rotMatrix.m[13] = 0;
  52917. this._rotMatrix.m[14] = 0;
  52918. this._rotMatrix.m[15] = 1.0;
  52919. };
  52920. /**
  52921. * Disposes the SPS.
  52922. */
  52923. SolidParticleSystem.prototype.dispose = function () {
  52924. this.mesh.dispose();
  52925. this.vars = null;
  52926. // drop references to internal big arrays for the GC
  52927. this._positions = null;
  52928. this._indices = null;
  52929. this._normals = null;
  52930. this._uvs = null;
  52931. this._colors = null;
  52932. this._indices32 = null;
  52933. this._positions32 = null;
  52934. this._normals32 = null;
  52935. this._fixedNormal32 = null;
  52936. this._uvs32 = null;
  52937. this._colors32 = null;
  52938. this.pickedParticles = null;
  52939. };
  52940. /**
  52941. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  52942. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52943. * @returns the SPS.
  52944. */
  52945. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  52946. if (!this._isVisibilityBoxLocked) {
  52947. this.mesh.refreshBoundingInfo();
  52948. }
  52949. return this;
  52950. };
  52951. /**
  52952. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  52953. * @param size the size (float) of the visibility box
  52954. * note : this doesn't lock the SPS mesh bounding box.
  52955. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52956. */
  52957. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  52958. var vis = size / 2;
  52959. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  52960. };
  52961. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  52962. /**
  52963. * Gets whether the SPS as always visible or not
  52964. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52965. */
  52966. get: function () {
  52967. return this._alwaysVisible;
  52968. },
  52969. /**
  52970. * Sets the SPS as always visible or not
  52971. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52972. */
  52973. set: function (val) {
  52974. this._alwaysVisible = val;
  52975. this.mesh.alwaysSelectAsActiveMesh = val;
  52976. },
  52977. enumerable: true,
  52978. configurable: true
  52979. });
  52980. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  52981. /**
  52982. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52983. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52984. */
  52985. get: function () {
  52986. return this._isVisibilityBoxLocked;
  52987. },
  52988. /**
  52989. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  52990. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  52991. */
  52992. set: function (val) {
  52993. this._isVisibilityBoxLocked = val;
  52994. var boundingInfo = this.mesh.getBoundingInfo();
  52995. boundingInfo.isLocked = val;
  52996. },
  52997. enumerable: true,
  52998. configurable: true
  52999. });
  53000. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53001. /**
  53002. * Gets if `setParticles()` computes the particle rotations or not.
  53003. * Default value : true. The SPS is faster when it's set to false.
  53004. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53005. */
  53006. get: function () {
  53007. return this._computeParticleRotation;
  53008. },
  53009. /**
  53010. * Tells to `setParticles()` to compute the particle rotations or not.
  53011. * Default value : true. The SPS is faster when it's set to false.
  53012. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53013. */
  53014. set: function (val) {
  53015. this._computeParticleRotation = val;
  53016. },
  53017. enumerable: true,
  53018. configurable: true
  53019. });
  53020. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53021. /**
  53022. * Gets if `setParticles()` computes the particle colors or not.
  53023. * Default value : true. The SPS is faster when it's set to false.
  53024. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53025. */
  53026. get: function () {
  53027. return this._computeParticleColor;
  53028. },
  53029. /**
  53030. * Tells to `setParticles()` to compute the particle colors or not.
  53031. * Default value : true. The SPS is faster when it's set to false.
  53032. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53033. */
  53034. set: function (val) {
  53035. this._computeParticleColor = val;
  53036. },
  53037. enumerable: true,
  53038. configurable: true
  53039. });
  53040. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53041. /**
  53042. * Gets if `setParticles()` computes the particle textures or not.
  53043. * Default value : true. The SPS is faster when it's set to false.
  53044. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53045. */
  53046. get: function () {
  53047. return this._computeParticleTexture;
  53048. },
  53049. set: function (val) {
  53050. this._computeParticleTexture = val;
  53051. },
  53052. enumerable: true,
  53053. configurable: true
  53054. });
  53055. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53056. /**
  53057. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53058. * Default value : false. The SPS is faster when it's set to false.
  53059. * Note : the particle custom vertex positions aren't stored values.
  53060. */
  53061. get: function () {
  53062. return this._computeParticleVertex;
  53063. },
  53064. /**
  53065. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53066. * Default value : false. The SPS is faster when it's set to false.
  53067. * Note : the particle custom vertex positions aren't stored values.
  53068. */
  53069. set: function (val) {
  53070. this._computeParticleVertex = val;
  53071. },
  53072. enumerable: true,
  53073. configurable: true
  53074. });
  53075. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53076. /**
  53077. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53078. */
  53079. get: function () {
  53080. return this._computeBoundingBox;
  53081. },
  53082. /**
  53083. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53084. */
  53085. set: function (val) {
  53086. this._computeBoundingBox = val;
  53087. },
  53088. enumerable: true,
  53089. configurable: true
  53090. });
  53091. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53092. /**
  53093. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53094. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53095. * Default : `true`
  53096. */
  53097. get: function () {
  53098. return this._depthSortParticles;
  53099. },
  53100. /**
  53101. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53102. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53103. * Default : `true`
  53104. */
  53105. set: function (val) {
  53106. this._depthSortParticles = val;
  53107. },
  53108. enumerable: true,
  53109. configurable: true
  53110. });
  53111. // =======================================================================
  53112. // Particle behavior logic
  53113. // these following methods may be overwritten by the user to fit his needs
  53114. /**
  53115. * This function does nothing. It may be overwritten to set all the particle first values.
  53116. * The SPS doesn't call this function, you may have to call it by your own.
  53117. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53118. */
  53119. SolidParticleSystem.prototype.initParticles = function () {
  53120. };
  53121. /**
  53122. * This function does nothing. It may be overwritten to recycle a particle.
  53123. * The SPS doesn't call this function, you may have to call it by your own.
  53124. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53125. * @param particle The particle to recycle
  53126. * @returns the recycled particle
  53127. */
  53128. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53129. return particle;
  53130. };
  53131. /**
  53132. * Updates a particle : this function should be overwritten by the user.
  53133. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53134. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53135. * @example : just set a particle position or velocity and recycle conditions
  53136. * @param particle The particle to update
  53137. * @returns the updated particle
  53138. */
  53139. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53140. return particle;
  53141. };
  53142. /**
  53143. * Updates a vertex of a particle : it can be overwritten by the user.
  53144. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53145. * @param particle the current particle
  53146. * @param vertex the current index of the current particle
  53147. * @param pt the index of the current vertex in the particle shape
  53148. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53149. * @example : just set a vertex particle position
  53150. * @returns the updated vertex
  53151. */
  53152. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53153. return vertex;
  53154. };
  53155. /**
  53156. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53157. * This does nothing and may be overwritten by the user.
  53158. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53159. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53160. * @param update the boolean update value actually passed to setParticles()
  53161. */
  53162. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53163. };
  53164. /**
  53165. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53166. * This will be passed three parameters.
  53167. * This does nothing and may be overwritten by the user.
  53168. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53169. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53170. * @param update the boolean update value actually passed to setParticles()
  53171. */
  53172. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53173. };
  53174. return SolidParticleSystem;
  53175. }());
  53176. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53177. })(BABYLON || (BABYLON = {}));
  53178. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53179. var BABYLON;
  53180. (function (BABYLON) {
  53181. var ShaderMaterial = /** @class */ (function (_super) {
  53182. __extends(ShaderMaterial, _super);
  53183. function ShaderMaterial(name, scene, shaderPath, options) {
  53184. var _this = _super.call(this, name, scene) || this;
  53185. _this._textures = {};
  53186. _this._textureArrays = {};
  53187. _this._floats = {};
  53188. _this._ints = {};
  53189. _this._floatsArrays = {};
  53190. _this._colors3 = {};
  53191. _this._colors3Arrays = {};
  53192. _this._colors4 = {};
  53193. _this._vectors2 = {};
  53194. _this._vectors3 = {};
  53195. _this._vectors4 = {};
  53196. _this._matrices = {};
  53197. _this._matrices3x3 = {};
  53198. _this._matrices2x2 = {};
  53199. _this._vectors2Arrays = {};
  53200. _this._vectors3Arrays = {};
  53201. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53202. _this._shaderPath = shaderPath;
  53203. options.needAlphaBlending = options.needAlphaBlending || false;
  53204. options.needAlphaTesting = options.needAlphaTesting || false;
  53205. options.attributes = options.attributes || ["position", "normal", "uv"];
  53206. options.uniforms = options.uniforms || ["worldViewProjection"];
  53207. options.uniformBuffers = options.uniformBuffers || [];
  53208. options.samplers = options.samplers || [];
  53209. options.defines = options.defines || [];
  53210. _this._options = options;
  53211. return _this;
  53212. }
  53213. ShaderMaterial.prototype.getClassName = function () {
  53214. return "ShaderMaterial";
  53215. };
  53216. ShaderMaterial.prototype.needAlphaBlending = function () {
  53217. return this._options.needAlphaBlending;
  53218. };
  53219. ShaderMaterial.prototype.needAlphaTesting = function () {
  53220. return this._options.needAlphaTesting;
  53221. };
  53222. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53223. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53224. this._options.uniforms.push(uniformName);
  53225. }
  53226. };
  53227. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53228. if (this._options.samplers.indexOf(name) === -1) {
  53229. this._options.samplers.push(name);
  53230. }
  53231. this._textures[name] = texture;
  53232. return this;
  53233. };
  53234. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53235. if (this._options.samplers.indexOf(name) === -1) {
  53236. this._options.samplers.push(name);
  53237. }
  53238. this._checkUniform(name);
  53239. this._textureArrays[name] = textures;
  53240. return this;
  53241. };
  53242. ShaderMaterial.prototype.setFloat = function (name, value) {
  53243. this._checkUniform(name);
  53244. this._floats[name] = value;
  53245. return this;
  53246. };
  53247. ShaderMaterial.prototype.setInt = function (name, value) {
  53248. this._checkUniform(name);
  53249. this._ints[name] = value;
  53250. return this;
  53251. };
  53252. ShaderMaterial.prototype.setFloats = function (name, value) {
  53253. this._checkUniform(name);
  53254. this._floatsArrays[name] = value;
  53255. return this;
  53256. };
  53257. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53258. this._checkUniform(name);
  53259. this._colors3[name] = value;
  53260. return this;
  53261. };
  53262. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53263. this._checkUniform(name);
  53264. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53265. color.toArray(arr, arr.length);
  53266. return arr;
  53267. }, []);
  53268. return this;
  53269. };
  53270. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53271. this._checkUniform(name);
  53272. this._colors4[name] = value;
  53273. return this;
  53274. };
  53275. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53276. this._checkUniform(name);
  53277. this._vectors2[name] = value;
  53278. return this;
  53279. };
  53280. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53281. this._checkUniform(name);
  53282. this._vectors3[name] = value;
  53283. return this;
  53284. };
  53285. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53286. this._checkUniform(name);
  53287. this._vectors4[name] = value;
  53288. return this;
  53289. };
  53290. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53291. this._checkUniform(name);
  53292. this._matrices[name] = value;
  53293. return this;
  53294. };
  53295. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53296. this._checkUniform(name);
  53297. this._matrices3x3[name] = value;
  53298. return this;
  53299. };
  53300. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53301. this._checkUniform(name);
  53302. this._matrices2x2[name] = value;
  53303. return this;
  53304. };
  53305. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53306. this._checkUniform(name);
  53307. this._vectors2Arrays[name] = value;
  53308. return this;
  53309. };
  53310. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53311. this._checkUniform(name);
  53312. this._vectors3Arrays[name] = value;
  53313. return this;
  53314. };
  53315. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53316. if (!mesh) {
  53317. return true;
  53318. }
  53319. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53320. return false;
  53321. }
  53322. return false;
  53323. };
  53324. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53325. var scene = this.getScene();
  53326. var engine = scene.getEngine();
  53327. if (!this.checkReadyOnEveryCall) {
  53328. if (this._renderId === scene.getRenderId()) {
  53329. if (this._checkCache(scene, mesh, useInstances)) {
  53330. return true;
  53331. }
  53332. }
  53333. }
  53334. // Instances
  53335. var defines = [];
  53336. var attribs = [];
  53337. var fallbacks = new BABYLON.EffectFallbacks();
  53338. if (useInstances) {
  53339. defines.push("#define INSTANCES");
  53340. }
  53341. for (var index = 0; index < this._options.defines.length; index++) {
  53342. defines.push(this._options.defines[index]);
  53343. }
  53344. for (var index = 0; index < this._options.attributes.length; index++) {
  53345. attribs.push(this._options.attributes[index]);
  53346. }
  53347. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53348. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53349. defines.push("#define VERTEXCOLOR");
  53350. }
  53351. // Bones
  53352. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53355. if (mesh.numBoneInfluencers > 4) {
  53356. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53357. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53358. }
  53359. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53360. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53361. fallbacks.addCPUSkinningFallback(0, mesh);
  53362. if (this._options.uniforms.indexOf("mBones") === -1) {
  53363. this._options.uniforms.push("mBones");
  53364. }
  53365. }
  53366. else {
  53367. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53368. }
  53369. // Textures
  53370. for (var name in this._textures) {
  53371. if (!this._textures[name].isReady()) {
  53372. return false;
  53373. }
  53374. }
  53375. // Alpha test
  53376. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53377. defines.push("#define ALPHATEST");
  53378. }
  53379. var previousEffect = this._effect;
  53380. var join = defines.join("\n");
  53381. this._effect = engine.createEffect(this._shaderPath, {
  53382. attributes: attribs,
  53383. uniformsNames: this._options.uniforms,
  53384. uniformBuffersNames: this._options.uniformBuffers,
  53385. samplers: this._options.samplers,
  53386. defines: join,
  53387. fallbacks: fallbacks,
  53388. onCompiled: this.onCompiled,
  53389. onError: this.onError
  53390. }, engine);
  53391. if (!this._effect.isReady()) {
  53392. return false;
  53393. }
  53394. if (previousEffect !== this._effect) {
  53395. scene.resetCachedMaterial();
  53396. }
  53397. this._renderId = scene.getRenderId();
  53398. return true;
  53399. };
  53400. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53401. var scene = this.getScene();
  53402. if (!this._effect) {
  53403. return;
  53404. }
  53405. if (this._options.uniforms.indexOf("world") !== -1) {
  53406. this._effect.setMatrix("world", world);
  53407. }
  53408. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53409. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53410. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53411. }
  53412. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53413. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53414. }
  53415. };
  53416. ShaderMaterial.prototype.bind = function (world, mesh) {
  53417. // Std values
  53418. this.bindOnlyWorldMatrix(world);
  53419. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53420. if (this._options.uniforms.indexOf("view") !== -1) {
  53421. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53422. }
  53423. if (this._options.uniforms.indexOf("projection") !== -1) {
  53424. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53425. }
  53426. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53427. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53428. }
  53429. // Bones
  53430. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53431. var name;
  53432. // Texture
  53433. for (name in this._textures) {
  53434. this._effect.setTexture(name, this._textures[name]);
  53435. }
  53436. // Texture arrays
  53437. for (name in this._textureArrays) {
  53438. this._effect.setTextureArray(name, this._textureArrays[name]);
  53439. }
  53440. // Int
  53441. for (name in this._ints) {
  53442. this._effect.setInt(name, this._ints[name]);
  53443. }
  53444. // Float
  53445. for (name in this._floats) {
  53446. this._effect.setFloat(name, this._floats[name]);
  53447. }
  53448. // Floats
  53449. for (name in this._floatsArrays) {
  53450. this._effect.setArray(name, this._floatsArrays[name]);
  53451. }
  53452. // Color3
  53453. for (name in this._colors3) {
  53454. this._effect.setColor3(name, this._colors3[name]);
  53455. }
  53456. for (name in this._colors3Arrays) {
  53457. this._effect.setArray3(name, this._colors3Arrays[name]);
  53458. }
  53459. // Color4
  53460. for (name in this._colors4) {
  53461. var color = this._colors4[name];
  53462. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53463. }
  53464. // Vector2
  53465. for (name in this._vectors2) {
  53466. this._effect.setVector2(name, this._vectors2[name]);
  53467. }
  53468. // Vector3
  53469. for (name in this._vectors3) {
  53470. this._effect.setVector3(name, this._vectors3[name]);
  53471. }
  53472. // Vector4
  53473. for (name in this._vectors4) {
  53474. this._effect.setVector4(name, this._vectors4[name]);
  53475. }
  53476. // Matrix
  53477. for (name in this._matrices) {
  53478. this._effect.setMatrix(name, this._matrices[name]);
  53479. }
  53480. // Matrix 3x3
  53481. for (name in this._matrices3x3) {
  53482. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53483. }
  53484. // Matrix 2x2
  53485. for (name in this._matrices2x2) {
  53486. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53487. }
  53488. // Vector2Array
  53489. for (name in this._vectors2Arrays) {
  53490. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53491. }
  53492. // Vector3Array
  53493. for (name in this._vectors3Arrays) {
  53494. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53495. }
  53496. }
  53497. this._afterBind(mesh);
  53498. };
  53499. ShaderMaterial.prototype.getActiveTextures = function () {
  53500. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53501. for (var name in this._textures) {
  53502. activeTextures.push(this._textures[name]);
  53503. }
  53504. for (var name in this._textureArrays) {
  53505. var array = this._textureArrays[name];
  53506. for (var index = 0; index < array.length; index++) {
  53507. activeTextures.push(array[index]);
  53508. }
  53509. }
  53510. return activeTextures;
  53511. };
  53512. ShaderMaterial.prototype.hasTexture = function (texture) {
  53513. if (_super.prototype.hasTexture.call(this, texture)) {
  53514. return true;
  53515. }
  53516. for (var name in this._textures) {
  53517. if (this._textures[name] === texture) {
  53518. return true;
  53519. }
  53520. }
  53521. for (var name in this._textureArrays) {
  53522. var array = this._textureArrays[name];
  53523. for (var index = 0; index < array.length; index++) {
  53524. if (array[index] === texture) {
  53525. return true;
  53526. }
  53527. }
  53528. }
  53529. return false;
  53530. };
  53531. ShaderMaterial.prototype.clone = function (name) {
  53532. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53533. return newShaderMaterial;
  53534. };
  53535. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53536. if (forceDisposeTextures) {
  53537. var name;
  53538. for (name in this._textures) {
  53539. this._textures[name].dispose();
  53540. }
  53541. for (name in this._textureArrays) {
  53542. var array = this._textureArrays[name];
  53543. for (var index = 0; index < array.length; index++) {
  53544. array[index].dispose();
  53545. }
  53546. }
  53547. }
  53548. this._textures = {};
  53549. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53550. };
  53551. ShaderMaterial.prototype.serialize = function () {
  53552. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53553. serializationObject.customType = "BABYLON.ShaderMaterial";
  53554. serializationObject.options = this._options;
  53555. serializationObject.shaderPath = this._shaderPath;
  53556. var name;
  53557. // Texture
  53558. serializationObject.textures = {};
  53559. for (name in this._textures) {
  53560. serializationObject.textures[name] = this._textures[name].serialize();
  53561. }
  53562. // Texture arrays
  53563. serializationObject.textureArrays = {};
  53564. for (name in this._textureArrays) {
  53565. serializationObject.textureArrays[name] = [];
  53566. var array = this._textureArrays[name];
  53567. for (var index = 0; index < array.length; index++) {
  53568. serializationObject.textureArrays[name].push(array[index].serialize());
  53569. }
  53570. }
  53571. // Float
  53572. serializationObject.floats = {};
  53573. for (name in this._floats) {
  53574. serializationObject.floats[name] = this._floats[name];
  53575. }
  53576. // Float s
  53577. serializationObject.FloatArrays = {};
  53578. for (name in this._floatsArrays) {
  53579. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  53580. }
  53581. // Color3
  53582. serializationObject.colors3 = {};
  53583. for (name in this._colors3) {
  53584. serializationObject.colors3[name] = this._colors3[name].asArray();
  53585. }
  53586. // Color3 array
  53587. serializationObject.colors3Arrays = {};
  53588. for (name in this._colors3Arrays) {
  53589. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  53590. }
  53591. // Color4
  53592. serializationObject.colors4 = {};
  53593. for (name in this._colors4) {
  53594. serializationObject.colors4[name] = this._colors4[name].asArray();
  53595. }
  53596. // Vector2
  53597. serializationObject.vectors2 = {};
  53598. for (name in this._vectors2) {
  53599. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  53600. }
  53601. // Vector3
  53602. serializationObject.vectors3 = {};
  53603. for (name in this._vectors3) {
  53604. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  53605. }
  53606. // Vector4
  53607. serializationObject.vectors4 = {};
  53608. for (name in this._vectors4) {
  53609. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  53610. }
  53611. // Matrix
  53612. serializationObject.matrices = {};
  53613. for (name in this._matrices) {
  53614. serializationObject.matrices[name] = this._matrices[name].asArray();
  53615. }
  53616. // Matrix 3x3
  53617. serializationObject.matrices3x3 = {};
  53618. for (name in this._matrices3x3) {
  53619. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  53620. }
  53621. // Matrix 2x2
  53622. serializationObject.matrices2x2 = {};
  53623. for (name in this._matrices2x2) {
  53624. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  53625. }
  53626. // Vector2Array
  53627. serializationObject.vectors2Arrays = {};
  53628. for (name in this._vectors2Arrays) {
  53629. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  53630. }
  53631. // Vector3Array
  53632. serializationObject.vectors3Arrays = {};
  53633. for (name in this._vectors3Arrays) {
  53634. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  53635. }
  53636. return serializationObject;
  53637. };
  53638. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  53639. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  53640. var name;
  53641. // Texture
  53642. for (name in source.textures) {
  53643. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  53644. }
  53645. // Texture arrays
  53646. for (name in source.textureArrays) {
  53647. var array = source.textureArrays[name];
  53648. var textureArray = new Array();
  53649. for (var index = 0; index < array.length; index++) {
  53650. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  53651. }
  53652. material.setTextureArray(name, textureArray);
  53653. }
  53654. // Float
  53655. for (name in source.floats) {
  53656. material.setFloat(name, source.floats[name]);
  53657. }
  53658. // Float s
  53659. for (name in source.floatsArrays) {
  53660. material.setFloats(name, source.floatsArrays[name]);
  53661. }
  53662. // Color3
  53663. for (name in source.colors3) {
  53664. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  53665. }
  53666. // Color3 arrays
  53667. for (name in source.colors3Arrays) {
  53668. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  53669. if (i % 3 === 0) {
  53670. arr.push([num]);
  53671. }
  53672. else {
  53673. arr[arr.length - 1].push(num);
  53674. }
  53675. return arr;
  53676. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  53677. material.setColor3Array(name, colors);
  53678. }
  53679. // Color4
  53680. for (name in source.colors4) {
  53681. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  53682. }
  53683. // Vector2
  53684. for (name in source.vectors2) {
  53685. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  53686. }
  53687. // Vector3
  53688. for (name in source.vectors3) {
  53689. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  53690. }
  53691. // Vector4
  53692. for (name in source.vectors4) {
  53693. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  53694. }
  53695. // Matrix
  53696. for (name in source.matrices) {
  53697. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  53698. }
  53699. // Matrix 3x3
  53700. for (name in source.matrices3x3) {
  53701. material.setMatrix3x3(name, source.matrices3x3[name]);
  53702. }
  53703. // Matrix 2x2
  53704. for (name in source.matrices2x2) {
  53705. material.setMatrix2x2(name, source.matrices2x2[name]);
  53706. }
  53707. // Vector2Array
  53708. for (name in source.vectors2Arrays) {
  53709. material.setArray2(name, source.vectors2Arrays[name]);
  53710. }
  53711. // Vector3Array
  53712. for (name in source.vectors3Arrays) {
  53713. material.setArray3(name, source.vectors3Arrays[name]);
  53714. }
  53715. return material;
  53716. };
  53717. return ShaderMaterial;
  53718. }(BABYLON.Material));
  53719. BABYLON.ShaderMaterial = ShaderMaterial;
  53720. })(BABYLON || (BABYLON = {}));
  53721. //# sourceMappingURL=babylon.shaderMaterial.js.map
  53722. var BABYLON;
  53723. (function (BABYLON) {
  53724. var GroundMesh = /** @class */ (function (_super) {
  53725. __extends(GroundMesh, _super);
  53726. function GroundMesh(name, scene) {
  53727. var _this = _super.call(this, name, scene) || this;
  53728. _this.generateOctree = false;
  53729. return _this;
  53730. }
  53731. GroundMesh.prototype.getClassName = function () {
  53732. return "GroundMesh";
  53733. };
  53734. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  53735. get: function () {
  53736. return Math.min(this._subdivisionsX, this._subdivisionsY);
  53737. },
  53738. enumerable: true,
  53739. configurable: true
  53740. });
  53741. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  53742. get: function () {
  53743. return this._subdivisionsX;
  53744. },
  53745. enumerable: true,
  53746. configurable: true
  53747. });
  53748. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  53749. get: function () {
  53750. return this._subdivisionsY;
  53751. },
  53752. enumerable: true,
  53753. configurable: true
  53754. });
  53755. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  53756. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  53757. this._subdivisionsX = chunksCount;
  53758. this._subdivisionsY = chunksCount;
  53759. this.subdivide(chunksCount);
  53760. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  53761. };
  53762. /**
  53763. * Returns a height (y) value in the Worl system :
  53764. * the ground altitude at the coordinates (x, z) expressed in the World system.
  53765. * Returns the ground y position if (x, z) are outside the ground surface.
  53766. */
  53767. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  53768. var world = this.getWorldMatrix();
  53769. var invMat = BABYLON.Tmp.Matrix[5];
  53770. world.invertToRef(invMat);
  53771. var tmpVect = BABYLON.Tmp.Vector3[8];
  53772. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  53773. x = tmpVect.x;
  53774. z = tmpVect.z;
  53775. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53776. return this.position.y;
  53777. }
  53778. if (!this._heightQuads || this._heightQuads.length == 0) {
  53779. this._initHeightQuads();
  53780. this._computeHeightQuads();
  53781. }
  53782. var facet = this._getFacetAt(x, z);
  53783. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  53784. // return y in the World system
  53785. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  53786. return tmpVect.y;
  53787. };
  53788. /**
  53789. * Returns a normalized vector (Vector3) orthogonal to the ground
  53790. * at the ground coordinates (x, z) expressed in the World system.
  53791. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  53792. */
  53793. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  53794. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  53795. this.getNormalAtCoordinatesToRef(x, z, normal);
  53796. return normal;
  53797. };
  53798. /**
  53799. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  53800. * at the ground coordinates (x, z) expressed in the World system.
  53801. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  53802. * Returns the GroundMesh.
  53803. */
  53804. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  53805. var world = this.getWorldMatrix();
  53806. var tmpMat = BABYLON.Tmp.Matrix[5];
  53807. world.invertToRef(tmpMat);
  53808. var tmpVect = BABYLON.Tmp.Vector3[8];
  53809. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  53810. x = tmpVect.x;
  53811. z = tmpVect.z;
  53812. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  53813. return this;
  53814. }
  53815. if (!this._heightQuads || this._heightQuads.length == 0) {
  53816. this._initHeightQuads();
  53817. this._computeHeightQuads();
  53818. }
  53819. var facet = this._getFacetAt(x, z);
  53820. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  53821. return this;
  53822. };
  53823. /**
  53824. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  53825. * if the ground has been updated.
  53826. * This can be used in the render loop.
  53827. * Returns the GroundMesh.
  53828. */
  53829. GroundMesh.prototype.updateCoordinateHeights = function () {
  53830. if (!this._heightQuads || this._heightQuads.length == 0) {
  53831. this._initHeightQuads();
  53832. }
  53833. this._computeHeightQuads();
  53834. return this;
  53835. };
  53836. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  53837. GroundMesh.prototype._getFacetAt = function (x, z) {
  53838. // retrieve col and row from x, z coordinates in the ground local system
  53839. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  53840. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  53841. var quad = this._heightQuads[row * this._subdivisionsX + col];
  53842. var facet;
  53843. if (z < quad.slope.x * x + quad.slope.y) {
  53844. facet = quad.facet1;
  53845. }
  53846. else {
  53847. facet = quad.facet2;
  53848. }
  53849. return facet;
  53850. };
  53851. // Creates and populates the heightMap array with "facet" elements :
  53852. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  53853. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53854. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53855. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53856. // Returns the GroundMesh.
  53857. GroundMesh.prototype._initHeightQuads = function () {
  53858. var subdivisionsX = this._subdivisionsX;
  53859. var subdivisionsY = this._subdivisionsY;
  53860. this._heightQuads = new Array();
  53861. for (var row = 0; row < subdivisionsY; row++) {
  53862. for (var col = 0; col < subdivisionsX; col++) {
  53863. 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) };
  53864. this._heightQuads[row * subdivisionsX + col] = quad;
  53865. }
  53866. }
  53867. return this;
  53868. };
  53869. // Compute each quad element values and update the the heightMap array :
  53870. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  53871. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  53872. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  53873. // Returns the GroundMesh.
  53874. GroundMesh.prototype._computeHeightQuads = function () {
  53875. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53876. if (!positions) {
  53877. return this;
  53878. }
  53879. var v1 = BABYLON.Tmp.Vector3[3];
  53880. var v2 = BABYLON.Tmp.Vector3[2];
  53881. var v3 = BABYLON.Tmp.Vector3[1];
  53882. var v4 = BABYLON.Tmp.Vector3[0];
  53883. var v1v2 = BABYLON.Tmp.Vector3[4];
  53884. var v1v3 = BABYLON.Tmp.Vector3[5];
  53885. var v1v4 = BABYLON.Tmp.Vector3[6];
  53886. var norm1 = BABYLON.Tmp.Vector3[7];
  53887. var norm2 = BABYLON.Tmp.Vector3[8];
  53888. var i = 0;
  53889. var j = 0;
  53890. var k = 0;
  53891. var cd = 0; // 2D slope coefficient : z = cd * x + h
  53892. var h = 0;
  53893. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  53894. var d2 = 0;
  53895. var subdivisionsX = this._subdivisionsX;
  53896. var subdivisionsY = this._subdivisionsY;
  53897. for (var row = 0; row < subdivisionsY; row++) {
  53898. for (var col = 0; col < subdivisionsX; col++) {
  53899. i = col * 3;
  53900. j = row * (subdivisionsX + 1) * 3;
  53901. k = (row + 1) * (subdivisionsX + 1) * 3;
  53902. v1.x = positions[j + i];
  53903. v1.y = positions[j + i + 1];
  53904. v1.z = positions[j + i + 2];
  53905. v2.x = positions[j + i + 3];
  53906. v2.y = positions[j + i + 4];
  53907. v2.z = positions[j + i + 5];
  53908. v3.x = positions[k + i];
  53909. v3.y = positions[k + i + 1];
  53910. v3.z = positions[k + i + 2];
  53911. v4.x = positions[k + i + 3];
  53912. v4.y = positions[k + i + 4];
  53913. v4.z = positions[k + i + 5];
  53914. // 2D slope V1V4
  53915. cd = (v4.z - v1.z) / (v4.x - v1.x);
  53916. h = v1.z - cd * v1.x; // v1 belongs to the slope
  53917. // facet equations :
  53918. // we compute each facet normal vector
  53919. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  53920. // we compute the value d by applying the equation to v1 which belongs to the plane
  53921. // then we store the facet equation in a Vector4
  53922. v2.subtractToRef(v1, v1v2);
  53923. v3.subtractToRef(v1, v1v3);
  53924. v4.subtractToRef(v1, v1v4);
  53925. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  53926. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  53927. norm1.normalize();
  53928. norm2.normalize();
  53929. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  53930. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  53931. var quad = this._heightQuads[row * subdivisionsX + col];
  53932. quad.slope.copyFromFloats(cd, h);
  53933. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  53934. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  53935. }
  53936. }
  53937. return this;
  53938. };
  53939. GroundMesh.prototype.serialize = function (serializationObject) {
  53940. _super.prototype.serialize.call(this, serializationObject);
  53941. serializationObject.subdivisionsX = this._subdivisionsX;
  53942. serializationObject.subdivisionsY = this._subdivisionsY;
  53943. serializationObject.minX = this._minX;
  53944. serializationObject.maxX = this._maxX;
  53945. serializationObject.minZ = this._minZ;
  53946. serializationObject.maxZ = this._maxZ;
  53947. serializationObject.width = this._width;
  53948. serializationObject.height = this._height;
  53949. };
  53950. GroundMesh.Parse = function (parsedMesh, scene) {
  53951. var result = new GroundMesh(parsedMesh.name, scene);
  53952. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  53953. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  53954. result._minX = parsedMesh.minX;
  53955. result._maxX = parsedMesh.maxX;
  53956. result._minZ = parsedMesh.minZ;
  53957. result._maxZ = parsedMesh.maxZ;
  53958. result._width = parsedMesh.width;
  53959. result._height = parsedMesh.height;
  53960. return result;
  53961. };
  53962. return GroundMesh;
  53963. }(BABYLON.Mesh));
  53964. BABYLON.GroundMesh = GroundMesh;
  53965. })(BABYLON || (BABYLON = {}));
  53966. //# sourceMappingURL=babylon.groundMesh.js.map
  53967. var BABYLON;
  53968. (function (BABYLON) {
  53969. /**
  53970. * Creates an instance based on a source mesh.
  53971. */
  53972. var InstancedMesh = /** @class */ (function (_super) {
  53973. __extends(InstancedMesh, _super);
  53974. function InstancedMesh(name, source) {
  53975. var _this = _super.call(this, name, source.getScene()) || this;
  53976. source.instances.push(_this);
  53977. _this._sourceMesh = source;
  53978. _this.position.copyFrom(source.position);
  53979. _this.rotation.copyFrom(source.rotation);
  53980. _this.scaling.copyFrom(source.scaling);
  53981. if (source.rotationQuaternion) {
  53982. _this.rotationQuaternion = source.rotationQuaternion.clone();
  53983. }
  53984. _this.infiniteDistance = source.infiniteDistance;
  53985. _this.setPivotMatrix(source.getPivotMatrix());
  53986. _this.refreshBoundingInfo();
  53987. _this._syncSubMeshes();
  53988. return _this;
  53989. }
  53990. /**
  53991. * Returns the string "InstancedMesh".
  53992. */
  53993. InstancedMesh.prototype.getClassName = function () {
  53994. return "InstancedMesh";
  53995. };
  53996. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  53997. // Methods
  53998. get: function () {
  53999. return this._sourceMesh.receiveShadows;
  54000. },
  54001. enumerable: true,
  54002. configurable: true
  54003. });
  54004. Object.defineProperty(InstancedMesh.prototype, "material", {
  54005. get: function () {
  54006. return this._sourceMesh.material;
  54007. },
  54008. enumerable: true,
  54009. configurable: true
  54010. });
  54011. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54012. get: function () {
  54013. return this._sourceMesh.visibility;
  54014. },
  54015. enumerable: true,
  54016. configurable: true
  54017. });
  54018. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54019. get: function () {
  54020. return this._sourceMesh.skeleton;
  54021. },
  54022. enumerable: true,
  54023. configurable: true
  54024. });
  54025. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54026. get: function () {
  54027. return this._sourceMesh.renderingGroupId;
  54028. },
  54029. enumerable: true,
  54030. configurable: true
  54031. });
  54032. /**
  54033. * Returns the total number of vertices (integer).
  54034. */
  54035. InstancedMesh.prototype.getTotalVertices = function () {
  54036. return this._sourceMesh.getTotalVertices();
  54037. };
  54038. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54039. get: function () {
  54040. return this._sourceMesh;
  54041. },
  54042. enumerable: true,
  54043. configurable: true
  54044. });
  54045. /**
  54046. * Is this node ready to be used/rendered
  54047. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54048. * @return {boolean} is it ready
  54049. */
  54050. InstancedMesh.prototype.isReady = function (completeCheck) {
  54051. if (completeCheck === void 0) { completeCheck = false; }
  54052. return this._sourceMesh.isReady(completeCheck, true);
  54053. };
  54054. /**
  54055. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54056. */
  54057. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54058. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54059. };
  54060. /**
  54061. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54062. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54063. * The `data` are either a numeric array either a Float32Array.
  54064. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54065. * 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).
  54066. * Note that a new underlying VertexBuffer object is created each call.
  54067. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54068. *
  54069. * Possible `kind` values :
  54070. * - BABYLON.VertexBuffer.PositionKind
  54071. * - BABYLON.VertexBuffer.UVKind
  54072. * - BABYLON.VertexBuffer.UV2Kind
  54073. * - BABYLON.VertexBuffer.UV3Kind
  54074. * - BABYLON.VertexBuffer.UV4Kind
  54075. * - BABYLON.VertexBuffer.UV5Kind
  54076. * - BABYLON.VertexBuffer.UV6Kind
  54077. * - BABYLON.VertexBuffer.ColorKind
  54078. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54079. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54080. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54081. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54082. *
  54083. * Returns the Mesh.
  54084. */
  54085. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54086. if (this.sourceMesh) {
  54087. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54088. }
  54089. return this.sourceMesh;
  54090. };
  54091. /**
  54092. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54093. * If the mesh has no geometry, it is simply returned as it is.
  54094. * The `data` are either a numeric array either a Float32Array.
  54095. * No new underlying VertexBuffer object is created.
  54096. * 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.
  54097. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54098. *
  54099. * Possible `kind` values :
  54100. * - BABYLON.VertexBuffer.PositionKind
  54101. * - BABYLON.VertexBuffer.UVKind
  54102. * - BABYLON.VertexBuffer.UV2Kind
  54103. * - BABYLON.VertexBuffer.UV3Kind
  54104. * - BABYLON.VertexBuffer.UV4Kind
  54105. * - BABYLON.VertexBuffer.UV5Kind
  54106. * - BABYLON.VertexBuffer.UV6Kind
  54107. * - BABYLON.VertexBuffer.ColorKind
  54108. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54109. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54110. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54111. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54112. *
  54113. * Returns the Mesh.
  54114. */
  54115. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54116. if (this.sourceMesh) {
  54117. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54118. }
  54119. return this.sourceMesh;
  54120. };
  54121. /**
  54122. * Sets the mesh indices.
  54123. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54124. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54125. * This method creates a new index buffer each call.
  54126. * Returns the Mesh.
  54127. */
  54128. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54129. if (totalVertices === void 0) { totalVertices = null; }
  54130. if (this.sourceMesh) {
  54131. this.sourceMesh.setIndices(indices, totalVertices);
  54132. }
  54133. return this.sourceMesh;
  54134. };
  54135. /**
  54136. * Boolean : True if the mesh owns the requested kind of data.
  54137. */
  54138. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54139. return this._sourceMesh.isVerticesDataPresent(kind);
  54140. };
  54141. /**
  54142. * Returns an array of indices (IndicesArray).
  54143. */
  54144. InstancedMesh.prototype.getIndices = function () {
  54145. return this._sourceMesh.getIndices();
  54146. };
  54147. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54148. get: function () {
  54149. return this._sourceMesh._positions;
  54150. },
  54151. enumerable: true,
  54152. configurable: true
  54153. });
  54154. /**
  54155. * Sets a new updated BoundingInfo to the mesh.
  54156. * Returns the mesh.
  54157. */
  54158. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54159. var meshBB = this._sourceMesh.getBoundingInfo();
  54160. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54161. this._updateBoundingInfo();
  54162. return this;
  54163. };
  54164. InstancedMesh.prototype._preActivate = function () {
  54165. if (this._currentLOD) {
  54166. this._currentLOD._preActivate();
  54167. }
  54168. return this;
  54169. };
  54170. InstancedMesh.prototype._activate = function (renderId) {
  54171. if (this._currentLOD) {
  54172. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54173. }
  54174. return this;
  54175. };
  54176. /**
  54177. * Returns the current associated LOD AbstractMesh.
  54178. */
  54179. InstancedMesh.prototype.getLOD = function (camera) {
  54180. if (!camera) {
  54181. return this;
  54182. }
  54183. var boundingInfo = this.getBoundingInfo();
  54184. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54185. if (this._currentLOD === this.sourceMesh) {
  54186. return this;
  54187. }
  54188. return this._currentLOD;
  54189. };
  54190. InstancedMesh.prototype._syncSubMeshes = function () {
  54191. this.releaseSubMeshes();
  54192. if (this._sourceMesh.subMeshes) {
  54193. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54194. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54195. }
  54196. }
  54197. return this;
  54198. };
  54199. InstancedMesh.prototype._generatePointsArray = function () {
  54200. return this._sourceMesh._generatePointsArray();
  54201. };
  54202. /**
  54203. * Creates a new InstancedMesh from the current mesh.
  54204. * - name (string) : the cloned mesh name
  54205. * - newParent (optional Node) : the optional Node to parent the clone to.
  54206. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54207. *
  54208. * Returns the clone.
  54209. */
  54210. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54211. var result = this._sourceMesh.createInstance(name);
  54212. // Deep copy
  54213. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54214. // Bounding info
  54215. this.refreshBoundingInfo();
  54216. // Parent
  54217. if (newParent) {
  54218. result.parent = newParent;
  54219. }
  54220. if (!doNotCloneChildren) {
  54221. // Children
  54222. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54223. var mesh = this.getScene().meshes[index];
  54224. if (mesh.parent === this) {
  54225. mesh.clone(mesh.name, result);
  54226. }
  54227. }
  54228. }
  54229. result.computeWorldMatrix(true);
  54230. return result;
  54231. };
  54232. /**
  54233. * Disposes the InstancedMesh.
  54234. * Returns nothing.
  54235. */
  54236. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54237. // Remove from mesh
  54238. var index = this._sourceMesh.instances.indexOf(this);
  54239. this._sourceMesh.instances.splice(index, 1);
  54240. _super.prototype.dispose.call(this, doNotRecurse);
  54241. };
  54242. return InstancedMesh;
  54243. }(BABYLON.AbstractMesh));
  54244. BABYLON.InstancedMesh = InstancedMesh;
  54245. })(BABYLON || (BABYLON = {}));
  54246. //# sourceMappingURL=babylon.instancedMesh.js.map
  54247. var BABYLON;
  54248. (function (BABYLON) {
  54249. var LinesMesh = /** @class */ (function (_super) {
  54250. __extends(LinesMesh, _super);
  54251. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54252. if (scene === void 0) { scene = null; }
  54253. if (parent === void 0) { parent = null; }
  54254. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54255. _this.useVertexColor = useVertexColor;
  54256. _this.useVertexAlpha = useVertexAlpha;
  54257. _this.color = new BABYLON.Color3(1, 1, 1);
  54258. _this.alpha = 1;
  54259. if (source) {
  54260. _this.color = source.color.clone();
  54261. _this.alpha = source.alpha;
  54262. _this.useVertexColor = source.useVertexColor;
  54263. _this.useVertexAlpha = source.useVertexAlpha;
  54264. }
  54265. _this._intersectionThreshold = 0.1;
  54266. var defines = [];
  54267. var options = {
  54268. attributes: [BABYLON.VertexBuffer.PositionKind],
  54269. uniforms: ["world", "viewProjection"],
  54270. needAlphaBlending: true,
  54271. defines: defines
  54272. };
  54273. if (useVertexAlpha === false) {
  54274. options.needAlphaBlending = false;
  54275. }
  54276. if (!useVertexColor) {
  54277. options.uniforms.push("color");
  54278. }
  54279. else {
  54280. options.defines.push("#define VERTEXCOLOR");
  54281. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54282. }
  54283. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54284. return _this;
  54285. }
  54286. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54287. /**
  54288. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54289. * This margin is expressed in world space coordinates, so its value may vary.
  54290. * Default value is 0.1
  54291. * @returns the intersection Threshold value.
  54292. */
  54293. get: function () {
  54294. return this._intersectionThreshold;
  54295. },
  54296. /**
  54297. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54298. * This margin is expressed in world space coordinates, so its value may vary.
  54299. * @param value the new threshold to apply
  54300. */
  54301. set: function (value) {
  54302. if (this._intersectionThreshold === value) {
  54303. return;
  54304. }
  54305. this._intersectionThreshold = value;
  54306. if (this.geometry) {
  54307. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54308. }
  54309. },
  54310. enumerable: true,
  54311. configurable: true
  54312. });
  54313. /**
  54314. * Returns the string "LineMesh"
  54315. */
  54316. LinesMesh.prototype.getClassName = function () {
  54317. return "LinesMesh";
  54318. };
  54319. Object.defineProperty(LinesMesh.prototype, "material", {
  54320. get: function () {
  54321. return this._colorShader;
  54322. },
  54323. set: function (value) {
  54324. // Do nothing
  54325. },
  54326. enumerable: true,
  54327. configurable: true
  54328. });
  54329. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54330. get: function () {
  54331. return false;
  54332. },
  54333. enumerable: true,
  54334. configurable: true
  54335. });
  54336. LinesMesh.prototype.createInstance = function (name) {
  54337. throw new Error("LinesMeshes do not support createInstance.");
  54338. };
  54339. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54340. if (!this._geometry) {
  54341. return this;
  54342. }
  54343. // VBOs
  54344. this._geometry._bind(this._colorShader.getEffect());
  54345. // Color
  54346. if (!this.useVertexColor) {
  54347. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54348. }
  54349. return this;
  54350. };
  54351. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54352. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54353. return this;
  54354. }
  54355. var engine = this.getScene().getEngine();
  54356. // Draw order
  54357. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54358. return this;
  54359. };
  54360. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54361. this._colorShader.dispose();
  54362. _super.prototype.dispose.call(this, doNotRecurse);
  54363. };
  54364. /**
  54365. * Returns a new LineMesh object cloned from the current one.
  54366. */
  54367. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54368. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54369. };
  54370. return LinesMesh;
  54371. }(BABYLON.Mesh));
  54372. BABYLON.LinesMesh = LinesMesh;
  54373. })(BABYLON || (BABYLON = {}));
  54374. //# sourceMappingURL=babylon.linesMesh.js.map
  54375. var BABYLON;
  54376. (function (BABYLON) {
  54377. var MeshBuilder = /** @class */ (function () {
  54378. function MeshBuilder() {
  54379. }
  54380. MeshBuilder.updateSideOrientation = function (orientation) {
  54381. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54382. return BABYLON.Mesh.DOUBLESIDE;
  54383. }
  54384. if (orientation === undefined || orientation === null) {
  54385. return BABYLON.Mesh.FRONTSIDE;
  54386. }
  54387. return orientation;
  54388. };
  54389. /**
  54390. * Creates a box mesh.
  54391. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54392. * The parameter `size` sets the size (float) of each box side (default 1).
  54393. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54394. * 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).
  54395. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54396. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54397. * 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).
  54398. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54399. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54400. */
  54401. MeshBuilder.CreateBox = function (name, options, scene) {
  54402. if (scene === void 0) { scene = null; }
  54403. var box = new BABYLON.Mesh(name, scene);
  54404. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54405. box._originalBuilderSideOrientation = options.sideOrientation;
  54406. var vertexData = BABYLON.VertexData.CreateBox(options);
  54407. vertexData.applyToMesh(box, options.updatable);
  54408. return box;
  54409. };
  54410. /**
  54411. * Creates a sphere mesh.
  54412. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54413. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54414. * 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`).
  54415. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54416. * 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
  54417. * 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).
  54418. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54419. * 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).
  54420. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54422. */
  54423. MeshBuilder.CreateSphere = function (name, options, scene) {
  54424. var sphere = new BABYLON.Mesh(name, scene);
  54425. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54426. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54427. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54428. vertexData.applyToMesh(sphere, options.updatable);
  54429. return sphere;
  54430. };
  54431. /**
  54432. * Creates a plane polygonal mesh. By default, this is a disc.
  54433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54434. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54435. * 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.
  54436. * 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
  54437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54438. * 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).
  54439. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54441. */
  54442. MeshBuilder.CreateDisc = function (name, options, scene) {
  54443. if (scene === void 0) { scene = null; }
  54444. var disc = new BABYLON.Mesh(name, scene);
  54445. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54446. disc._originalBuilderSideOrientation = options.sideOrientation;
  54447. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54448. vertexData.applyToMesh(disc, options.updatable);
  54449. return disc;
  54450. };
  54451. /**
  54452. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54453. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54454. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54455. * 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`).
  54456. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54457. * 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.
  54458. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54459. * 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).
  54460. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54462. */
  54463. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54464. var sphere = new BABYLON.Mesh(name, scene);
  54465. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54466. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54467. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54468. vertexData.applyToMesh(sphere, options.updatable);
  54469. return sphere;
  54470. };
  54471. ;
  54472. /**
  54473. * Creates a ribbon mesh.
  54474. * 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.
  54475. *
  54476. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54477. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54478. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54479. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54480. * 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.
  54481. * 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.
  54482. * 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
  54483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54484. * 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).
  54485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54486. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54487. * 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.
  54488. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54489. * 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
  54490. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54491. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54492. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54493. */
  54494. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54495. if (scene === void 0) { scene = null; }
  54496. var pathArray = options.pathArray;
  54497. var closeArray = options.closeArray;
  54498. var closePath = options.closePath;
  54499. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54500. var instance = options.instance;
  54501. var updatable = options.updatable;
  54502. if (instance) {
  54503. // positionFunction : ribbon case
  54504. // only pathArray and sideOrientation parameters are taken into account for positions update
  54505. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54506. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54507. var positionFunction = function (positions) {
  54508. var minlg = pathArray[0].length;
  54509. var i = 0;
  54510. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54511. for (var si = 1; si <= ns; si++) {
  54512. for (var p = 0; p < pathArray.length; p++) {
  54513. var path = pathArray[p];
  54514. var l = path.length;
  54515. minlg = (minlg < l) ? minlg : l;
  54516. var j = 0;
  54517. while (j < minlg) {
  54518. positions[i] = path[j].x;
  54519. positions[i + 1] = path[j].y;
  54520. positions[i + 2] = path[j].z;
  54521. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54522. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54523. }
  54524. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54525. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54526. }
  54527. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54528. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54529. }
  54530. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54531. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54532. }
  54533. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54534. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54535. }
  54536. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54537. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54538. }
  54539. j++;
  54540. i += 3;
  54541. }
  54542. if (instance._closePath) {
  54543. positions[i] = path[0].x;
  54544. positions[i + 1] = path[0].y;
  54545. positions[i + 2] = path[0].z;
  54546. i += 3;
  54547. }
  54548. }
  54549. }
  54550. };
  54551. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54552. positionFunction(positions);
  54553. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54554. instance._boundingInfo.update(instance._worldMatrix);
  54555. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54556. if (options.colors) {
  54557. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54558. for (var c = 0; c < options.colors.length; c++) {
  54559. colors[c * 4] = options.colors[c].r;
  54560. colors[c * 4 + 1] = options.colors[c].g;
  54561. colors[c * 4 + 2] = options.colors[c].b;
  54562. colors[c * 4 + 3] = options.colors[c].a;
  54563. }
  54564. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  54565. }
  54566. if (options.uvs) {
  54567. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54568. for (var i = 0; i < options.uvs.length; i++) {
  54569. uvs[i * 2] = options.uvs[i].x;
  54570. uvs[i * 2 + 1] = options.uvs[i].y;
  54571. }
  54572. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  54573. }
  54574. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  54575. var indices = instance.getIndices();
  54576. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54577. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  54578. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  54579. if (instance._closePath) {
  54580. var indexFirst = 0;
  54581. var indexLast = 0;
  54582. for (var p = 0; p < pathArray.length; p++) {
  54583. indexFirst = instance._idx[p] * 3;
  54584. if (p + 1 < pathArray.length) {
  54585. indexLast = (instance._idx[p + 1] - 1) * 3;
  54586. }
  54587. else {
  54588. indexLast = normals.length - 3;
  54589. }
  54590. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  54591. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  54592. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  54593. normals[indexLast] = normals[indexFirst];
  54594. normals[indexLast + 1] = normals[indexFirst + 1];
  54595. normals[indexLast + 2] = normals[indexFirst + 2];
  54596. }
  54597. }
  54598. if (!(instance.areNormalsFrozen)) {
  54599. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  54600. }
  54601. }
  54602. return instance;
  54603. }
  54604. else {
  54605. var ribbon = new BABYLON.Mesh(name, scene);
  54606. ribbon._originalBuilderSideOrientation = sideOrientation;
  54607. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  54608. if (closePath) {
  54609. ribbon._idx = vertexData._idx;
  54610. }
  54611. ribbon._closePath = closePath;
  54612. ribbon._closeArray = closeArray;
  54613. vertexData.applyToMesh(ribbon, updatable);
  54614. return ribbon;
  54615. }
  54616. };
  54617. /**
  54618. * Creates a cylinder or a cone mesh.
  54619. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  54620. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  54621. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  54622. * 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.
  54623. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  54624. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  54625. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  54626. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  54627. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  54628. * 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).
  54629. * 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
  54630. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  54631. * 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
  54632. * 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.
  54633. * If `enclose` is false, a ring surface is one element.
  54634. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  54635. * 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
  54636. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54637. * 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).
  54638. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54639. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54640. */
  54641. MeshBuilder.CreateCylinder = function (name, options, scene) {
  54642. var cylinder = new BABYLON.Mesh(name, scene);
  54643. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54644. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  54645. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  54646. vertexData.applyToMesh(cylinder, options.updatable);
  54647. return cylinder;
  54648. };
  54649. /**
  54650. * Creates a torus mesh.
  54651. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  54652. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  54653. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  54654. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  54655. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54656. * 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).
  54657. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54658. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54659. */
  54660. MeshBuilder.CreateTorus = function (name, options, scene) {
  54661. var torus = new BABYLON.Mesh(name, scene);
  54662. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54663. torus._originalBuilderSideOrientation = options.sideOrientation;
  54664. var vertexData = BABYLON.VertexData.CreateTorus(options);
  54665. vertexData.applyToMesh(torus, options.updatable);
  54666. return torus;
  54667. };
  54668. /**
  54669. * Creates a torus knot mesh.
  54670. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  54671. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  54672. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  54673. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  54674. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  54675. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54676. * 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).
  54677. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54679. */
  54680. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  54681. var torusKnot = new BABYLON.Mesh(name, scene);
  54682. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54683. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  54684. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  54685. vertexData.applyToMesh(torusKnot, options.updatable);
  54686. return torusKnot;
  54687. };
  54688. /**
  54689. * Creates a line system mesh.
  54690. * A line system is a pool of many lines gathered in a single mesh.
  54691. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  54692. * 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.
  54693. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  54694. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  54695. * 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
  54696. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  54697. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  54698. * 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
  54699. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  54700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54701. */
  54702. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  54703. var instance = options.instance;
  54704. var lines = options.lines;
  54705. var colors = options.colors;
  54706. if (instance) {
  54707. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54708. var vertexColor;
  54709. var lineColors;
  54710. if (colors) {
  54711. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54712. }
  54713. var i = 0;
  54714. var c = 0;
  54715. for (var l = 0; l < lines.length; l++) {
  54716. var points = lines[l];
  54717. for (var p = 0; p < points.length; p++) {
  54718. positions[i] = points[p].x;
  54719. positions[i + 1] = points[p].y;
  54720. positions[i + 2] = points[p].z;
  54721. if (colors && vertexColor) {
  54722. lineColors = colors[l];
  54723. vertexColor[c] = lineColors[p].r;
  54724. vertexColor[c + 1] = lineColors[p].g;
  54725. vertexColor[c + 2] = lineColors[p].b;
  54726. vertexColor[c + 3] = lineColors[p].a;
  54727. c += 4;
  54728. }
  54729. i += 3;
  54730. }
  54731. }
  54732. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54733. if (colors && vertexColor) {
  54734. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  54735. }
  54736. return instance;
  54737. }
  54738. // line system creation
  54739. var useVertexColor = (colors) ? true : false;
  54740. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  54741. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  54742. vertexData.applyToMesh(lineSystem, options.updatable);
  54743. return lineSystem;
  54744. };
  54745. /**
  54746. * Creates a line mesh.
  54747. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  54748. * 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.
  54749. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54750. * The parameter `points` is an array successive Vector3.
  54751. * 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
  54752. * The optional parameter `colors` is an array of successive Color4, one per line point.
  54753. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  54754. * When updating an instance, remember that only point positions can change, not the number of points.
  54755. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54756. */
  54757. MeshBuilder.CreateLines = function (name, options, scene) {
  54758. if (scene === void 0) { scene = null; }
  54759. var colors = (options.colors) ? [options.colors] : null;
  54760. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  54761. return lines;
  54762. };
  54763. /**
  54764. * Creates a dashed line mesh.
  54765. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  54766. * 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.
  54767. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  54768. * The parameter `points` is an array successive Vector3.
  54769. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  54770. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  54771. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  54772. * 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
  54773. * When updating an instance, remember that only point positions can change, not the number of points.
  54774. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54775. */
  54776. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  54777. if (scene === void 0) { scene = null; }
  54778. var points = options.points;
  54779. var instance = options.instance;
  54780. var gapSize = options.gapSize || 1;
  54781. var dashSize = options.dashSize || 3;
  54782. if (instance) {
  54783. var positionFunction = function (positions) {
  54784. var curvect = BABYLON.Vector3.Zero();
  54785. var nbSeg = positions.length / 6;
  54786. var lg = 0;
  54787. var nb = 0;
  54788. var shft = 0;
  54789. var dashshft = 0;
  54790. var curshft = 0;
  54791. var p = 0;
  54792. var i = 0;
  54793. var j = 0;
  54794. for (i = 0; i < points.length - 1; i++) {
  54795. points[i + 1].subtractToRef(points[i], curvect);
  54796. lg += curvect.length();
  54797. }
  54798. shft = lg / nbSeg;
  54799. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  54800. for (i = 0; i < points.length - 1; i++) {
  54801. points[i + 1].subtractToRef(points[i], curvect);
  54802. nb = Math.floor(curvect.length() / shft);
  54803. curvect.normalize();
  54804. j = 0;
  54805. while (j < nb && p < positions.length) {
  54806. curshft = shft * j;
  54807. positions[p] = points[i].x + curshft * curvect.x;
  54808. positions[p + 1] = points[i].y + curshft * curvect.y;
  54809. positions[p + 2] = points[i].z + curshft * curvect.z;
  54810. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  54811. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  54812. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  54813. p += 6;
  54814. j++;
  54815. }
  54816. }
  54817. while (p < positions.length) {
  54818. positions[p] = points[i].x;
  54819. positions[p + 1] = points[i].y;
  54820. positions[p + 2] = points[i].z;
  54821. p += 3;
  54822. }
  54823. };
  54824. instance.updateMeshPositions(positionFunction, false);
  54825. return instance;
  54826. }
  54827. // dashed lines creation
  54828. var dashedLines = new BABYLON.LinesMesh(name, scene);
  54829. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  54830. vertexData.applyToMesh(dashedLines, options.updatable);
  54831. dashedLines.dashSize = dashSize;
  54832. dashedLines.gapSize = gapSize;
  54833. return dashedLines;
  54834. };
  54835. /**
  54836. * Creates an extruded shape mesh.
  54837. * 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.
  54838. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  54839. *
  54840. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54841. * 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
  54842. * extruded along the Z axis.
  54843. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54844. * 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.
  54845. * The parameter `scale` (float, default 1) is the value to scale the shape.
  54846. * 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
  54847. * 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
  54848. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54849. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54850. * 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).
  54851. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54852. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54853. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54854. */
  54855. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  54856. if (scene === void 0) { scene = null; }
  54857. var path = options.path;
  54858. var shape = options.shape;
  54859. var scale = options.scale || 1;
  54860. var rotation = options.rotation || 0;
  54861. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54862. var updatable = options.updatable;
  54863. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54864. var instance = options.instance || null;
  54865. var invertUV = options.invertUV || false;
  54866. 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);
  54867. };
  54868. /**
  54869. * Creates an custom extruded shape mesh.
  54870. * 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.
  54871. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  54872. *
  54873. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  54874. * 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
  54875. * extruded along the Z axis.
  54876. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  54877. * 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
  54878. * and the distance of this point from the begining of the path :
  54879. * ```javascript
  54880. * var rotationFunction = function(i, distance) {
  54881. * // do things
  54882. * return rotationValue; }
  54883. * ```
  54884. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  54885. * 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
  54886. * and the distance of this point from the begining of the path :
  54887. * ```javascript
  54888. * var scaleFunction = function(i, distance) {
  54889. * // do things
  54890. * return scaleValue;}
  54891. * ```
  54892. * It must returns a float value that will be the scale value applied to the shape on each path point.
  54893. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  54894. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  54895. * 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
  54896. * 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
  54897. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  54898. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54899. * 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).
  54900. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54901. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54903. */
  54904. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  54905. var path = options.path;
  54906. var shape = options.shape;
  54907. var scaleFunction = options.scaleFunction || (function () { return 1; });
  54908. var rotationFunction = options.rotationFunction || (function () { return 0; });
  54909. var ribbonCloseArray = options.ribbonCloseArray || false;
  54910. var ribbonClosePath = options.ribbonClosePath || false;
  54911. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  54912. var updatable = options.updatable;
  54913. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54914. var instance = options.instance;
  54915. var invertUV = options.invertUV || false;
  54916. 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);
  54917. };
  54918. /**
  54919. * Creates lathe mesh.
  54920. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  54921. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  54922. *
  54923. * 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
  54924. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  54925. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  54926. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  54927. * 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.
  54928. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  54929. * 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
  54930. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54931. * 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).
  54932. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54933. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54934. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54935. */
  54936. MeshBuilder.CreateLathe = function (name, options, scene) {
  54937. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  54938. var closed = (options.closed === undefined) ? true : options.closed;
  54939. var shape = options.shape;
  54940. var radius = options.radius || 1;
  54941. var tessellation = options.tessellation || 64;
  54942. var updatable = options.updatable;
  54943. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54944. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  54945. var pi2 = Math.PI * 2;
  54946. var paths = new Array();
  54947. var invertUV = options.invertUV || false;
  54948. var i = 0;
  54949. var p = 0;
  54950. var step = pi2 / tessellation * arc;
  54951. var rotated;
  54952. var path = new Array();
  54953. ;
  54954. for (i = 0; i <= tessellation; i++) {
  54955. var path = [];
  54956. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  54957. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  54958. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  54959. }
  54960. for (p = 0; p < shape.length; p++) {
  54961. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  54962. path.push(rotated);
  54963. }
  54964. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  54965. 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));
  54966. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  54967. }
  54968. paths.push(path);
  54969. }
  54970. // lathe ribbon
  54971. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  54972. return lathe;
  54973. };
  54974. /**
  54975. * Creates a plane mesh.
  54976. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  54977. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  54978. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  54979. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  54980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54981. * 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).
  54982. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54983. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54984. */
  54985. MeshBuilder.CreatePlane = function (name, options, scene) {
  54986. var plane = new BABYLON.Mesh(name, scene);
  54987. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54988. plane._originalBuilderSideOrientation = options.sideOrientation;
  54989. var vertexData = BABYLON.VertexData.CreatePlane(options);
  54990. vertexData.applyToMesh(plane, options.updatable);
  54991. if (options.sourcePlane) {
  54992. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  54993. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  54994. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  54995. plane.rotate(vectorProduct, product);
  54996. }
  54997. return plane;
  54998. };
  54999. /**
  55000. * Creates a ground mesh.
  55001. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55002. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55003. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55004. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55005. */
  55006. MeshBuilder.CreateGround = function (name, options, scene) {
  55007. var ground = new BABYLON.GroundMesh(name, scene);
  55008. ground._setReady(false);
  55009. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55010. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55011. ground._width = options.width || 1;
  55012. ground._height = options.height || 1;
  55013. ground._maxX = ground._width / 2;
  55014. ground._maxZ = ground._height / 2;
  55015. ground._minX = -ground._maxX;
  55016. ground._minZ = -ground._maxZ;
  55017. var vertexData = BABYLON.VertexData.CreateGround(options);
  55018. vertexData.applyToMesh(ground, options.updatable);
  55019. ground._setReady(true);
  55020. return ground;
  55021. };
  55022. /**
  55023. * Creates a tiled ground mesh.
  55024. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55025. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55026. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55027. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55028. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55029. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55030. * numbers of subdivisions on the ground width and height of each tile.
  55031. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55032. */
  55033. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55034. var tiledGround = new BABYLON.Mesh(name, scene);
  55035. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55036. vertexData.applyToMesh(tiledGround, options.updatable);
  55037. return tiledGround;
  55038. };
  55039. /**
  55040. * Creates a ground mesh from a height map.
  55041. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55042. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55043. * The parameter `url` sets the URL of the height map image resource.
  55044. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55045. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55046. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55047. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55048. * 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.
  55049. * 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).
  55050. * This function is passed the newly built mesh :
  55051. * ```javascript
  55052. * function(mesh) { // do things
  55053. * return; }
  55054. * ```
  55055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55056. */
  55057. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55058. var width = options.width || 10.0;
  55059. var height = options.height || 10.0;
  55060. var subdivisions = options.subdivisions || 1 | 0;
  55061. var minHeight = options.minHeight || 0.0;
  55062. var maxHeight = options.maxHeight || 1.0;
  55063. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55064. var updatable = options.updatable;
  55065. var onReady = options.onReady;
  55066. var ground = new BABYLON.GroundMesh(name, scene);
  55067. ground._subdivisionsX = subdivisions;
  55068. ground._subdivisionsY = subdivisions;
  55069. ground._width = width;
  55070. ground._height = height;
  55071. ground._maxX = ground._width / 2.0;
  55072. ground._maxZ = ground._height / 2.0;
  55073. ground._minX = -ground._maxX;
  55074. ground._minZ = -ground._maxZ;
  55075. ground._setReady(false);
  55076. var onload = function (img) {
  55077. // Getting height map data
  55078. var canvas = document.createElement("canvas");
  55079. var context = canvas.getContext("2d");
  55080. if (!context) {
  55081. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55082. }
  55083. if (scene.isDisposed) {
  55084. return;
  55085. }
  55086. var bufferWidth = img.width;
  55087. var bufferHeight = img.height;
  55088. canvas.width = bufferWidth;
  55089. canvas.height = bufferHeight;
  55090. context.drawImage(img, 0, 0);
  55091. // Create VertexData from map data
  55092. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55093. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55094. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55095. width: width, height: height,
  55096. subdivisions: subdivisions,
  55097. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55098. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55099. });
  55100. vertexData.applyToMesh(ground, updatable);
  55101. ground._setReady(true);
  55102. //execute ready callback, if set
  55103. if (onReady) {
  55104. onReady(ground);
  55105. }
  55106. };
  55107. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55108. return ground;
  55109. };
  55110. /**
  55111. * Creates a polygon mesh.
  55112. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55113. * 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.
  55114. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55115. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55116. * 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).
  55117. * Remember you can only change the shape positions, not their number when updating a polygon.
  55118. */
  55119. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55120. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55121. var shape = options.shape;
  55122. var holes = options.holes || [];
  55123. var depth = options.depth || 0;
  55124. var contours = [];
  55125. var hole = [];
  55126. for (var i = 0; i < shape.length; i++) {
  55127. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55128. }
  55129. var epsilon = 0.00000001;
  55130. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55131. contours.pop();
  55132. }
  55133. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55134. for (var hNb = 0; hNb < holes.length; hNb++) {
  55135. hole = [];
  55136. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55137. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55138. }
  55139. polygonTriangulation.addHole(hole);
  55140. }
  55141. var polygon = polygonTriangulation.build(options.updatable, depth);
  55142. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55143. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55144. vertexData.applyToMesh(polygon, options.updatable);
  55145. return polygon;
  55146. };
  55147. ;
  55148. /**
  55149. * Creates an extruded polygon mesh, with depth in the Y direction.
  55150. * 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).
  55151. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55152. */
  55153. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55154. return MeshBuilder.CreatePolygon(name, options, scene);
  55155. };
  55156. ;
  55157. /**
  55158. * Creates a tube mesh.
  55159. * 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.
  55160. *
  55161. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55162. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55163. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55164. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55165. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55166. * 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.
  55167. * It must return a radius value (positive float) :
  55168. * ```javascript
  55169. * var radiusFunction = function(i, distance) {
  55170. * // do things
  55171. * return radius; }
  55172. * ```
  55173. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55174. * 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
  55175. * 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
  55176. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55177. * 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).
  55178. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55179. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55181. */
  55182. MeshBuilder.CreateTube = function (name, options, scene) {
  55183. var path = options.path;
  55184. var instance = options.instance;
  55185. var radius = 1.0;
  55186. if (instance) {
  55187. radius = instance.radius;
  55188. }
  55189. if (options.radius !== undefined) {
  55190. radius = options.radius;
  55191. }
  55192. ;
  55193. var tessellation = options.tessellation || 64 | 0;
  55194. var radiusFunction = options.radiusFunction || null;
  55195. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55196. var invertUV = options.invertUV || false;
  55197. var updatable = options.updatable;
  55198. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55199. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55200. // tube geometry
  55201. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55202. var tangents = path3D.getTangents();
  55203. var normals = path3D.getNormals();
  55204. var distances = path3D.getDistances();
  55205. var pi2 = Math.PI * 2;
  55206. var step = pi2 / tessellation * arc;
  55207. var returnRadius = function () { return radius; };
  55208. var radiusFunctionFinal = radiusFunction || returnRadius;
  55209. var circlePath;
  55210. var rad;
  55211. var normal;
  55212. var rotated;
  55213. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55214. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55215. for (var i = 0; i < path.length; i++) {
  55216. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55217. circlePath = Array(); // current circle array
  55218. normal = normals[i]; // current normal
  55219. for (var t = 0; t < tessellation; t++) {
  55220. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55221. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55222. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55223. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55224. circlePath[t] = rotated;
  55225. }
  55226. circlePaths[index] = circlePath;
  55227. index++;
  55228. }
  55229. // cap
  55230. var capPath = function (nbPoints, pathIndex) {
  55231. var pointCap = Array();
  55232. for (var i = 0; i < nbPoints; i++) {
  55233. pointCap.push(path[pathIndex]);
  55234. }
  55235. return pointCap;
  55236. };
  55237. switch (cap) {
  55238. case BABYLON.Mesh.NO_CAP:
  55239. break;
  55240. case BABYLON.Mesh.CAP_START:
  55241. circlePaths[0] = capPath(tessellation, 0);
  55242. circlePaths[1] = circlePaths[2].slice(0);
  55243. break;
  55244. case BABYLON.Mesh.CAP_END:
  55245. circlePaths[index] = circlePaths[index - 1].slice(0);
  55246. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55247. break;
  55248. case BABYLON.Mesh.CAP_ALL:
  55249. circlePaths[0] = capPath(tessellation, 0);
  55250. circlePaths[1] = circlePaths[2].slice(0);
  55251. circlePaths[index] = circlePaths[index - 1].slice(0);
  55252. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55253. break;
  55254. default:
  55255. break;
  55256. }
  55257. return circlePaths;
  55258. };
  55259. var path3D;
  55260. var pathArray;
  55261. if (instance) {
  55262. var arc = options.arc || instance.arc;
  55263. path3D = (instance.path3D).update(path);
  55264. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55265. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55266. instance.path3D = path3D;
  55267. instance.pathArray = pathArray;
  55268. instance.arc = arc;
  55269. instance.radius = radius;
  55270. return instance;
  55271. }
  55272. // tube creation
  55273. path3D = new BABYLON.Path3D(path);
  55274. var newPathArray = new Array();
  55275. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55276. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55277. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55278. tube.pathArray = pathArray;
  55279. tube.path3D = path3D;
  55280. tube.tessellation = tessellation;
  55281. tube.cap = cap;
  55282. tube.arc = options.arc;
  55283. tube.radius = radius;
  55284. return tube;
  55285. };
  55286. /**
  55287. * Creates a polyhedron mesh.
  55288. *
  55289. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55290. * 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
  55291. * to choose the wanted type.
  55292. * The parameter `size` (positive float, default 1) sets the polygon size.
  55293. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55294. * 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`.
  55295. * 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
  55296. * 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)`).
  55297. * 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
  55298. * 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.
  55299. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55300. * 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).
  55301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55303. */
  55304. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55305. var polyhedron = new BABYLON.Mesh(name, scene);
  55306. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55307. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55308. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55309. vertexData.applyToMesh(polyhedron, options.updatable);
  55310. return polyhedron;
  55311. };
  55312. /**
  55313. * Creates a decal mesh.
  55314. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55315. * 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.
  55316. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55317. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55318. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55319. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55320. */
  55321. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55322. var indices = sourceMesh.getIndices();
  55323. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55324. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55325. var position = options.position || BABYLON.Vector3.Zero();
  55326. var normal = options.normal || BABYLON.Vector3.Up();
  55327. var size = options.size || BABYLON.Vector3.One();
  55328. var angle = options.angle || 0;
  55329. // Getting correct rotation
  55330. if (!normal) {
  55331. var target = new BABYLON.Vector3(0, 0, 1);
  55332. var camera = sourceMesh.getScene().activeCamera;
  55333. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55334. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55335. }
  55336. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55337. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55338. var pitch = Math.atan2(normal.y, len);
  55339. // Matrix
  55340. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55341. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55342. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55343. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55344. var vertexData = new BABYLON.VertexData();
  55345. vertexData.indices = [];
  55346. vertexData.positions = [];
  55347. vertexData.normals = [];
  55348. vertexData.uvs = [];
  55349. var currentVertexDataIndex = 0;
  55350. var extractDecalVector3 = function (indexId) {
  55351. var result = new BABYLON.PositionNormalVertex();
  55352. if (!indices || !positions || !normals) {
  55353. return result;
  55354. }
  55355. var vertexId = indices[indexId];
  55356. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55357. // Send vector to decal local world
  55358. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55359. // Get normal
  55360. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55361. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55362. return result;
  55363. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55364. var clip = function (vertices, axis) {
  55365. if (vertices.length === 0) {
  55366. return vertices;
  55367. }
  55368. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55369. var clipVertices = function (v0, v1) {
  55370. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55371. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55372. };
  55373. var result = new Array();
  55374. for (var index = 0; index < vertices.length; index += 3) {
  55375. var v1Out;
  55376. var v2Out;
  55377. var v3Out;
  55378. var total = 0;
  55379. var nV1 = null;
  55380. var nV2 = null;
  55381. var nV3 = null;
  55382. var nV4 = null;
  55383. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55384. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55385. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55386. v1Out = d1 > 0;
  55387. v2Out = d2 > 0;
  55388. v3Out = d3 > 0;
  55389. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55390. switch (total) {
  55391. case 0:
  55392. result.push(vertices[index]);
  55393. result.push(vertices[index + 1]);
  55394. result.push(vertices[index + 2]);
  55395. break;
  55396. case 1:
  55397. if (v1Out) {
  55398. nV1 = vertices[index + 1];
  55399. nV2 = vertices[index + 2];
  55400. nV3 = clipVertices(vertices[index], nV1);
  55401. nV4 = clipVertices(vertices[index], nV2);
  55402. }
  55403. if (v2Out) {
  55404. nV1 = vertices[index];
  55405. nV2 = vertices[index + 2];
  55406. nV3 = clipVertices(vertices[index + 1], nV1);
  55407. nV4 = clipVertices(vertices[index + 1], nV2);
  55408. result.push(nV3);
  55409. result.push(nV2.clone());
  55410. result.push(nV1.clone());
  55411. result.push(nV2.clone());
  55412. result.push(nV3.clone());
  55413. result.push(nV4);
  55414. break;
  55415. }
  55416. if (v3Out) {
  55417. nV1 = vertices[index];
  55418. nV2 = vertices[index + 1];
  55419. nV3 = clipVertices(vertices[index + 2], nV1);
  55420. nV4 = clipVertices(vertices[index + 2], nV2);
  55421. }
  55422. if (nV1 && nV2 && nV3 && nV4) {
  55423. result.push(nV1.clone());
  55424. result.push(nV2.clone());
  55425. result.push(nV3);
  55426. result.push(nV4);
  55427. result.push(nV3.clone());
  55428. result.push(nV2.clone());
  55429. }
  55430. break;
  55431. case 2:
  55432. if (!v1Out) {
  55433. nV1 = vertices[index].clone();
  55434. nV2 = clipVertices(nV1, vertices[index + 1]);
  55435. nV3 = clipVertices(nV1, vertices[index + 2]);
  55436. result.push(nV1);
  55437. result.push(nV2);
  55438. result.push(nV3);
  55439. }
  55440. if (!v2Out) {
  55441. nV1 = vertices[index + 1].clone();
  55442. nV2 = clipVertices(nV1, vertices[index + 2]);
  55443. nV3 = clipVertices(nV1, vertices[index]);
  55444. result.push(nV1);
  55445. result.push(nV2);
  55446. result.push(nV3);
  55447. }
  55448. if (!v3Out) {
  55449. nV1 = vertices[index + 2].clone();
  55450. nV2 = clipVertices(nV1, vertices[index]);
  55451. nV3 = clipVertices(nV1, vertices[index + 1]);
  55452. result.push(nV1);
  55453. result.push(nV2);
  55454. result.push(nV3);
  55455. }
  55456. break;
  55457. case 3:
  55458. break;
  55459. }
  55460. }
  55461. return result;
  55462. };
  55463. for (var index = 0; index < indices.length; index += 3) {
  55464. var faceVertices = new Array();
  55465. faceVertices.push(extractDecalVector3(index));
  55466. faceVertices.push(extractDecalVector3(index + 1));
  55467. faceVertices.push(extractDecalVector3(index + 2));
  55468. // Clip
  55469. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55470. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55471. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55472. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55473. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55474. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55475. if (faceVertices.length === 0) {
  55476. continue;
  55477. }
  55478. // Add UVs and get back to world
  55479. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55480. var vertex = faceVertices[vIndex];
  55481. //TODO check for Int32Array | Uint32Array | Uint16Array
  55482. vertexData.indices.push(currentVertexDataIndex);
  55483. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55484. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55485. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55486. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55487. currentVertexDataIndex++;
  55488. }
  55489. }
  55490. // Return mesh
  55491. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55492. vertexData.applyToMesh(decal);
  55493. decal.position = position.clone();
  55494. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55495. return decal;
  55496. };
  55497. // Privates
  55498. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55499. // extrusion geometry
  55500. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55501. var tangents = path3D.getTangents();
  55502. var normals = path3D.getNormals();
  55503. var binormals = path3D.getBinormals();
  55504. var distances = path3D.getDistances();
  55505. var angle = 0;
  55506. var returnScale = function () { return scale !== null ? scale : 1; };
  55507. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55508. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55509. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55510. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55511. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55512. for (var i = 0; i < curve.length; i++) {
  55513. var shapePath = new Array();
  55514. var angleStep = rotate(i, distances[i]);
  55515. var scaleRatio = scl(i, distances[i]);
  55516. for (var p = 0; p < shape.length; p++) {
  55517. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55518. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55519. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55520. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55521. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55522. shapePath[p] = rotated;
  55523. }
  55524. shapePaths[index] = shapePath;
  55525. angle += angleStep;
  55526. index++;
  55527. }
  55528. // cap
  55529. var capPath = function (shapePath) {
  55530. var pointCap = Array();
  55531. var barycenter = BABYLON.Vector3.Zero();
  55532. var i;
  55533. for (i = 0; i < shapePath.length; i++) {
  55534. barycenter.addInPlace(shapePath[i]);
  55535. }
  55536. barycenter.scaleInPlace(1.0 / shapePath.length);
  55537. for (i = 0; i < shapePath.length; i++) {
  55538. pointCap.push(barycenter);
  55539. }
  55540. return pointCap;
  55541. };
  55542. switch (cap) {
  55543. case BABYLON.Mesh.NO_CAP:
  55544. break;
  55545. case BABYLON.Mesh.CAP_START:
  55546. shapePaths[0] = capPath(shapePaths[2]);
  55547. shapePaths[1] = shapePaths[2];
  55548. break;
  55549. case BABYLON.Mesh.CAP_END:
  55550. shapePaths[index] = shapePaths[index - 1];
  55551. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55552. break;
  55553. case BABYLON.Mesh.CAP_ALL:
  55554. shapePaths[0] = capPath(shapePaths[2]);
  55555. shapePaths[1] = shapePaths[2];
  55556. shapePaths[index] = shapePaths[index - 1];
  55557. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55558. break;
  55559. default:
  55560. break;
  55561. }
  55562. return shapePaths;
  55563. };
  55564. var path3D;
  55565. var pathArray;
  55566. if (instance) {
  55567. path3D = (instance.path3D).update(curve);
  55568. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  55569. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  55570. return instance;
  55571. }
  55572. // extruded shape creation
  55573. path3D = new BABYLON.Path3D(curve);
  55574. var newShapePaths = new Array();
  55575. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55576. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  55577. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  55578. extrudedGeneric.pathArray = pathArray;
  55579. extrudedGeneric.path3D = path3D;
  55580. extrudedGeneric.cap = cap;
  55581. return extrudedGeneric;
  55582. };
  55583. return MeshBuilder;
  55584. }());
  55585. BABYLON.MeshBuilder = MeshBuilder;
  55586. })(BABYLON || (BABYLON = {}));
  55587. //# sourceMappingURL=babylon.meshBuilder.js.map
  55588. var BABYLON;
  55589. (function (BABYLON) {
  55590. var AudioEngine = /** @class */ (function () {
  55591. function AudioEngine() {
  55592. this._audioContext = null;
  55593. this._audioContextInitialized = false;
  55594. this.canUseWebAudio = false;
  55595. this.WarnedWebAudioUnsupported = false;
  55596. this.unlocked = false;
  55597. this.isMP3supported = false;
  55598. this.isOGGsupported = false;
  55599. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  55600. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  55601. this.canUseWebAudio = true;
  55602. }
  55603. var audioElem = document.createElement('audio');
  55604. try {
  55605. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  55606. this.isMP3supported = true;
  55607. }
  55608. }
  55609. catch (e) {
  55610. // protect error during capability check.
  55611. }
  55612. try {
  55613. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  55614. this.isOGGsupported = true;
  55615. }
  55616. }
  55617. catch (e) {
  55618. // protect error during capability check.
  55619. }
  55620. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  55621. this._unlockiOSaudio();
  55622. }
  55623. else {
  55624. this.unlocked = true;
  55625. }
  55626. }
  55627. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  55628. get: function () {
  55629. if (!this._audioContextInitialized) {
  55630. this._initializeAudioContext();
  55631. }
  55632. return this._audioContext;
  55633. },
  55634. enumerable: true,
  55635. configurable: true
  55636. });
  55637. AudioEngine.prototype._unlockiOSaudio = function () {
  55638. var _this = this;
  55639. var unlockaudio = function () {
  55640. if (!_this.audioContext) {
  55641. return;
  55642. }
  55643. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  55644. var source = _this.audioContext.createBufferSource();
  55645. source.buffer = buffer;
  55646. source.connect(_this.audioContext.destination);
  55647. source.start(0);
  55648. setTimeout(function () {
  55649. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  55650. _this.unlocked = true;
  55651. window.removeEventListener('touchend', unlockaudio, false);
  55652. if (_this.onAudioUnlocked) {
  55653. _this.onAudioUnlocked();
  55654. }
  55655. }
  55656. }, 0);
  55657. };
  55658. window.addEventListener('touchend', unlockaudio, false);
  55659. };
  55660. AudioEngine.prototype._initializeAudioContext = function () {
  55661. try {
  55662. if (this.canUseWebAudio) {
  55663. this._audioContext = new AudioContext();
  55664. // create a global volume gain node
  55665. this.masterGain = this._audioContext.createGain();
  55666. this.masterGain.gain.value = 1;
  55667. this.masterGain.connect(this._audioContext.destination);
  55668. this._audioContextInitialized = true;
  55669. }
  55670. }
  55671. catch (e) {
  55672. this.canUseWebAudio = false;
  55673. BABYLON.Tools.Error("Web Audio: " + e.message);
  55674. }
  55675. };
  55676. AudioEngine.prototype.dispose = function () {
  55677. if (this.canUseWebAudio && this._audioContextInitialized) {
  55678. if (this._connectedAnalyser && this._audioContext) {
  55679. this._connectedAnalyser.stopDebugCanvas();
  55680. this._connectedAnalyser.dispose();
  55681. this.masterGain.disconnect();
  55682. this.masterGain.connect(this._audioContext.destination);
  55683. this._connectedAnalyser = null;
  55684. }
  55685. this.masterGain.gain.value = 1;
  55686. }
  55687. this.WarnedWebAudioUnsupported = false;
  55688. };
  55689. AudioEngine.prototype.getGlobalVolume = function () {
  55690. if (this.canUseWebAudio && this._audioContextInitialized) {
  55691. return this.masterGain.gain.value;
  55692. }
  55693. else {
  55694. return -1;
  55695. }
  55696. };
  55697. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  55698. if (this.canUseWebAudio && this._audioContextInitialized) {
  55699. this.masterGain.gain.value = newVolume;
  55700. }
  55701. };
  55702. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  55703. if (this._connectedAnalyser) {
  55704. this._connectedAnalyser.stopDebugCanvas();
  55705. }
  55706. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  55707. this._connectedAnalyser = analyser;
  55708. this.masterGain.disconnect();
  55709. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  55710. }
  55711. };
  55712. return AudioEngine;
  55713. }());
  55714. BABYLON.AudioEngine = AudioEngine;
  55715. })(BABYLON || (BABYLON = {}));
  55716. //# sourceMappingURL=babylon.audioEngine.js.map
  55717. var BABYLON;
  55718. (function (BABYLON) {
  55719. var Sound = /** @class */ (function () {
  55720. /**
  55721. * Create a sound and attach it to a scene
  55722. * @param name Name of your sound
  55723. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  55724. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  55725. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  55726. */
  55727. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  55728. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  55729. var _this = this;
  55730. this.autoplay = false;
  55731. this.loop = false;
  55732. this.useCustomAttenuation = false;
  55733. this.spatialSound = false;
  55734. this.refDistance = 1;
  55735. this.rolloffFactor = 1;
  55736. this.maxDistance = 100;
  55737. this.distanceModel = "linear";
  55738. this._panningModel = "equalpower";
  55739. this._playbackRate = 1;
  55740. this._streaming = false;
  55741. this._startTime = 0;
  55742. this._startOffset = 0;
  55743. this._position = BABYLON.Vector3.Zero();
  55744. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  55745. this._volume = 1;
  55746. this._isReadyToPlay = false;
  55747. this.isPlaying = false;
  55748. this.isPaused = false;
  55749. this._isDirectional = false;
  55750. // Used if you'd like to create a directional sound.
  55751. // If not set, the sound will be omnidirectional
  55752. this._coneInnerAngle = 360;
  55753. this._coneOuterAngle = 360;
  55754. this._coneOuterGain = 0;
  55755. this._isOutputConnected = false;
  55756. this._urlType = "Unknown";
  55757. this.name = name;
  55758. this._scene = scene;
  55759. this._readyToPlayCallback = readyToPlayCallback;
  55760. // Default custom attenuation function is a linear attenuation
  55761. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  55762. if (currentDistance < maxDistance) {
  55763. return currentVolume * (1 - currentDistance / maxDistance);
  55764. }
  55765. else {
  55766. return 0;
  55767. }
  55768. };
  55769. if (options) {
  55770. this.autoplay = options.autoplay || false;
  55771. this.loop = options.loop || false;
  55772. // if volume === 0, we need another way to check this option
  55773. if (options.volume !== undefined) {
  55774. this._volume = options.volume;
  55775. }
  55776. this.spatialSound = options.spatialSound || false;
  55777. this.maxDistance = options.maxDistance || 100;
  55778. this.useCustomAttenuation = options.useCustomAttenuation || false;
  55779. this.rolloffFactor = options.rolloffFactor || 1;
  55780. this.refDistance = options.refDistance || 1;
  55781. this.distanceModel = options.distanceModel || "linear";
  55782. this._playbackRate = options.playbackRate || 1;
  55783. this._streaming = options.streaming || false;
  55784. }
  55785. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55786. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  55787. this._soundGain.gain.value = this._volume;
  55788. this._inputAudioNode = this._soundGain;
  55789. this._ouputAudioNode = this._soundGain;
  55790. if (this.spatialSound) {
  55791. this._createSpatialParameters();
  55792. }
  55793. this._scene.mainSoundTrack.AddSound(this);
  55794. var validParameter = true;
  55795. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  55796. if (urlOrArrayBuffer) {
  55797. if (typeof (urlOrArrayBuffer) === "string")
  55798. this._urlType = "String";
  55799. if (Array.isArray(urlOrArrayBuffer))
  55800. this._urlType = "Array";
  55801. if (urlOrArrayBuffer instanceof ArrayBuffer)
  55802. this._urlType = "ArrayBuffer";
  55803. var urls = [];
  55804. var codecSupportedFound = false;
  55805. switch (this._urlType) {
  55806. case "ArrayBuffer":
  55807. if (urlOrArrayBuffer.byteLength > 0) {
  55808. codecSupportedFound = true;
  55809. this._soundLoaded(urlOrArrayBuffer);
  55810. }
  55811. break;
  55812. case "String":
  55813. urls.push(urlOrArrayBuffer);
  55814. case "Array":
  55815. if (urls.length === 0)
  55816. urls = urlOrArrayBuffer;
  55817. // If we found a supported format, we load it immediately and stop the loop
  55818. for (var i = 0; i < urls.length; i++) {
  55819. var url = urls[i];
  55820. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  55821. codecSupportedFound = true;
  55822. }
  55823. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  55824. codecSupportedFound = true;
  55825. }
  55826. if (url.indexOf(".wav", url.length - 4) !== -1) {
  55827. codecSupportedFound = true;
  55828. }
  55829. if (url.indexOf("blob:") !== -1) {
  55830. codecSupportedFound = true;
  55831. }
  55832. if (codecSupportedFound) {
  55833. // Loading sound using XHR2
  55834. if (!this._streaming) {
  55835. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  55836. }
  55837. else {
  55838. this._htmlAudioElement = new Audio(url);
  55839. this._htmlAudioElement.controls = false;
  55840. this._htmlAudioElement.loop = this.loop;
  55841. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  55842. this._htmlAudioElement.preload = "auto";
  55843. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  55844. _this._isReadyToPlay = true;
  55845. if (_this.autoplay) {
  55846. _this.play();
  55847. }
  55848. if (_this._readyToPlayCallback) {
  55849. _this._readyToPlayCallback();
  55850. }
  55851. });
  55852. document.body.appendChild(this._htmlAudioElement);
  55853. }
  55854. break;
  55855. }
  55856. }
  55857. break;
  55858. default:
  55859. validParameter = false;
  55860. break;
  55861. }
  55862. if (!validParameter) {
  55863. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  55864. }
  55865. else {
  55866. if (!codecSupportedFound) {
  55867. this._isReadyToPlay = true;
  55868. // Simulating a ready to play event to avoid breaking code path
  55869. if (this._readyToPlayCallback) {
  55870. window.setTimeout(function () {
  55871. if (_this._readyToPlayCallback) {
  55872. _this._readyToPlayCallback();
  55873. }
  55874. }, 1000);
  55875. }
  55876. }
  55877. }
  55878. }
  55879. }
  55880. else {
  55881. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  55882. this._scene.mainSoundTrack.AddSound(this);
  55883. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  55884. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  55885. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  55886. }
  55887. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  55888. if (this._readyToPlayCallback) {
  55889. window.setTimeout(function () {
  55890. if (_this._readyToPlayCallback) {
  55891. _this._readyToPlayCallback();
  55892. }
  55893. }, 1000);
  55894. }
  55895. }
  55896. }
  55897. Sound.prototype.dispose = function () {
  55898. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  55899. if (this.isPlaying) {
  55900. this.stop();
  55901. }
  55902. this._isReadyToPlay = false;
  55903. if (this.soundTrackId === -1) {
  55904. this._scene.mainSoundTrack.RemoveSound(this);
  55905. }
  55906. else {
  55907. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  55908. }
  55909. if (this._soundGain) {
  55910. this._soundGain.disconnect();
  55911. this._soundGain = null;
  55912. }
  55913. if (this._soundPanner) {
  55914. this._soundPanner.disconnect();
  55915. this._soundPanner = null;
  55916. }
  55917. if (this._soundSource) {
  55918. this._soundSource.disconnect();
  55919. this._soundSource = null;
  55920. }
  55921. this._audioBuffer = null;
  55922. if (this._htmlAudioElement) {
  55923. this._htmlAudioElement.pause();
  55924. this._htmlAudioElement.src = "";
  55925. document.body.removeChild(this._htmlAudioElement);
  55926. }
  55927. if (this._connectedMesh && this._registerFunc) {
  55928. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  55929. this._connectedMesh = null;
  55930. }
  55931. }
  55932. };
  55933. Sound.prototype.isReady = function () {
  55934. return this._isReadyToPlay;
  55935. };
  55936. Sound.prototype._soundLoaded = function (audioData) {
  55937. var _this = this;
  55938. if (!BABYLON.Engine.audioEngine.audioContext) {
  55939. return;
  55940. }
  55941. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  55942. _this._audioBuffer = buffer;
  55943. _this._isReadyToPlay = true;
  55944. if (_this.autoplay) {
  55945. _this.play();
  55946. }
  55947. if (_this._readyToPlayCallback) {
  55948. _this._readyToPlayCallback();
  55949. }
  55950. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  55951. };
  55952. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  55953. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  55954. this._audioBuffer = audioBuffer;
  55955. this._isReadyToPlay = true;
  55956. }
  55957. };
  55958. Sound.prototype.updateOptions = function (options) {
  55959. if (options) {
  55960. this.loop = options.loop || this.loop;
  55961. this.maxDistance = options.maxDistance || this.maxDistance;
  55962. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  55963. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  55964. this.refDistance = options.refDistance || this.refDistance;
  55965. this.distanceModel = options.distanceModel || this.distanceModel;
  55966. this._playbackRate = options.playbackRate || this._playbackRate;
  55967. this._updateSpatialParameters();
  55968. if (this.isPlaying) {
  55969. if (this._streaming) {
  55970. this._htmlAudioElement.playbackRate = this._playbackRate;
  55971. }
  55972. else {
  55973. if (this._soundSource) {
  55974. this._soundSource.playbackRate.value = this._playbackRate;
  55975. }
  55976. }
  55977. }
  55978. }
  55979. };
  55980. Sound.prototype._createSpatialParameters = function () {
  55981. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  55982. if (this._scene.headphone) {
  55983. this._panningModel = "HRTF";
  55984. }
  55985. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  55986. this._updateSpatialParameters();
  55987. this._soundPanner.connect(this._ouputAudioNode);
  55988. this._inputAudioNode = this._soundPanner;
  55989. }
  55990. };
  55991. Sound.prototype._updateSpatialParameters = function () {
  55992. if (this.spatialSound && this._soundPanner) {
  55993. if (this.useCustomAttenuation) {
  55994. // Tricks to disable in a way embedded Web Audio attenuation
  55995. this._soundPanner.distanceModel = "linear";
  55996. this._soundPanner.maxDistance = Number.MAX_VALUE;
  55997. this._soundPanner.refDistance = 1;
  55998. this._soundPanner.rolloffFactor = 1;
  55999. this._soundPanner.panningModel = this._panningModel;
  56000. }
  56001. else {
  56002. this._soundPanner.distanceModel = this.distanceModel;
  56003. this._soundPanner.maxDistance = this.maxDistance;
  56004. this._soundPanner.refDistance = this.refDistance;
  56005. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56006. this._soundPanner.panningModel = this._panningModel;
  56007. }
  56008. }
  56009. };
  56010. Sound.prototype.switchPanningModelToHRTF = function () {
  56011. this._panningModel = "HRTF";
  56012. this._switchPanningModel();
  56013. };
  56014. Sound.prototype.switchPanningModelToEqualPower = function () {
  56015. this._panningModel = "equalpower";
  56016. this._switchPanningModel();
  56017. };
  56018. Sound.prototype._switchPanningModel = function () {
  56019. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56020. this._soundPanner.panningModel = this._panningModel;
  56021. }
  56022. };
  56023. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56024. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56025. if (this._isOutputConnected) {
  56026. this._ouputAudioNode.disconnect();
  56027. }
  56028. this._ouputAudioNode.connect(soundTrackAudioNode);
  56029. this._isOutputConnected = true;
  56030. }
  56031. };
  56032. /**
  56033. * Transform this sound into a directional source
  56034. * @param coneInnerAngle Size of the inner cone in degree
  56035. * @param coneOuterAngle Size of the outer cone in degree
  56036. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56037. */
  56038. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56039. if (coneOuterAngle < coneInnerAngle) {
  56040. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56041. return;
  56042. }
  56043. this._coneInnerAngle = coneInnerAngle;
  56044. this._coneOuterAngle = coneOuterAngle;
  56045. this._coneOuterGain = coneOuterGain;
  56046. this._isDirectional = true;
  56047. if (this.isPlaying && this.loop) {
  56048. this.stop();
  56049. this.play();
  56050. }
  56051. };
  56052. Sound.prototype.setPosition = function (newPosition) {
  56053. this._position = newPosition;
  56054. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56055. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56056. }
  56057. };
  56058. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56059. this._localDirection = newLocalDirection;
  56060. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56061. this._updateDirection();
  56062. }
  56063. };
  56064. Sound.prototype._updateDirection = function () {
  56065. if (!this._connectedMesh || !this._soundPanner) {
  56066. return;
  56067. }
  56068. var mat = this._connectedMesh.getWorldMatrix();
  56069. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56070. direction.normalize();
  56071. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56072. };
  56073. Sound.prototype.updateDistanceFromListener = function () {
  56074. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56075. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56076. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56077. }
  56078. };
  56079. Sound.prototype.setAttenuationFunction = function (callback) {
  56080. this._customAttenuationFunction = callback;
  56081. };
  56082. /**
  56083. * Play the sound
  56084. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56085. * @param offset (optional) Start the sound setting it at a specific time
  56086. */
  56087. Sound.prototype.play = function (time, offset) {
  56088. var _this = this;
  56089. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56090. try {
  56091. if (this._startOffset < 0) {
  56092. time = -this._startOffset;
  56093. this._startOffset = 0;
  56094. }
  56095. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56096. if (!this._soundSource || !this._streamingSource) {
  56097. if (this.spatialSound && this._soundPanner) {
  56098. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56099. if (this._isDirectional) {
  56100. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56101. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56102. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56103. if (this._connectedMesh) {
  56104. this._updateDirection();
  56105. }
  56106. else {
  56107. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56108. }
  56109. }
  56110. }
  56111. }
  56112. if (this._streaming) {
  56113. if (!this._streamingSource) {
  56114. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56115. this._htmlAudioElement.onended = function () { _this._onended(); };
  56116. this._htmlAudioElement.playbackRate = this._playbackRate;
  56117. }
  56118. this._streamingSource.disconnect();
  56119. this._streamingSource.connect(this._inputAudioNode);
  56120. this._htmlAudioElement.play();
  56121. }
  56122. else {
  56123. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56124. this._soundSource.buffer = this._audioBuffer;
  56125. this._soundSource.connect(this._inputAudioNode);
  56126. this._soundSource.loop = this.loop;
  56127. this._soundSource.playbackRate.value = this._playbackRate;
  56128. this._soundSource.onended = function () { _this._onended(); };
  56129. if (this._soundSource.buffer) {
  56130. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56131. }
  56132. }
  56133. this._startTime = startTime;
  56134. this.isPlaying = true;
  56135. this.isPaused = false;
  56136. }
  56137. catch (ex) {
  56138. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56139. }
  56140. }
  56141. };
  56142. Sound.prototype._onended = function () {
  56143. this.isPlaying = false;
  56144. if (this.onended) {
  56145. this.onended();
  56146. }
  56147. };
  56148. /**
  56149. * Stop the sound
  56150. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56151. */
  56152. Sound.prototype.stop = function (time) {
  56153. if (this.isPlaying) {
  56154. if (this._streaming) {
  56155. this._htmlAudioElement.pause();
  56156. // Test needed for Firefox or it will generate an Invalid State Error
  56157. if (this._htmlAudioElement.currentTime > 0) {
  56158. this._htmlAudioElement.currentTime = 0;
  56159. }
  56160. }
  56161. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56162. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56163. this._soundSource.stop(stopTime);
  56164. this._soundSource.onended = function () { };
  56165. if (!this.isPaused) {
  56166. this._startOffset = 0;
  56167. }
  56168. }
  56169. this.isPlaying = false;
  56170. }
  56171. };
  56172. Sound.prototype.pause = function () {
  56173. if (this.isPlaying) {
  56174. this.isPaused = true;
  56175. if (this._streaming) {
  56176. this._htmlAudioElement.pause();
  56177. }
  56178. else if (BABYLON.Engine.audioEngine.audioContext) {
  56179. this.stop(0);
  56180. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56181. }
  56182. }
  56183. };
  56184. Sound.prototype.setVolume = function (newVolume, time) {
  56185. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56186. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56187. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56188. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56189. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56190. }
  56191. else {
  56192. this._soundGain.gain.value = newVolume;
  56193. }
  56194. }
  56195. this._volume = newVolume;
  56196. };
  56197. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56198. this._playbackRate = newPlaybackRate;
  56199. if (this.isPlaying) {
  56200. if (this._streaming) {
  56201. this._htmlAudioElement.playbackRate = this._playbackRate;
  56202. }
  56203. else if (this._soundSource) {
  56204. this._soundSource.playbackRate.value = this._playbackRate;
  56205. }
  56206. }
  56207. };
  56208. Sound.prototype.getVolume = function () {
  56209. return this._volume;
  56210. };
  56211. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56212. var _this = this;
  56213. if (this._connectedMesh && this._registerFunc) {
  56214. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56215. this._registerFunc = null;
  56216. }
  56217. this._connectedMesh = meshToConnectTo;
  56218. if (!this.spatialSound) {
  56219. this.spatialSound = true;
  56220. this._createSpatialParameters();
  56221. if (this.isPlaying && this.loop) {
  56222. this.stop();
  56223. this.play();
  56224. }
  56225. }
  56226. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56227. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56228. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56229. };
  56230. Sound.prototype.detachFromMesh = function () {
  56231. if (this._connectedMesh && this._registerFunc) {
  56232. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56233. this._registerFunc = null;
  56234. this._connectedMesh = null;
  56235. }
  56236. };
  56237. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56238. if (!node.getBoundingInfo) {
  56239. return;
  56240. }
  56241. var mesh = node;
  56242. var boundingInfo = mesh.getBoundingInfo();
  56243. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56244. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56245. this._updateDirection();
  56246. }
  56247. };
  56248. Sound.prototype.clone = function () {
  56249. var _this = this;
  56250. if (!this._streaming) {
  56251. var setBufferAndRun = function () {
  56252. if (_this._isReadyToPlay) {
  56253. clonedSound._audioBuffer = _this.getAudioBuffer();
  56254. clonedSound._isReadyToPlay = true;
  56255. if (clonedSound.autoplay) {
  56256. clonedSound.play();
  56257. }
  56258. }
  56259. else {
  56260. window.setTimeout(setBufferAndRun, 300);
  56261. }
  56262. };
  56263. var currentOptions = {
  56264. autoplay: this.autoplay, loop: this.loop,
  56265. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56266. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56267. refDistance: this.refDistance, distanceModel: this.distanceModel
  56268. };
  56269. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56270. if (this.useCustomAttenuation) {
  56271. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56272. }
  56273. clonedSound.setPosition(this._position);
  56274. clonedSound.setPlaybackRate(this._playbackRate);
  56275. setBufferAndRun();
  56276. return clonedSound;
  56277. }
  56278. else {
  56279. return null;
  56280. }
  56281. };
  56282. Sound.prototype.getAudioBuffer = function () {
  56283. return this._audioBuffer;
  56284. };
  56285. Sound.prototype.serialize = function () {
  56286. var serializationObject = {
  56287. name: this.name,
  56288. url: this.name,
  56289. autoplay: this.autoplay,
  56290. loop: this.loop,
  56291. volume: this._volume,
  56292. spatialSound: this.spatialSound,
  56293. maxDistance: this.maxDistance,
  56294. rolloffFactor: this.rolloffFactor,
  56295. refDistance: this.refDistance,
  56296. distanceModel: this.distanceModel,
  56297. playbackRate: this._playbackRate,
  56298. panningModel: this._panningModel,
  56299. soundTrackId: this.soundTrackId
  56300. };
  56301. if (this.spatialSound) {
  56302. if (this._connectedMesh)
  56303. serializationObject.connectedMeshId = this._connectedMesh.id;
  56304. serializationObject.position = this._position.asArray();
  56305. serializationObject.refDistance = this.refDistance;
  56306. serializationObject.distanceModel = this.distanceModel;
  56307. serializationObject.isDirectional = this._isDirectional;
  56308. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56309. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56310. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56311. serializationObject.coneOuterGain = this._coneOuterGain;
  56312. }
  56313. return serializationObject;
  56314. };
  56315. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56316. var soundName = parsedSound.name;
  56317. var soundUrl;
  56318. if (parsedSound.url) {
  56319. soundUrl = rootUrl + parsedSound.url;
  56320. }
  56321. else {
  56322. soundUrl = rootUrl + soundName;
  56323. }
  56324. var options = {
  56325. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56326. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56327. rolloffFactor: parsedSound.rolloffFactor,
  56328. refDistance: parsedSound.refDistance,
  56329. distanceModel: parsedSound.distanceModel,
  56330. playbackRate: parsedSound.playbackRate
  56331. };
  56332. var newSound;
  56333. if (!sourceSound) {
  56334. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56335. scene._addPendingData(newSound);
  56336. }
  56337. else {
  56338. var setBufferAndRun = function () {
  56339. if (sourceSound._isReadyToPlay) {
  56340. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56341. newSound._isReadyToPlay = true;
  56342. if (newSound.autoplay) {
  56343. newSound.play();
  56344. }
  56345. }
  56346. else {
  56347. window.setTimeout(setBufferAndRun, 300);
  56348. }
  56349. };
  56350. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56351. setBufferAndRun();
  56352. }
  56353. if (parsedSound.position) {
  56354. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56355. newSound.setPosition(soundPosition);
  56356. }
  56357. if (parsedSound.isDirectional) {
  56358. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56359. if (parsedSound.localDirectionToMesh) {
  56360. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56361. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56362. }
  56363. }
  56364. if (parsedSound.connectedMeshId) {
  56365. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56366. if (connectedMesh) {
  56367. newSound.attachToMesh(connectedMesh);
  56368. }
  56369. }
  56370. return newSound;
  56371. };
  56372. return Sound;
  56373. }());
  56374. BABYLON.Sound = Sound;
  56375. })(BABYLON || (BABYLON = {}));
  56376. //# sourceMappingURL=babylon.sound.js.map
  56377. var BABYLON;
  56378. (function (BABYLON) {
  56379. var SoundTrack = /** @class */ (function () {
  56380. function SoundTrack(scene, options) {
  56381. this.id = -1;
  56382. this._isMainTrack = false;
  56383. this._isInitialized = false;
  56384. this._scene = scene;
  56385. this.soundCollection = new Array();
  56386. this._options = options;
  56387. if (!this._isMainTrack) {
  56388. this._scene.soundTracks.push(this);
  56389. this.id = this._scene.soundTracks.length - 1;
  56390. }
  56391. }
  56392. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56393. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56394. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56395. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56396. if (this._options) {
  56397. if (this._options.volume) {
  56398. this._outputAudioNode.gain.value = this._options.volume;
  56399. }
  56400. if (this._options.mainTrack) {
  56401. this._isMainTrack = this._options.mainTrack;
  56402. }
  56403. }
  56404. this._isInitialized = true;
  56405. }
  56406. };
  56407. SoundTrack.prototype.dispose = function () {
  56408. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56409. if (this._connectedAnalyser) {
  56410. this._connectedAnalyser.stopDebugCanvas();
  56411. }
  56412. while (this.soundCollection.length) {
  56413. this.soundCollection[0].dispose();
  56414. }
  56415. if (this._outputAudioNode) {
  56416. this._outputAudioNode.disconnect();
  56417. }
  56418. this._outputAudioNode = null;
  56419. }
  56420. };
  56421. SoundTrack.prototype.AddSound = function (sound) {
  56422. if (!this._isInitialized) {
  56423. this._initializeSoundTrackAudioGraph();
  56424. }
  56425. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56426. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56427. }
  56428. if (sound.soundTrackId) {
  56429. if (sound.soundTrackId === -1) {
  56430. this._scene.mainSoundTrack.RemoveSound(sound);
  56431. }
  56432. else {
  56433. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56434. }
  56435. }
  56436. this.soundCollection.push(sound);
  56437. sound.soundTrackId = this.id;
  56438. };
  56439. SoundTrack.prototype.RemoveSound = function (sound) {
  56440. var index = this.soundCollection.indexOf(sound);
  56441. if (index !== -1) {
  56442. this.soundCollection.splice(index, 1);
  56443. }
  56444. };
  56445. SoundTrack.prototype.setVolume = function (newVolume) {
  56446. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56447. this._outputAudioNode.gain.value = newVolume;
  56448. }
  56449. };
  56450. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56451. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56452. for (var i = 0; i < this.soundCollection.length; i++) {
  56453. this.soundCollection[i].switchPanningModelToHRTF();
  56454. }
  56455. }
  56456. };
  56457. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  56458. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56459. for (var i = 0; i < this.soundCollection.length; i++) {
  56460. this.soundCollection[i].switchPanningModelToEqualPower();
  56461. }
  56462. }
  56463. };
  56464. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  56465. if (this._connectedAnalyser) {
  56466. this._connectedAnalyser.stopDebugCanvas();
  56467. }
  56468. this._connectedAnalyser = analyser;
  56469. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56470. this._outputAudioNode.disconnect();
  56471. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  56472. }
  56473. };
  56474. return SoundTrack;
  56475. }());
  56476. BABYLON.SoundTrack = SoundTrack;
  56477. })(BABYLON || (BABYLON = {}));
  56478. //# sourceMappingURL=babylon.soundtrack.js.map
  56479. var BABYLON;
  56480. (function (BABYLON) {
  56481. var Analyser = /** @class */ (function () {
  56482. function Analyser(scene) {
  56483. this.SMOOTHING = 0.75;
  56484. this.FFT_SIZE = 512;
  56485. this.BARGRAPHAMPLITUDE = 256;
  56486. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  56487. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  56488. this._scene = scene;
  56489. this._audioEngine = BABYLON.Engine.audioEngine;
  56490. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  56491. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  56492. this._webAudioAnalyser.minDecibels = -140;
  56493. this._webAudioAnalyser.maxDecibels = 0;
  56494. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56495. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  56496. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  56497. }
  56498. }
  56499. Analyser.prototype.getFrequencyBinCount = function () {
  56500. if (this._audioEngine.canUseWebAudio) {
  56501. return this._webAudioAnalyser.frequencyBinCount;
  56502. }
  56503. else {
  56504. return 0;
  56505. }
  56506. };
  56507. Analyser.prototype.getByteFrequencyData = function () {
  56508. if (this._audioEngine.canUseWebAudio) {
  56509. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56510. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56511. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  56512. }
  56513. return this._byteFreqs;
  56514. };
  56515. Analyser.prototype.getByteTimeDomainData = function () {
  56516. if (this._audioEngine.canUseWebAudio) {
  56517. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56518. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56519. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  56520. }
  56521. return this._byteTime;
  56522. };
  56523. Analyser.prototype.getFloatFrequencyData = function () {
  56524. if (this._audioEngine.canUseWebAudio) {
  56525. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  56526. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  56527. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  56528. }
  56529. return this._floatFreqs;
  56530. };
  56531. Analyser.prototype.drawDebugCanvas = function () {
  56532. var _this = this;
  56533. if (this._audioEngine.canUseWebAudio) {
  56534. if (!this._debugCanvas) {
  56535. this._debugCanvas = document.createElement("canvas");
  56536. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  56537. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  56538. this._debugCanvas.style.position = "absolute";
  56539. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  56540. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  56541. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  56542. document.body.appendChild(this._debugCanvas);
  56543. this._registerFunc = function () {
  56544. _this.drawDebugCanvas();
  56545. };
  56546. this._scene.registerBeforeRender(this._registerFunc);
  56547. }
  56548. if (this._registerFunc && this._debugCanvasContext) {
  56549. var workingArray = this.getByteFrequencyData();
  56550. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  56551. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  56552. // Draw the frequency domain chart.
  56553. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  56554. var value = workingArray[i];
  56555. var percent = value / this.BARGRAPHAMPLITUDE;
  56556. var height = this.DEBUGCANVASSIZE.height * percent;
  56557. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  56558. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  56559. var hue = i / this.getFrequencyBinCount() * 360;
  56560. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  56561. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  56562. }
  56563. }
  56564. }
  56565. };
  56566. Analyser.prototype.stopDebugCanvas = function () {
  56567. if (this._debugCanvas) {
  56568. if (this._registerFunc) {
  56569. this._scene.unregisterBeforeRender(this._registerFunc);
  56570. this._registerFunc = null;
  56571. }
  56572. document.body.removeChild(this._debugCanvas);
  56573. this._debugCanvas = null;
  56574. this._debugCanvasContext = null;
  56575. }
  56576. };
  56577. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  56578. if (this._audioEngine.canUseWebAudio) {
  56579. inputAudioNode.connect(this._webAudioAnalyser);
  56580. this._webAudioAnalyser.connect(outputAudioNode);
  56581. }
  56582. };
  56583. Analyser.prototype.dispose = function () {
  56584. if (this._audioEngine.canUseWebAudio) {
  56585. this._webAudioAnalyser.disconnect();
  56586. }
  56587. };
  56588. return Analyser;
  56589. }());
  56590. BABYLON.Analyser = Analyser;
  56591. })(BABYLON || (BABYLON = {}));
  56592. //# sourceMappingURL=babylon.analyser.js.map
  56593. var BABYLON;
  56594. (function (BABYLON) {
  56595. var CubeTexture = /** @class */ (function (_super) {
  56596. __extends(CubeTexture, _super);
  56597. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  56598. if (extensions === void 0) { extensions = null; }
  56599. if (noMipmap === void 0) { noMipmap = false; }
  56600. if (files === void 0) { files = null; }
  56601. if (onLoad === void 0) { onLoad = null; }
  56602. if (onError === void 0) { onError = null; }
  56603. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  56604. if (prefiltered === void 0) { prefiltered = false; }
  56605. if (forcedExtension === void 0) { forcedExtension = null; }
  56606. var _this = _super.call(this, scene) || this;
  56607. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  56608. /**
  56609. * Gets or sets the center of the bounding box associated with the cube texture
  56610. * It must define where the camera used to render the texture was set
  56611. */
  56612. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56613. _this.name = rootUrl;
  56614. _this.url = rootUrl;
  56615. _this._noMipmap = noMipmap;
  56616. _this.hasAlpha = false;
  56617. _this._format = format;
  56618. _this._prefiltered = prefiltered;
  56619. _this.isCube = true;
  56620. _this._textureMatrix = BABYLON.Matrix.Identity();
  56621. if (prefiltered) {
  56622. _this.gammaSpace = false;
  56623. }
  56624. if (!rootUrl && !files) {
  56625. return _this;
  56626. }
  56627. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  56628. var lastDot = rootUrl.lastIndexOf(".");
  56629. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  56630. var isDDS = (extension === ".dds");
  56631. if (!files) {
  56632. if (!isDDS && !extensions) {
  56633. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  56634. }
  56635. files = [];
  56636. if (extensions) {
  56637. for (var index = 0; index < extensions.length; index++) {
  56638. files.push(rootUrl + extensions[index]);
  56639. }
  56640. }
  56641. }
  56642. _this._files = files;
  56643. if (!_this._texture) {
  56644. if (!scene.useDelayedTextureLoading) {
  56645. if (prefiltered) {
  56646. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  56647. }
  56648. else {
  56649. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  56650. }
  56651. }
  56652. else {
  56653. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  56654. }
  56655. }
  56656. else if (onLoad) {
  56657. if (_this._texture.isReady) {
  56658. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  56659. }
  56660. else {
  56661. _this._texture.onLoadedObservable.add(onLoad);
  56662. }
  56663. }
  56664. return _this;
  56665. }
  56666. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  56667. get: function () {
  56668. return this._boundingBoxSize;
  56669. },
  56670. /**
  56671. * Gets or sets the size of the bounding box associated with the cube texture
  56672. * When defined, the cubemap will switch to local mode
  56673. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56674. * @example https://www.babylonjs-playground.com/#RNASML
  56675. */
  56676. set: function (value) {
  56677. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56678. return;
  56679. }
  56680. this._boundingBoxSize = value;
  56681. var scene = this.getScene();
  56682. if (scene) {
  56683. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56684. }
  56685. },
  56686. enumerable: true,
  56687. configurable: true
  56688. });
  56689. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  56690. return new CubeTexture("", scene, null, noMipmap, files);
  56691. };
  56692. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  56693. if (forcedExtension === void 0) { forcedExtension = null; }
  56694. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  56695. };
  56696. // Methods
  56697. CubeTexture.prototype.delayLoad = function () {
  56698. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  56699. return;
  56700. }
  56701. var scene = this.getScene();
  56702. if (!scene) {
  56703. return;
  56704. }
  56705. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  56706. this._texture = this._getFromCache(this.url, this._noMipmap);
  56707. if (!this._texture) {
  56708. if (this._prefiltered) {
  56709. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  56710. }
  56711. else {
  56712. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  56713. }
  56714. }
  56715. };
  56716. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  56717. return this._textureMatrix;
  56718. };
  56719. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  56720. this._textureMatrix = value;
  56721. };
  56722. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  56723. var texture = BABYLON.SerializationHelper.Parse(function () {
  56724. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  56725. }, parsedTexture, scene);
  56726. // Animations
  56727. if (parsedTexture.animations) {
  56728. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  56729. var parsedAnimation = parsedTexture.animations[animationIndex];
  56730. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56731. }
  56732. }
  56733. return texture;
  56734. };
  56735. CubeTexture.prototype.clone = function () {
  56736. var _this = this;
  56737. return BABYLON.SerializationHelper.Clone(function () {
  56738. var scene = _this.getScene();
  56739. if (!scene) {
  56740. return _this;
  56741. }
  56742. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  56743. }, this);
  56744. };
  56745. return CubeTexture;
  56746. }(BABYLON.BaseTexture));
  56747. BABYLON.CubeTexture = CubeTexture;
  56748. })(BABYLON || (BABYLON = {}));
  56749. //# sourceMappingURL=babylon.cubeTexture.js.map
  56750. var BABYLON;
  56751. (function (BABYLON) {
  56752. var RenderTargetTexture = /** @class */ (function (_super) {
  56753. __extends(RenderTargetTexture, _super);
  56754. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  56755. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  56756. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56757. if (isCube === void 0) { isCube = false; }
  56758. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56759. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  56760. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  56761. if (isMulti === void 0) { isMulti = false; }
  56762. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56763. _this.isCube = isCube;
  56764. /**
  56765. * Use this list to define the list of mesh you want to render.
  56766. */
  56767. _this.renderList = new Array();
  56768. _this.renderParticles = true;
  56769. _this.renderSprites = false;
  56770. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  56771. _this.ignoreCameraViewport = false;
  56772. // Events
  56773. /**
  56774. * An event triggered when the texture is unbind.
  56775. * @type {BABYLON.Observable}
  56776. */
  56777. _this.onBeforeBindObservable = new BABYLON.Observable();
  56778. /**
  56779. * An event triggered when the texture is unbind.
  56780. * @type {BABYLON.Observable}
  56781. */
  56782. _this.onAfterUnbindObservable = new BABYLON.Observable();
  56783. /**
  56784. * An event triggered before rendering the texture
  56785. * @type {BABYLON.Observable}
  56786. */
  56787. _this.onBeforeRenderObservable = new BABYLON.Observable();
  56788. /**
  56789. * An event triggered after rendering the texture
  56790. * @type {BABYLON.Observable}
  56791. */
  56792. _this.onAfterRenderObservable = new BABYLON.Observable();
  56793. /**
  56794. * An event triggered after the texture clear
  56795. * @type {BABYLON.Observable}
  56796. */
  56797. _this.onClearObservable = new BABYLON.Observable();
  56798. _this._currentRefreshId = -1;
  56799. _this._refreshRate = 1;
  56800. _this._samples = 1;
  56801. /**
  56802. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  56803. * It must define where the camera used to render the texture is set
  56804. */
  56805. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  56806. scene = _this.getScene();
  56807. if (!scene) {
  56808. return _this;
  56809. }
  56810. _this._engine = scene.getEngine();
  56811. _this.name = name;
  56812. _this.isRenderTarget = true;
  56813. _this._initialSizeParameter = size;
  56814. _this._processSizeParameter(size);
  56815. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  56816. });
  56817. _this._generateMipMaps = generateMipMaps ? true : false;
  56818. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  56819. // Rendering groups
  56820. _this._renderingManager = new BABYLON.RenderingManager(scene);
  56821. if (isMulti) {
  56822. return _this;
  56823. }
  56824. _this._renderTargetOptions = {
  56825. generateMipMaps: generateMipMaps,
  56826. type: type,
  56827. samplingMode: samplingMode,
  56828. generateDepthBuffer: generateDepthBuffer,
  56829. generateStencilBuffer: generateStencilBuffer
  56830. };
  56831. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  56832. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56833. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56834. }
  56835. if (isCube) {
  56836. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  56837. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  56838. _this._textureMatrix = BABYLON.Matrix.Identity();
  56839. }
  56840. else {
  56841. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  56842. }
  56843. return _this;
  56844. }
  56845. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  56846. get: function () {
  56847. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  56848. },
  56849. enumerable: true,
  56850. configurable: true
  56851. });
  56852. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  56853. get: function () {
  56854. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  56855. },
  56856. enumerable: true,
  56857. configurable: true
  56858. });
  56859. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  56860. get: function () {
  56861. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  56862. },
  56863. enumerable: true,
  56864. configurable: true
  56865. });
  56866. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  56867. set: function (callback) {
  56868. if (this._onAfterUnbindObserver) {
  56869. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  56870. }
  56871. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  56872. },
  56873. enumerable: true,
  56874. configurable: true
  56875. });
  56876. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  56877. set: function (callback) {
  56878. if (this._onBeforeRenderObserver) {
  56879. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  56880. }
  56881. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  56882. },
  56883. enumerable: true,
  56884. configurable: true
  56885. });
  56886. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  56887. set: function (callback) {
  56888. if (this._onAfterRenderObserver) {
  56889. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  56890. }
  56891. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  56892. },
  56893. enumerable: true,
  56894. configurable: true
  56895. });
  56896. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  56897. set: function (callback) {
  56898. if (this._onClearObserver) {
  56899. this.onClearObservable.remove(this._onClearObserver);
  56900. }
  56901. this._onClearObserver = this.onClearObservable.add(callback);
  56902. },
  56903. enumerable: true,
  56904. configurable: true
  56905. });
  56906. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  56907. get: function () {
  56908. return this._renderTargetOptions;
  56909. },
  56910. enumerable: true,
  56911. configurable: true
  56912. });
  56913. RenderTargetTexture.prototype._onRatioRescale = function () {
  56914. if (this._sizeRatio) {
  56915. this.resize(this._initialSizeParameter);
  56916. }
  56917. };
  56918. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  56919. get: function () {
  56920. return this._boundingBoxSize;
  56921. },
  56922. /**
  56923. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  56924. * When defined, the cubemap will switch to local mode
  56925. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  56926. * @example https://www.babylonjs-playground.com/#RNASML
  56927. */
  56928. set: function (value) {
  56929. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  56930. return;
  56931. }
  56932. this._boundingBoxSize = value;
  56933. var scene = this.getScene();
  56934. if (scene) {
  56935. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  56936. }
  56937. },
  56938. enumerable: true,
  56939. configurable: true
  56940. });
  56941. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  56942. if (size.ratio) {
  56943. this._sizeRatio = size.ratio;
  56944. this._size = {
  56945. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  56946. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  56947. };
  56948. }
  56949. else {
  56950. this._size = size;
  56951. }
  56952. };
  56953. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  56954. get: function () {
  56955. return this._samples;
  56956. },
  56957. set: function (value) {
  56958. if (this._samples === value) {
  56959. return;
  56960. }
  56961. var scene = this.getScene();
  56962. if (!scene) {
  56963. return;
  56964. }
  56965. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  56966. },
  56967. enumerable: true,
  56968. configurable: true
  56969. });
  56970. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  56971. this._currentRefreshId = -1;
  56972. };
  56973. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  56974. get: function () {
  56975. return this._refreshRate;
  56976. },
  56977. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56978. set: function (value) {
  56979. this._refreshRate = value;
  56980. this.resetRefreshCounter();
  56981. },
  56982. enumerable: true,
  56983. configurable: true
  56984. });
  56985. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  56986. if (!this._postProcessManager) {
  56987. var scene = this.getScene();
  56988. if (!scene) {
  56989. return;
  56990. }
  56991. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  56992. this._postProcesses = new Array();
  56993. }
  56994. this._postProcesses.push(postProcess);
  56995. this._postProcesses[0].autoClear = false;
  56996. };
  56997. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  56998. if (!this._postProcesses) {
  56999. return;
  57000. }
  57001. if (dispose) {
  57002. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57003. var postProcess = _a[_i];
  57004. postProcess.dispose();
  57005. }
  57006. }
  57007. this._postProcesses = [];
  57008. };
  57009. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57010. if (!this._postProcesses) {
  57011. return;
  57012. }
  57013. var index = this._postProcesses.indexOf(postProcess);
  57014. if (index === -1) {
  57015. return;
  57016. }
  57017. this._postProcesses.splice(index, 1);
  57018. if (this._postProcesses.length > 0) {
  57019. this._postProcesses[0].autoClear = false;
  57020. }
  57021. };
  57022. RenderTargetTexture.prototype._shouldRender = function () {
  57023. if (this._currentRefreshId === -1) {
  57024. this._currentRefreshId = 1;
  57025. return true;
  57026. }
  57027. if (this.refreshRate === this._currentRefreshId) {
  57028. this._currentRefreshId = 1;
  57029. return true;
  57030. }
  57031. this._currentRefreshId++;
  57032. return false;
  57033. };
  57034. RenderTargetTexture.prototype.getRenderSize = function () {
  57035. if (this._size.width) {
  57036. return this._size.width;
  57037. }
  57038. return this._size;
  57039. };
  57040. RenderTargetTexture.prototype.getRenderWidth = function () {
  57041. if (this._size.width) {
  57042. return this._size.width;
  57043. }
  57044. return this._size;
  57045. };
  57046. RenderTargetTexture.prototype.getRenderHeight = function () {
  57047. if (this._size.width) {
  57048. return this._size.height;
  57049. }
  57050. return this._size;
  57051. };
  57052. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57053. get: function () {
  57054. return true;
  57055. },
  57056. enumerable: true,
  57057. configurable: true
  57058. });
  57059. RenderTargetTexture.prototype.scale = function (ratio) {
  57060. var newSize = this.getRenderSize() * ratio;
  57061. this.resize(newSize);
  57062. };
  57063. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57064. if (this.isCube) {
  57065. return this._textureMatrix;
  57066. }
  57067. return _super.prototype.getReflectionTextureMatrix.call(this);
  57068. };
  57069. RenderTargetTexture.prototype.resize = function (size) {
  57070. this.releaseInternalTexture();
  57071. var scene = this.getScene();
  57072. if (!scene) {
  57073. return;
  57074. }
  57075. this._processSizeParameter(size);
  57076. if (this.isCube) {
  57077. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57078. }
  57079. else {
  57080. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57081. }
  57082. };
  57083. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57084. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57085. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57086. var scene = this.getScene();
  57087. if (!scene) {
  57088. return;
  57089. }
  57090. var engine = scene.getEngine();
  57091. if (this.useCameraPostProcesses !== undefined) {
  57092. useCameraPostProcess = this.useCameraPostProcesses;
  57093. }
  57094. if (this._waitingRenderList) {
  57095. this.renderList = [];
  57096. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57097. var id = this._waitingRenderList[index];
  57098. var mesh_1 = scene.getMeshByID(id);
  57099. if (mesh_1) {
  57100. this.renderList.push(mesh_1);
  57101. }
  57102. }
  57103. delete this._waitingRenderList;
  57104. }
  57105. // Is predicate defined?
  57106. if (this.renderListPredicate) {
  57107. if (this.renderList) {
  57108. this.renderList.splice(0); // Clear previous renderList
  57109. }
  57110. else {
  57111. this.renderList = [];
  57112. }
  57113. var scene = this.getScene();
  57114. if (!scene) {
  57115. return;
  57116. }
  57117. var sceneMeshes = scene.meshes;
  57118. for (var index = 0; index < sceneMeshes.length; index++) {
  57119. var mesh = sceneMeshes[index];
  57120. if (this.renderListPredicate(mesh)) {
  57121. this.renderList.push(mesh);
  57122. }
  57123. }
  57124. }
  57125. this.onBeforeBindObservable.notifyObservers(this);
  57126. // Set custom projection.
  57127. // Needs to be before binding to prevent changing the aspect ratio.
  57128. var camera;
  57129. if (this.activeCamera) {
  57130. camera = this.activeCamera;
  57131. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57132. if (this.activeCamera !== scene.activeCamera) {
  57133. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57134. }
  57135. }
  57136. else {
  57137. camera = scene.activeCamera;
  57138. if (camera) {
  57139. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57140. }
  57141. }
  57142. // Prepare renderingManager
  57143. this._renderingManager.reset();
  57144. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57145. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57146. var sceneRenderId = scene.getRenderId();
  57147. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57148. var mesh = currentRenderList[meshIndex];
  57149. if (mesh) {
  57150. if (!mesh.isReady()) {
  57151. // Reset _currentRefreshId
  57152. this.resetRefreshCounter();
  57153. continue;
  57154. }
  57155. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57156. var isMasked = void 0;
  57157. if (!this.renderList && camera) {
  57158. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57159. }
  57160. else {
  57161. isMasked = false;
  57162. }
  57163. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57164. mesh._activate(sceneRenderId);
  57165. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57166. var subMesh = mesh.subMeshes[subIndex];
  57167. scene._activeIndices.addCount(subMesh.indexCount, false);
  57168. this._renderingManager.dispatch(subMesh, mesh);
  57169. }
  57170. }
  57171. }
  57172. }
  57173. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57174. var particleSystem = scene.particleSystems[particleIndex];
  57175. var emitter = particleSystem.emitter;
  57176. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57177. continue;
  57178. }
  57179. if (currentRenderList.indexOf(emitter) >= 0) {
  57180. this._renderingManager.dispatchParticles(particleSystem);
  57181. }
  57182. }
  57183. if (this.isCube) {
  57184. for (var face = 0; face < 6; face++) {
  57185. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57186. scene.incrementRenderId();
  57187. scene.resetCachedMaterial();
  57188. }
  57189. }
  57190. else {
  57191. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57192. }
  57193. this.onAfterUnbindObservable.notifyObservers(this);
  57194. if (scene.activeCamera) {
  57195. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57196. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57197. }
  57198. engine.setViewport(scene.activeCamera.viewport);
  57199. }
  57200. scene.resetCachedMaterial();
  57201. };
  57202. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57203. var minimum = 128;
  57204. var x = renderDimension * scale;
  57205. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57206. // Ensure we don't exceed the render dimension (while staying POT)
  57207. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57208. };
  57209. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57210. var _this = this;
  57211. if (!this._texture) {
  57212. return;
  57213. }
  57214. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57215. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57216. });
  57217. };
  57218. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57219. var scene = this.getScene();
  57220. if (!scene) {
  57221. return;
  57222. }
  57223. var engine = scene.getEngine();
  57224. if (!this._texture) {
  57225. return;
  57226. }
  57227. // Bind
  57228. if (this._postProcessManager) {
  57229. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57230. }
  57231. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57232. if (this._texture) {
  57233. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  57234. }
  57235. }
  57236. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57237. // Clear
  57238. if (this.onClearObservable.hasObservers()) {
  57239. this.onClearObservable.notifyObservers(engine);
  57240. }
  57241. else {
  57242. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57243. }
  57244. if (!this._doNotChangeAspectRatio) {
  57245. scene.updateTransformMatrix(true);
  57246. }
  57247. // Render
  57248. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57249. if (this._postProcessManager) {
  57250. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57251. }
  57252. else if (useCameraPostProcess) {
  57253. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57254. }
  57255. if (!this._doNotChangeAspectRatio) {
  57256. scene.updateTransformMatrix(true);
  57257. }
  57258. // Dump ?
  57259. if (dumpForDebug) {
  57260. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57261. }
  57262. // Unbind
  57263. if (!this.isCube || faceIndex === 5) {
  57264. if (this.isCube) {
  57265. if (faceIndex === 5) {
  57266. engine.generateMipMapsForCubemap(this._texture);
  57267. }
  57268. }
  57269. this.unbindFrameBuffer(engine, faceIndex);
  57270. }
  57271. else {
  57272. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57273. }
  57274. };
  57275. /**
  57276. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57277. * This allowed control for front to back rendering or reversly depending of the special needs.
  57278. *
  57279. * @param renderingGroupId The rendering group id corresponding to its index
  57280. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57281. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57282. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57283. */
  57284. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57285. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57286. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57287. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57288. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57289. };
  57290. /**
  57291. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57292. *
  57293. * @param renderingGroupId The rendering group id corresponding to its index
  57294. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57295. */
  57296. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57297. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57298. };
  57299. RenderTargetTexture.prototype.clone = function () {
  57300. var textureSize = this.getSize();
  57301. 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);
  57302. // Base texture
  57303. newTexture.hasAlpha = this.hasAlpha;
  57304. newTexture.level = this.level;
  57305. // RenderTarget Texture
  57306. newTexture.coordinatesMode = this.coordinatesMode;
  57307. if (this.renderList) {
  57308. newTexture.renderList = this.renderList.slice(0);
  57309. }
  57310. return newTexture;
  57311. };
  57312. RenderTargetTexture.prototype.serialize = function () {
  57313. if (!this.name) {
  57314. return null;
  57315. }
  57316. var serializationObject = _super.prototype.serialize.call(this);
  57317. serializationObject.renderTargetSize = this.getRenderSize();
  57318. serializationObject.renderList = [];
  57319. if (this.renderList) {
  57320. for (var index = 0; index < this.renderList.length; index++) {
  57321. serializationObject.renderList.push(this.renderList[index].id);
  57322. }
  57323. }
  57324. return serializationObject;
  57325. };
  57326. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57327. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57328. var objBuffer = this.getInternalTexture();
  57329. var scene = this.getScene();
  57330. if (objBuffer && scene) {
  57331. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57332. }
  57333. };
  57334. RenderTargetTexture.prototype.dispose = function () {
  57335. if (this._postProcessManager) {
  57336. this._postProcessManager.dispose();
  57337. this._postProcessManager = null;
  57338. }
  57339. this.clearPostProcesses(true);
  57340. if (this._resizeObserver) {
  57341. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57342. this._resizeObserver = null;
  57343. }
  57344. this.renderList = null;
  57345. // Remove from custom render targets
  57346. var scene = this.getScene();
  57347. if (!scene) {
  57348. return;
  57349. }
  57350. var index = scene.customRenderTargets.indexOf(this);
  57351. if (index >= 0) {
  57352. scene.customRenderTargets.splice(index, 1);
  57353. }
  57354. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57355. var camera = _a[_i];
  57356. index = camera.customRenderTargets.indexOf(this);
  57357. if (index >= 0) {
  57358. camera.customRenderTargets.splice(index, 1);
  57359. }
  57360. }
  57361. _super.prototype.dispose.call(this);
  57362. };
  57363. RenderTargetTexture.prototype._rebuild = function () {
  57364. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57365. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57366. }
  57367. if (this._postProcessManager) {
  57368. this._postProcessManager._rebuild();
  57369. }
  57370. };
  57371. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57372. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57373. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57374. return RenderTargetTexture;
  57375. }(BABYLON.Texture));
  57376. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57377. })(BABYLON || (BABYLON = {}));
  57378. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57379. var BABYLON;
  57380. (function (BABYLON) {
  57381. ;
  57382. var MultiRenderTarget = /** @class */ (function (_super) {
  57383. __extends(MultiRenderTarget, _super);
  57384. function MultiRenderTarget(name, size, count, scene, options) {
  57385. var _this = this;
  57386. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57387. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57388. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57389. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57390. _this._engine = scene.getEngine();
  57391. if (!_this.isSupported) {
  57392. _this.dispose();
  57393. return;
  57394. }
  57395. var types = [];
  57396. var samplingModes = [];
  57397. for (var i = 0; i < count; i++) {
  57398. if (options && options.types && options.types[i] !== undefined) {
  57399. types.push(options.types[i]);
  57400. }
  57401. else {
  57402. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57403. }
  57404. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57405. samplingModes.push(options.samplingModes[i]);
  57406. }
  57407. else {
  57408. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57409. }
  57410. }
  57411. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57412. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57413. _this._size = size;
  57414. _this._multiRenderTargetOptions = {
  57415. samplingModes: samplingModes,
  57416. generateMipMaps: generateMipMaps,
  57417. generateDepthBuffer: generateDepthBuffer,
  57418. generateStencilBuffer: generateStencilBuffer,
  57419. generateDepthTexture: generateDepthTexture,
  57420. types: types,
  57421. textureCount: count
  57422. };
  57423. _this._createInternalTextures();
  57424. _this._createTextures();
  57425. return _this;
  57426. }
  57427. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57428. get: function () {
  57429. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57430. },
  57431. enumerable: true,
  57432. configurable: true
  57433. });
  57434. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57435. get: function () {
  57436. return this._textures;
  57437. },
  57438. enumerable: true,
  57439. configurable: true
  57440. });
  57441. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57442. get: function () {
  57443. return this._textures[this._textures.length - 1];
  57444. },
  57445. enumerable: true,
  57446. configurable: true
  57447. });
  57448. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57449. set: function (wrap) {
  57450. if (this._textures) {
  57451. for (var i = 0; i < this._textures.length; i++) {
  57452. this._textures[i].wrapU = wrap;
  57453. }
  57454. }
  57455. },
  57456. enumerable: true,
  57457. configurable: true
  57458. });
  57459. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  57460. set: function (wrap) {
  57461. if (this._textures) {
  57462. for (var i = 0; i < this._textures.length; i++) {
  57463. this._textures[i].wrapV = wrap;
  57464. }
  57465. }
  57466. },
  57467. enumerable: true,
  57468. configurable: true
  57469. });
  57470. MultiRenderTarget.prototype._rebuild = function () {
  57471. this.releaseInternalTextures();
  57472. this._createInternalTextures();
  57473. for (var i = 0; i < this._internalTextures.length; i++) {
  57474. var texture = this._textures[i];
  57475. texture._texture = this._internalTextures[i];
  57476. }
  57477. // Keeps references to frame buffer and stencil/depth buffer
  57478. this._texture = this._internalTextures[0];
  57479. };
  57480. MultiRenderTarget.prototype._createInternalTextures = function () {
  57481. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  57482. };
  57483. MultiRenderTarget.prototype._createTextures = function () {
  57484. this._textures = [];
  57485. for (var i = 0; i < this._internalTextures.length; i++) {
  57486. var texture = new BABYLON.Texture(null, this.getScene());
  57487. texture._texture = this._internalTextures[i];
  57488. this._textures.push(texture);
  57489. }
  57490. // Keeps references to frame buffer and stencil/depth buffer
  57491. this._texture = this._internalTextures[0];
  57492. };
  57493. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  57494. get: function () {
  57495. return this._samples;
  57496. },
  57497. set: function (value) {
  57498. if (this._samples === value) {
  57499. return;
  57500. }
  57501. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  57502. },
  57503. enumerable: true,
  57504. configurable: true
  57505. });
  57506. MultiRenderTarget.prototype.resize = function (size) {
  57507. this.releaseInternalTextures();
  57508. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  57509. this._createInternalTextures();
  57510. };
  57511. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57512. var _this = this;
  57513. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  57514. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57515. });
  57516. };
  57517. MultiRenderTarget.prototype.dispose = function () {
  57518. this.releaseInternalTextures();
  57519. _super.prototype.dispose.call(this);
  57520. };
  57521. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  57522. if (!this._internalTextures) {
  57523. return;
  57524. }
  57525. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  57526. if (this._internalTextures[i] !== undefined) {
  57527. this._internalTextures[i].dispose();
  57528. this._internalTextures.splice(i, 1);
  57529. }
  57530. }
  57531. };
  57532. return MultiRenderTarget;
  57533. }(BABYLON.RenderTargetTexture));
  57534. BABYLON.MultiRenderTarget = MultiRenderTarget;
  57535. })(BABYLON || (BABYLON = {}));
  57536. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  57537. var BABYLON;
  57538. (function (BABYLON) {
  57539. var MirrorTexture = /** @class */ (function (_super) {
  57540. __extends(MirrorTexture, _super);
  57541. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  57542. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57543. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  57544. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57545. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  57546. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  57547. _this._transformMatrix = BABYLON.Matrix.Zero();
  57548. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  57549. _this._adaptiveBlurKernel = 0;
  57550. _this._blurKernelX = 0;
  57551. _this._blurKernelY = 0;
  57552. _this._blurRatio = 1.0;
  57553. _this.ignoreCameraViewport = true;
  57554. _this.onBeforeRenderObservable.add(function () {
  57555. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  57556. _this._savedViewMatrix = scene.getViewMatrix();
  57557. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  57558. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  57559. scene.clipPlane = _this.mirrorPlane;
  57560. scene.getEngine().cullBackFaces = false;
  57561. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  57562. });
  57563. _this.onAfterRenderObservable.add(function () {
  57564. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  57565. scene.getEngine().cullBackFaces = true;
  57566. scene._mirroredCameraPosition = null;
  57567. delete scene.clipPlane;
  57568. });
  57569. return _this;
  57570. }
  57571. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  57572. get: function () {
  57573. return this._blurRatio;
  57574. },
  57575. set: function (value) {
  57576. if (this._blurRatio === value) {
  57577. return;
  57578. }
  57579. this._blurRatio = value;
  57580. this._preparePostProcesses();
  57581. },
  57582. enumerable: true,
  57583. configurable: true
  57584. });
  57585. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  57586. set: function (value) {
  57587. this._adaptiveBlurKernel = value;
  57588. this._autoComputeBlurKernel();
  57589. },
  57590. enumerable: true,
  57591. configurable: true
  57592. });
  57593. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  57594. set: function (value) {
  57595. this.blurKernelX = value;
  57596. this.blurKernelY = value;
  57597. },
  57598. enumerable: true,
  57599. configurable: true
  57600. });
  57601. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  57602. get: function () {
  57603. return this._blurKernelX;
  57604. },
  57605. set: function (value) {
  57606. if (this._blurKernelX === value) {
  57607. return;
  57608. }
  57609. this._blurKernelX = value;
  57610. this._preparePostProcesses();
  57611. },
  57612. enumerable: true,
  57613. configurable: true
  57614. });
  57615. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  57616. get: function () {
  57617. return this._blurKernelY;
  57618. },
  57619. set: function (value) {
  57620. if (this._blurKernelY === value) {
  57621. return;
  57622. }
  57623. this._blurKernelY = value;
  57624. this._preparePostProcesses();
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  57630. var engine = this.getScene().getEngine();
  57631. var dw = this.getRenderWidth() / engine.getRenderWidth();
  57632. var dh = this.getRenderHeight() / engine.getRenderHeight();
  57633. this.blurKernelX = this._adaptiveBlurKernel * dw;
  57634. this.blurKernelY = this._adaptiveBlurKernel * dh;
  57635. };
  57636. MirrorTexture.prototype._onRatioRescale = function () {
  57637. if (this._sizeRatio) {
  57638. this.resize(this._initialSizeParameter);
  57639. if (!this._adaptiveBlurKernel) {
  57640. this._preparePostProcesses();
  57641. }
  57642. }
  57643. if (this._adaptiveBlurKernel) {
  57644. this._autoComputeBlurKernel();
  57645. }
  57646. };
  57647. MirrorTexture.prototype._preparePostProcesses = function () {
  57648. this.clearPostProcesses(true);
  57649. if (this._blurKernelX && this._blurKernelY) {
  57650. var engine = this.getScene().getEngine();
  57651. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  57652. 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);
  57653. this._blurX.autoClear = false;
  57654. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  57655. this._blurX.inputTexture = this._texture;
  57656. }
  57657. else {
  57658. this._blurX.alwaysForcePOT = true;
  57659. }
  57660. 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);
  57661. this._blurY.autoClear = false;
  57662. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  57663. this.addPostProcess(this._blurX);
  57664. this.addPostProcess(this._blurY);
  57665. }
  57666. else {
  57667. if (this._blurY) {
  57668. this.removePostProcess(this._blurY);
  57669. this._blurY.dispose();
  57670. this._blurY = null;
  57671. }
  57672. if (this._blurX) {
  57673. this.removePostProcess(this._blurX);
  57674. this._blurX.dispose();
  57675. this._blurX = null;
  57676. }
  57677. }
  57678. };
  57679. MirrorTexture.prototype.clone = function () {
  57680. var scene = this.getScene();
  57681. if (!scene) {
  57682. return this;
  57683. }
  57684. var textureSize = this.getSize();
  57685. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  57686. // Base texture
  57687. newTexture.hasAlpha = this.hasAlpha;
  57688. newTexture.level = this.level;
  57689. // Mirror Texture
  57690. newTexture.mirrorPlane = this.mirrorPlane.clone();
  57691. if (this.renderList) {
  57692. newTexture.renderList = this.renderList.slice(0);
  57693. }
  57694. return newTexture;
  57695. };
  57696. MirrorTexture.prototype.serialize = function () {
  57697. if (!this.name) {
  57698. return null;
  57699. }
  57700. var serializationObject = _super.prototype.serialize.call(this);
  57701. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  57702. return serializationObject;
  57703. };
  57704. return MirrorTexture;
  57705. }(BABYLON.RenderTargetTexture));
  57706. BABYLON.MirrorTexture = MirrorTexture;
  57707. })(BABYLON || (BABYLON = {}));
  57708. //# sourceMappingURL=babylon.mirrorTexture.js.map
  57709. var BABYLON;
  57710. (function (BABYLON) {
  57711. /**
  57712. * Creates a refraction texture used by refraction channel of the standard material.
  57713. * @param name the texture name
  57714. * @param size size of the underlying texture
  57715. * @param scene root scene
  57716. */
  57717. var RefractionTexture = /** @class */ (function (_super) {
  57718. __extends(RefractionTexture, _super);
  57719. function RefractionTexture(name, size, scene, generateMipMaps) {
  57720. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  57721. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  57722. _this.depth = 2.0;
  57723. _this.onBeforeRenderObservable.add(function () {
  57724. scene.clipPlane = _this.refractionPlane;
  57725. });
  57726. _this.onAfterRenderObservable.add(function () {
  57727. delete scene.clipPlane;
  57728. });
  57729. return _this;
  57730. }
  57731. RefractionTexture.prototype.clone = function () {
  57732. var scene = this.getScene();
  57733. if (!scene) {
  57734. return this;
  57735. }
  57736. var textureSize = this.getSize();
  57737. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  57738. // Base texture
  57739. newTexture.hasAlpha = this.hasAlpha;
  57740. newTexture.level = this.level;
  57741. // Refraction Texture
  57742. newTexture.refractionPlane = this.refractionPlane.clone();
  57743. if (this.renderList) {
  57744. newTexture.renderList = this.renderList.slice(0);
  57745. }
  57746. newTexture.depth = this.depth;
  57747. return newTexture;
  57748. };
  57749. RefractionTexture.prototype.serialize = function () {
  57750. if (!this.name) {
  57751. return null;
  57752. }
  57753. var serializationObject = _super.prototype.serialize.call(this);
  57754. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  57755. serializationObject.depth = this.depth;
  57756. return serializationObject;
  57757. };
  57758. return RefractionTexture;
  57759. }(BABYLON.RenderTargetTexture));
  57760. BABYLON.RefractionTexture = RefractionTexture;
  57761. })(BABYLON || (BABYLON = {}));
  57762. //# sourceMappingURL=babylon.refractionTexture.js.map
  57763. var BABYLON;
  57764. (function (BABYLON) {
  57765. var DynamicTexture = /** @class */ (function (_super) {
  57766. __extends(DynamicTexture, _super);
  57767. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  57768. if (scene === void 0) { scene = null; }
  57769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57770. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57771. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  57772. _this.name = name;
  57773. _this._engine = _this.getScene().getEngine();
  57774. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57775. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57776. _this._generateMipMaps = generateMipMaps;
  57777. if (options.getContext) {
  57778. _this._canvas = options;
  57779. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57780. }
  57781. else {
  57782. _this._canvas = document.createElement("canvas");
  57783. if (options.width) {
  57784. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  57785. }
  57786. else {
  57787. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  57788. }
  57789. }
  57790. var textureSize = _this.getSize();
  57791. _this._canvas.width = textureSize.width;
  57792. _this._canvas.height = textureSize.height;
  57793. _this._context = _this._canvas.getContext("2d");
  57794. return _this;
  57795. }
  57796. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  57797. get: function () {
  57798. return true;
  57799. },
  57800. enumerable: true,
  57801. configurable: true
  57802. });
  57803. DynamicTexture.prototype._recreate = function (textureSize) {
  57804. this._canvas.width = textureSize.width;
  57805. this._canvas.height = textureSize.height;
  57806. this.releaseInternalTexture();
  57807. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  57808. };
  57809. DynamicTexture.prototype.scale = function (ratio) {
  57810. var textureSize = this.getSize();
  57811. textureSize.width *= ratio;
  57812. textureSize.height *= ratio;
  57813. this._recreate(textureSize);
  57814. };
  57815. DynamicTexture.prototype.scaleTo = function (width, height) {
  57816. var textureSize = this.getSize();
  57817. textureSize.width = width;
  57818. textureSize.height = height;
  57819. this._recreate(textureSize);
  57820. };
  57821. DynamicTexture.prototype.getContext = function () {
  57822. return this._context;
  57823. };
  57824. DynamicTexture.prototype.clear = function () {
  57825. var size = this.getSize();
  57826. this._context.fillRect(0, 0, size.width, size.height);
  57827. };
  57828. DynamicTexture.prototype.update = function (invertY) {
  57829. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  57830. };
  57831. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  57832. if (update === void 0) { update = true; }
  57833. var size = this.getSize();
  57834. if (clearColor) {
  57835. this._context.fillStyle = clearColor;
  57836. this._context.fillRect(0, 0, size.width, size.height);
  57837. }
  57838. this._context.font = font;
  57839. if (x === null || x === undefined) {
  57840. var textSize = this._context.measureText(text);
  57841. x = (size.width - textSize.width) / 2;
  57842. }
  57843. if (y === null || y === undefined) {
  57844. var fontSize = parseInt((font.replace(/\D/g, '')));
  57845. ;
  57846. y = (size.height / 2) + (fontSize / 3.65);
  57847. }
  57848. this._context.fillStyle = color;
  57849. this._context.fillText(text, x, y);
  57850. if (update) {
  57851. this.update(invertY);
  57852. }
  57853. };
  57854. DynamicTexture.prototype.clone = function () {
  57855. var scene = this.getScene();
  57856. if (!scene) {
  57857. return this;
  57858. }
  57859. var textureSize = this.getSize();
  57860. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  57861. // Base texture
  57862. newTexture.hasAlpha = this.hasAlpha;
  57863. newTexture.level = this.level;
  57864. // Dynamic Texture
  57865. newTexture.wrapU = this.wrapU;
  57866. newTexture.wrapV = this.wrapV;
  57867. return newTexture;
  57868. };
  57869. DynamicTexture.prototype._rebuild = function () {
  57870. this.update();
  57871. };
  57872. return DynamicTexture;
  57873. }(BABYLON.Texture));
  57874. BABYLON.DynamicTexture = DynamicTexture;
  57875. })(BABYLON || (BABYLON = {}));
  57876. //# sourceMappingURL=babylon.dynamicTexture.js.map
  57877. var BABYLON;
  57878. (function (BABYLON) {
  57879. var VideoTexture = /** @class */ (function (_super) {
  57880. __extends(VideoTexture, _super);
  57881. /**
  57882. * Creates a video texture.
  57883. * Sample : https://doc.babylonjs.com/how_to/video_texture
  57884. * @param {string | null} name optional name, will detect from video source, if not defined
  57885. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  57886. * @param {BABYLON.Scene} scene is obviously the current scene.
  57887. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  57888. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  57889. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  57890. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  57891. */
  57892. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  57893. if (generateMipMaps === void 0) { generateMipMaps = false; }
  57894. if (invertY === void 0) { invertY = false; }
  57895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57896. if (settings === void 0) { settings = {
  57897. autoPlay: true,
  57898. loop: true,
  57899. autoUpdateTexture: true,
  57900. }; }
  57901. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  57902. _this._createInternalTexture = function () {
  57903. if (_this._texture != null) {
  57904. return;
  57905. }
  57906. if (!_this._engine.needPOTTextures ||
  57907. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  57908. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57909. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57910. }
  57911. else {
  57912. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57913. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57914. _this._generateMipMaps = false;
  57915. }
  57916. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  57917. _this._texture.isReady = true;
  57918. _this._updateInternalTexture();
  57919. };
  57920. _this.reset = function () {
  57921. if (_this._texture == null) {
  57922. return;
  57923. }
  57924. _this._texture.dispose();
  57925. _this._texture = null;
  57926. };
  57927. _this._updateInternalTexture = function (e) {
  57928. if (_this._texture == null || !_this._texture.isReady) {
  57929. return;
  57930. }
  57931. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  57932. return;
  57933. }
  57934. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  57935. };
  57936. _this._engine = _this.getScene().getEngine();
  57937. _this._generateMipMaps = generateMipMaps;
  57938. _this._samplingMode = samplingMode;
  57939. _this.autoUpdateTexture = settings.autoUpdateTexture;
  57940. _this.name = name || _this._getName(src);
  57941. _this.video = _this._getVideo(src);
  57942. if (settings.autoPlay !== undefined) {
  57943. _this.video.autoplay = settings.autoPlay;
  57944. }
  57945. if (settings.loop !== undefined) {
  57946. _this.video.loop = settings.loop;
  57947. }
  57948. _this.video.addEventListener("canplay", _this._createInternalTexture);
  57949. _this.video.addEventListener("paused", _this._updateInternalTexture);
  57950. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  57951. _this.video.addEventListener("emptied", _this.reset);
  57952. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  57953. _this._createInternalTexture();
  57954. }
  57955. return _this;
  57956. }
  57957. VideoTexture.prototype._getName = function (src) {
  57958. if (src instanceof HTMLVideoElement) {
  57959. return src.currentSrc;
  57960. }
  57961. if (typeof src === "object") {
  57962. return src.toString();
  57963. }
  57964. return src;
  57965. };
  57966. ;
  57967. VideoTexture.prototype._getVideo = function (src) {
  57968. if (src instanceof HTMLVideoElement) {
  57969. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  57970. return src;
  57971. }
  57972. var video = document.createElement("video");
  57973. if (typeof src === "string") {
  57974. BABYLON.Tools.SetCorsBehavior(src, video);
  57975. video.src = src;
  57976. }
  57977. else {
  57978. BABYLON.Tools.SetCorsBehavior(src[0], video);
  57979. src.forEach(function (url) {
  57980. var source = document.createElement("source");
  57981. source.src = url;
  57982. video.appendChild(source);
  57983. });
  57984. }
  57985. return video;
  57986. };
  57987. ;
  57988. /**
  57989. * Internal method to initiate `update`.
  57990. */
  57991. VideoTexture.prototype._rebuild = function () {
  57992. this.update();
  57993. };
  57994. /**
  57995. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  57996. */
  57997. VideoTexture.prototype.update = function () {
  57998. if (!this.autoUpdateTexture) {
  57999. // Expecting user to call `updateTexture` manually
  58000. return;
  58001. }
  58002. this.updateTexture(true);
  58003. };
  58004. /**
  58005. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58006. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58007. */
  58008. VideoTexture.prototype.updateTexture = function (isVisible) {
  58009. if (!isVisible) {
  58010. return;
  58011. }
  58012. if (this.video.paused) {
  58013. return;
  58014. }
  58015. this._updateInternalTexture();
  58016. };
  58017. /**
  58018. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58019. * @param url New url.
  58020. */
  58021. VideoTexture.prototype.updateURL = function (url) {
  58022. this.video.src = url;
  58023. };
  58024. VideoTexture.prototype.dispose = function () {
  58025. _super.prototype.dispose.call(this);
  58026. this.video.removeEventListener("canplay", this._createInternalTexture);
  58027. this.video.removeEventListener("paused", this._updateInternalTexture);
  58028. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58029. this.video.removeEventListener("emptied", this.reset);
  58030. };
  58031. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58032. var video = document.createElement("video");
  58033. var constraintsDeviceId;
  58034. if (constraints && constraints.deviceId) {
  58035. constraintsDeviceId = {
  58036. exact: constraints.deviceId,
  58037. };
  58038. }
  58039. navigator.getUserMedia =
  58040. navigator.getUserMedia ||
  58041. navigator.webkitGetUserMedia ||
  58042. navigator.mozGetUserMedia ||
  58043. navigator.msGetUserMedia;
  58044. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58045. if (navigator.getUserMedia) {
  58046. navigator.getUserMedia({
  58047. video: {
  58048. deviceId: constraintsDeviceId,
  58049. width: {
  58050. min: (constraints && constraints.minWidth) || 256,
  58051. max: (constraints && constraints.maxWidth) || 640,
  58052. },
  58053. height: {
  58054. min: (constraints && constraints.minHeight) || 256,
  58055. max: (constraints && constraints.maxHeight) || 480,
  58056. },
  58057. },
  58058. }, function (stream) {
  58059. if (video.mozSrcObject !== undefined) {
  58060. // hack for Firefox < 19
  58061. video.mozSrcObject = stream;
  58062. }
  58063. else {
  58064. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58065. }
  58066. video.play();
  58067. if (onReady) {
  58068. onReady(new VideoTexture("video", video, scene, true, true));
  58069. }
  58070. }, function (e) {
  58071. BABYLON.Tools.Error(e.name);
  58072. });
  58073. }
  58074. };
  58075. return VideoTexture;
  58076. }(BABYLON.Texture));
  58077. BABYLON.VideoTexture = VideoTexture;
  58078. })(BABYLON || (BABYLON = {}));
  58079. //# sourceMappingURL=babylon.videoTexture.js.map
  58080. var BABYLON;
  58081. (function (BABYLON) {
  58082. var RawTexture = /** @class */ (function (_super) {
  58083. __extends(RawTexture, _super);
  58084. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58085. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58086. if (invertY === void 0) { invertY = false; }
  58087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58088. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58089. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58090. _this.format = format;
  58091. _this._engine = scene.getEngine();
  58092. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58093. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58094. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58095. return _this;
  58096. }
  58097. RawTexture.prototype.update = function (data) {
  58098. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58099. };
  58100. // Statics
  58101. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58102. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58103. if (invertY === void 0) { invertY = false; }
  58104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58105. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58106. };
  58107. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58108. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58109. if (invertY === void 0) { invertY = false; }
  58110. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58111. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58112. };
  58113. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58114. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58115. if (invertY === void 0) { invertY = false; }
  58116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58117. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58118. };
  58119. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58120. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58121. if (invertY === void 0) { invertY = false; }
  58122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58123. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58124. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58125. };
  58126. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58127. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58128. if (invertY === void 0) { invertY = false; }
  58129. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58130. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58131. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58132. };
  58133. return RawTexture;
  58134. }(BABYLON.Texture));
  58135. BABYLON.RawTexture = RawTexture;
  58136. })(BABYLON || (BABYLON = {}));
  58137. //# sourceMappingURL=babylon.rawTexture.js.map
  58138. var BABYLON;
  58139. (function (BABYLON) {
  58140. /**
  58141. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58142. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58143. */
  58144. var PostProcess = /** @class */ (function () {
  58145. /**
  58146. * Creates a new instance of @see PostProcess
  58147. * @param name The name of the PostProcess.
  58148. * @param fragmentUrl The url of the fragment shader to be used.
  58149. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58150. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58151. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58152. * @param camera The camera to apply the render pass to.
  58153. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58154. * @param engine The engine which the post process will be applied. (default: current engine)
  58155. * @param reusable If the post process can be reused on the same frame. (default: false)
  58156. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58157. * @param textureType Type of textures used when performing the post process. (default: 0)
  58158. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58159. * @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
  58160. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58161. */
  58162. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58164. if (defines === void 0) { defines = null; }
  58165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58166. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58167. if (blockCompilation === void 0) { blockCompilation = false; }
  58168. this.name = name;
  58169. /**
  58170. * Width of the texture to apply the post process on
  58171. */
  58172. this.width = -1;
  58173. /**
  58174. * Height of the texture to apply the post process on
  58175. */
  58176. this.height = -1;
  58177. /**
  58178. * If the buffer needs to be cleared before applying the post process. (default: true)
  58179. * Should be set to false if shader will overwrite all previous pixels.
  58180. */
  58181. this.autoClear = true;
  58182. /**
  58183. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58184. */
  58185. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58186. /**
  58187. * Animations to be used for the post processing
  58188. */
  58189. this.animations = new Array();
  58190. /**
  58191. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58192. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58193. */
  58194. this.enablePixelPerfectMode = false;
  58195. /**
  58196. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58197. */
  58198. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58199. /**
  58200. * Force textures to be a power of two (default: false)
  58201. */
  58202. this.alwaysForcePOT = false;
  58203. /**
  58204. * Number of sample textures (default: 1)
  58205. */
  58206. this.samples = 1;
  58207. /**
  58208. * Modify the scale of the post process to be the same as the viewport (default: false)
  58209. */
  58210. this.adaptScaleToCurrentViewport = false;
  58211. this._reusable = false;
  58212. /**
  58213. * Smart array of input and output textures for the post process.
  58214. */
  58215. this._textures = new BABYLON.SmartArray(2);
  58216. /**
  58217. * The index in _textures that corresponds to the output texture.
  58218. */
  58219. this._currentRenderTextureInd = 0;
  58220. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58221. this._texelSize = BABYLON.Vector2.Zero();
  58222. // Events
  58223. /**
  58224. * An event triggered when the postprocess is activated.
  58225. * @type {BABYLON.Observable}
  58226. */
  58227. this.onActivateObservable = new BABYLON.Observable();
  58228. /**
  58229. * An event triggered when the postprocess changes its size.
  58230. * @type {BABYLON.Observable}
  58231. */
  58232. this.onSizeChangedObservable = new BABYLON.Observable();
  58233. /**
  58234. * An event triggered when the postprocess applies its effect.
  58235. * @type {BABYLON.Observable}
  58236. */
  58237. this.onApplyObservable = new BABYLON.Observable();
  58238. /**
  58239. * An event triggered before rendering the postprocess
  58240. * @type {BABYLON.Observable}
  58241. */
  58242. this.onBeforeRenderObservable = new BABYLON.Observable();
  58243. /**
  58244. * An event triggered after rendering the postprocess
  58245. * @type {BABYLON.Observable}
  58246. */
  58247. this.onAfterRenderObservable = new BABYLON.Observable();
  58248. if (camera != null) {
  58249. this._camera = camera;
  58250. this._scene = camera.getScene();
  58251. camera.attachPostProcess(this);
  58252. this._engine = this._scene.getEngine();
  58253. this._scene.postProcesses.push(this);
  58254. }
  58255. else if (engine) {
  58256. this._engine = engine;
  58257. this._engine.postProcesses.push(this);
  58258. }
  58259. this._options = options;
  58260. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58261. this._reusable = reusable || false;
  58262. this._textureType = textureType;
  58263. this._samplers = samplers || [];
  58264. this._samplers.push("textureSampler");
  58265. this._fragmentUrl = fragmentUrl;
  58266. this._vertexUrl = vertexUrl;
  58267. this._parameters = parameters || [];
  58268. this._parameters.push("scale");
  58269. this._indexParameters = indexParameters;
  58270. if (!blockCompilation) {
  58271. this.updateEffect(defines);
  58272. }
  58273. }
  58274. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58275. /**
  58276. * A function that is added to the onActivateObservable
  58277. */
  58278. set: function (callback) {
  58279. if (this._onActivateObserver) {
  58280. this.onActivateObservable.remove(this._onActivateObserver);
  58281. }
  58282. if (callback) {
  58283. this._onActivateObserver = this.onActivateObservable.add(callback);
  58284. }
  58285. },
  58286. enumerable: true,
  58287. configurable: true
  58288. });
  58289. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58290. /**
  58291. * A function that is added to the onSizeChangedObservable
  58292. */
  58293. set: function (callback) {
  58294. if (this._onSizeChangedObserver) {
  58295. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58296. }
  58297. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58298. },
  58299. enumerable: true,
  58300. configurable: true
  58301. });
  58302. Object.defineProperty(PostProcess.prototype, "onApply", {
  58303. /**
  58304. * A function that is added to the onApplyObservable
  58305. */
  58306. set: function (callback) {
  58307. if (this._onApplyObserver) {
  58308. this.onApplyObservable.remove(this._onApplyObserver);
  58309. }
  58310. this._onApplyObserver = this.onApplyObservable.add(callback);
  58311. },
  58312. enumerable: true,
  58313. configurable: true
  58314. });
  58315. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58316. /**
  58317. * A function that is added to the onBeforeRenderObservable
  58318. */
  58319. set: function (callback) {
  58320. if (this._onBeforeRenderObserver) {
  58321. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58322. }
  58323. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58324. },
  58325. enumerable: true,
  58326. configurable: true
  58327. });
  58328. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58329. /**
  58330. * A function that is added to the onAfterRenderObservable
  58331. */
  58332. set: function (callback) {
  58333. if (this._onAfterRenderObserver) {
  58334. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58335. }
  58336. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58337. },
  58338. enumerable: true,
  58339. configurable: true
  58340. });
  58341. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58342. /**
  58343. * 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
  58344. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58345. */
  58346. get: function () {
  58347. return this._textures.data[this._currentRenderTextureInd];
  58348. },
  58349. set: function (value) {
  58350. this._forcedOutputTexture = value;
  58351. },
  58352. enumerable: true,
  58353. configurable: true
  58354. });
  58355. /**
  58356. * Gets the camera which post process is applied to.
  58357. * @returns The camera the post process is applied to.
  58358. */
  58359. PostProcess.prototype.getCamera = function () {
  58360. return this._camera;
  58361. };
  58362. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58363. /**
  58364. * Gets the texel size of the postprocess.
  58365. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58366. */
  58367. get: function () {
  58368. if (this._shareOutputWithPostProcess) {
  58369. return this._shareOutputWithPostProcess.texelSize;
  58370. }
  58371. if (this._forcedOutputTexture) {
  58372. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58373. }
  58374. return this._texelSize;
  58375. },
  58376. enumerable: true,
  58377. configurable: true
  58378. });
  58379. /**
  58380. * Gets the engine which this post process belongs to.
  58381. * @returns The engine the post process was enabled with.
  58382. */
  58383. PostProcess.prototype.getEngine = function () {
  58384. return this._engine;
  58385. };
  58386. /**
  58387. * The effect that is created when initializing the post process.
  58388. * @returns The created effect corrisponding the the postprocess.
  58389. */
  58390. PostProcess.prototype.getEffect = function () {
  58391. return this._effect;
  58392. };
  58393. /**
  58394. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58395. * @param postProcess The post process to share the output with.
  58396. * @returns This post process.
  58397. */
  58398. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58399. this._disposeTextures();
  58400. this._shareOutputWithPostProcess = postProcess;
  58401. return this;
  58402. };
  58403. /**
  58404. * Updates the effect with the current post process compile time values and recompiles the shader.
  58405. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58406. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58407. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58408. * @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
  58409. * @param onCompiled Called when the shader has been compiled.
  58410. * @param onError Called if there is an error when compiling a shader.
  58411. */
  58412. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58413. if (defines === void 0) { defines = null; }
  58414. if (uniforms === void 0) { uniforms = null; }
  58415. if (samplers === void 0) { samplers = null; }
  58416. 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);
  58417. };
  58418. /**
  58419. * The post process is reusable if it can be used multiple times within one frame.
  58420. * @returns If the post process is reusable
  58421. */
  58422. PostProcess.prototype.isReusable = function () {
  58423. return this._reusable;
  58424. };
  58425. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58426. PostProcess.prototype.markTextureDirty = function () {
  58427. this.width = -1;
  58428. };
  58429. /**
  58430. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58431. * 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.
  58432. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58433. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58434. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58435. */
  58436. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58437. var _this = this;
  58438. if (sourceTexture === void 0) { sourceTexture = null; }
  58439. camera = camera || this._camera;
  58440. var scene = camera.getScene();
  58441. var engine = scene.getEngine();
  58442. var maxSize = engine.getCaps().maxTextureSize;
  58443. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58444. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58445. var desiredWidth = (this._options.width || requiredWidth);
  58446. var desiredHeight = this._options.height || requiredHeight;
  58447. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58448. if (this.adaptScaleToCurrentViewport) {
  58449. var currentViewport = engine.currentViewport;
  58450. if (currentViewport) {
  58451. desiredWidth *= currentViewport.width;
  58452. desiredHeight *= currentViewport.height;
  58453. }
  58454. }
  58455. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  58456. if (!this._options.width) {
  58457. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  58458. }
  58459. if (!this._options.height) {
  58460. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  58461. }
  58462. }
  58463. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  58464. if (this._textures.length > 0) {
  58465. for (var i = 0; i < this._textures.length; i++) {
  58466. this._engine._releaseTexture(this._textures.data[i]);
  58467. }
  58468. this._textures.reset();
  58469. }
  58470. this.width = desiredWidth;
  58471. this.height = desiredHeight;
  58472. var textureSize = { width: this.width, height: this.height };
  58473. var textureOptions = {
  58474. generateMipMaps: false,
  58475. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  58476. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  58477. samplingMode: this.renderTargetSamplingMode,
  58478. type: this._textureType
  58479. };
  58480. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58481. if (this._reusable) {
  58482. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  58483. }
  58484. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  58485. this.onSizeChangedObservable.notifyObservers(this);
  58486. }
  58487. this._textures.forEach(function (texture) {
  58488. if (texture.samples !== _this.samples) {
  58489. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  58490. }
  58491. });
  58492. }
  58493. var target;
  58494. if (this._shareOutputWithPostProcess) {
  58495. target = this._shareOutputWithPostProcess.inputTexture;
  58496. }
  58497. else if (this._forcedOutputTexture) {
  58498. target = this._forcedOutputTexture;
  58499. this.width = this._forcedOutputTexture.width;
  58500. this.height = this._forcedOutputTexture.height;
  58501. }
  58502. else {
  58503. target = this.inputTexture;
  58504. }
  58505. // Bind the input of this post process to be used as the output of the previous post process.
  58506. if (this.enablePixelPerfectMode) {
  58507. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  58508. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  58509. }
  58510. else {
  58511. this._scaleRatio.copyFromFloats(1, 1);
  58512. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  58513. }
  58514. this.onActivateObservable.notifyObservers(camera);
  58515. // Clear
  58516. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  58517. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  58518. }
  58519. if (this._reusable) {
  58520. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  58521. }
  58522. };
  58523. Object.defineProperty(PostProcess.prototype, "isSupported", {
  58524. /**
  58525. * If the post process is supported.
  58526. */
  58527. get: function () {
  58528. return this._effect.isSupported;
  58529. },
  58530. enumerable: true,
  58531. configurable: true
  58532. });
  58533. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  58534. /**
  58535. * The aspect ratio of the output texture.
  58536. */
  58537. get: function () {
  58538. if (this._shareOutputWithPostProcess) {
  58539. return this._shareOutputWithPostProcess.aspectRatio;
  58540. }
  58541. if (this._forcedOutputTexture) {
  58542. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  58543. }
  58544. return this.width / this.height;
  58545. },
  58546. enumerable: true,
  58547. configurable: true
  58548. });
  58549. /**
  58550. * Get a value indicating if the post-process is ready to be used
  58551. * @returns true if the post-process is ready (shader is compiled)
  58552. */
  58553. PostProcess.prototype.isReady = function () {
  58554. return this._effect && this._effect.isReady();
  58555. };
  58556. /**
  58557. * Binds all textures and uniforms to the shader, this will be run on every pass.
  58558. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  58559. */
  58560. PostProcess.prototype.apply = function () {
  58561. // Check
  58562. if (!this._effect || !this._effect.isReady())
  58563. return null;
  58564. // States
  58565. this._engine.enableEffect(this._effect);
  58566. this._engine.setState(false);
  58567. this._engine.setDepthBuffer(false);
  58568. this._engine.setDepthWrite(false);
  58569. // Alpha
  58570. this._engine.setAlphaMode(this.alphaMode);
  58571. if (this.alphaConstants) {
  58572. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  58573. }
  58574. // Bind the output texture of the preivous post process as the input to this post process.
  58575. var source;
  58576. if (this._shareOutputWithPostProcess) {
  58577. source = this._shareOutputWithPostProcess.inputTexture;
  58578. }
  58579. else if (this._forcedOutputTexture) {
  58580. source = this._forcedOutputTexture;
  58581. }
  58582. else {
  58583. source = this.inputTexture;
  58584. }
  58585. this._effect._bindTexture("textureSampler", source);
  58586. // Parameters
  58587. this._effect.setVector2("scale", this._scaleRatio);
  58588. this.onApplyObservable.notifyObservers(this._effect);
  58589. return this._effect;
  58590. };
  58591. PostProcess.prototype._disposeTextures = function () {
  58592. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  58593. return;
  58594. }
  58595. if (this._textures.length > 0) {
  58596. for (var i = 0; i < this._textures.length; i++) {
  58597. this._engine._releaseTexture(this._textures.data[i]);
  58598. }
  58599. }
  58600. this._textures.dispose();
  58601. };
  58602. /**
  58603. * Disposes the post process.
  58604. * @param camera The camera to dispose the post process on.
  58605. */
  58606. PostProcess.prototype.dispose = function (camera) {
  58607. camera = camera || this._camera;
  58608. this._disposeTextures();
  58609. if (this._scene) {
  58610. var index_1 = this._scene.postProcesses.indexOf(this);
  58611. if (index_1 !== -1) {
  58612. this._scene.postProcesses.splice(index_1, 1);
  58613. }
  58614. }
  58615. else {
  58616. var index_2 = this._engine.postProcesses.indexOf(this);
  58617. if (index_2 !== -1) {
  58618. this._engine.postProcesses.splice(index_2, 1);
  58619. }
  58620. }
  58621. if (!camera) {
  58622. return;
  58623. }
  58624. camera.detachPostProcess(this);
  58625. var index = camera._postProcesses.indexOf(this);
  58626. if (index === 0 && camera._postProcesses.length > 0) {
  58627. this._camera._postProcesses[0].markTextureDirty();
  58628. }
  58629. this.onActivateObservable.clear();
  58630. this.onAfterRenderObservable.clear();
  58631. this.onApplyObservable.clear();
  58632. this.onBeforeRenderObservable.clear();
  58633. this.onSizeChangedObservable.clear();
  58634. };
  58635. return PostProcess;
  58636. }());
  58637. BABYLON.PostProcess = PostProcess;
  58638. })(BABYLON || (BABYLON = {}));
  58639. //# sourceMappingURL=babylon.postProcess.js.map
  58640. var BABYLON;
  58641. (function (BABYLON) {
  58642. var PassPostProcess = /** @class */ (function (_super) {
  58643. __extends(PassPostProcess, _super);
  58644. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  58645. if (camera === void 0) { camera = null; }
  58646. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58647. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  58648. }
  58649. return PassPostProcess;
  58650. }(BABYLON.PostProcess));
  58651. BABYLON.PassPostProcess = PassPostProcess;
  58652. })(BABYLON || (BABYLON = {}));
  58653. //# sourceMappingURL=babylon.passPostProcess.js.map
  58654. var __assign = (this && this.__assign) || Object.assign || function(t) {
  58655. for (var s, i = 1, n = arguments.length; i < n; i++) {
  58656. s = arguments[i];
  58657. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  58658. t[p] = s[p];
  58659. }
  58660. return t;
  58661. };
  58662. var BABYLON;
  58663. (function (BABYLON) {
  58664. /**
  58665. * Default implementation of @see IShadowGenerator.
  58666. * This is the main object responsible of generating shadows in the framework.
  58667. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  58668. */
  58669. var ShadowGenerator = /** @class */ (function () {
  58670. /**
  58671. * Creates a ShadowGenerator object.
  58672. * A ShadowGenerator is the required tool to use the shadows.
  58673. * Each light casting shadows needs to use its own ShadowGenerator.
  58674. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  58675. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  58676. * @param light The light object generating the shadows.
  58677. * @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.
  58678. */
  58679. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  58680. this._bias = 0.00005;
  58681. this._blurBoxOffset = 1;
  58682. this._blurScale = 2;
  58683. this._blurKernel = 1;
  58684. this._useKernelBlur = false;
  58685. this._filter = ShadowGenerator.FILTER_NONE;
  58686. this._darkness = 0;
  58687. this._transparencyShadow = false;
  58688. /**
  58689. * Controls the extent to which the shadows fade out at the edge of the frustum
  58690. * Used only by directionals and spots
  58691. */
  58692. this.frustumEdgeFalloff = 0;
  58693. /**
  58694. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  58695. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  58696. * It might on the other hand introduce peter panning.
  58697. */
  58698. this.forceBackFacesOnly = false;
  58699. this._lightDirection = BABYLON.Vector3.Zero();
  58700. this._viewMatrix = BABYLON.Matrix.Zero();
  58701. this._projectionMatrix = BABYLON.Matrix.Zero();
  58702. this._transformMatrix = BABYLON.Matrix.Zero();
  58703. this._currentFaceIndex = 0;
  58704. this._currentFaceIndexCache = 0;
  58705. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  58706. this._mapSize = mapSize;
  58707. this._light = light;
  58708. this._scene = light.getScene();
  58709. light._shadowGenerator = this;
  58710. // Texture type fallback from float to int if not supported.
  58711. var caps = this._scene.getEngine().getCaps();
  58712. if (!useFullFloatFirst) {
  58713. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58714. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58715. }
  58716. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58717. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58718. }
  58719. else {
  58720. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58721. }
  58722. }
  58723. else {
  58724. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  58725. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  58726. }
  58727. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  58728. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58729. }
  58730. else {
  58731. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  58732. }
  58733. }
  58734. this._initializeGenerator();
  58735. }
  58736. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  58737. /**
  58738. * Shadow generator mode None: no filtering applied.
  58739. */
  58740. get: function () {
  58741. return ShadowGenerator._FILTER_NONE;
  58742. },
  58743. enumerable: true,
  58744. configurable: true
  58745. });
  58746. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  58747. /**
  58748. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  58749. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  58750. */
  58751. get: function () {
  58752. return ShadowGenerator._FILTER_POISSONSAMPLING;
  58753. },
  58754. enumerable: true,
  58755. configurable: true
  58756. });
  58757. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  58758. /**
  58759. * Shadow generator mode ESM: Exponential Shadow Mapping.
  58760. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58761. */
  58762. get: function () {
  58763. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  58764. },
  58765. enumerable: true,
  58766. configurable: true
  58767. });
  58768. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  58769. /**
  58770. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  58771. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58772. */
  58773. get: function () {
  58774. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  58775. },
  58776. enumerable: true,
  58777. configurable: true
  58778. });
  58779. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  58780. /**
  58781. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  58782. * edge artifacts on steep falloff.
  58783. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58784. */
  58785. get: function () {
  58786. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  58787. },
  58788. enumerable: true,
  58789. configurable: true
  58790. });
  58791. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  58792. /**
  58793. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  58794. * edge artifacts on steep falloff.
  58795. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  58796. */
  58797. get: function () {
  58798. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  58799. },
  58800. enumerable: true,
  58801. configurable: true
  58802. });
  58803. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  58804. /**
  58805. * Gets the bias: offset applied on the depth preventing acnea.
  58806. */
  58807. get: function () {
  58808. return this._bias;
  58809. },
  58810. /**
  58811. * Sets the bias: offset applied on the depth preventing acnea.
  58812. */
  58813. set: function (bias) {
  58814. this._bias = bias;
  58815. },
  58816. enumerable: true,
  58817. configurable: true
  58818. });
  58819. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  58820. /**
  58821. * Gets the blur box offset: offset applied during the blur pass.
  58822. * Only usefull if useKernelBlur = false
  58823. */
  58824. get: function () {
  58825. return this._blurBoxOffset;
  58826. },
  58827. /**
  58828. * Sets the blur box offset: offset applied during the blur pass.
  58829. * Only usefull if useKernelBlur = false
  58830. */
  58831. set: function (value) {
  58832. if (this._blurBoxOffset === value) {
  58833. return;
  58834. }
  58835. this._blurBoxOffset = value;
  58836. this._disposeBlurPostProcesses();
  58837. },
  58838. enumerable: true,
  58839. configurable: true
  58840. });
  58841. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  58842. /**
  58843. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  58844. * 2 means half of the size.
  58845. */
  58846. get: function () {
  58847. return this._blurScale;
  58848. },
  58849. /**
  58850. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  58851. * 2 means half of the size.
  58852. */
  58853. set: function (value) {
  58854. if (this._blurScale === value) {
  58855. return;
  58856. }
  58857. this._blurScale = value;
  58858. this._disposeBlurPostProcesses();
  58859. },
  58860. enumerable: true,
  58861. configurable: true
  58862. });
  58863. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  58864. /**
  58865. * Gets the blur kernel: kernel size of the blur pass.
  58866. * Only usefull if useKernelBlur = true
  58867. */
  58868. get: function () {
  58869. return this._blurKernel;
  58870. },
  58871. /**
  58872. * Sets the blur kernel: kernel size of the blur pass.
  58873. * Only usefull if useKernelBlur = true
  58874. */
  58875. set: function (value) {
  58876. if (this._blurKernel === value) {
  58877. return;
  58878. }
  58879. this._blurKernel = value;
  58880. this._disposeBlurPostProcesses();
  58881. },
  58882. enumerable: true,
  58883. configurable: true
  58884. });
  58885. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  58886. /**
  58887. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  58888. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58889. */
  58890. get: function () {
  58891. return this._useKernelBlur;
  58892. },
  58893. /**
  58894. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  58895. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  58896. */
  58897. set: function (value) {
  58898. if (this._useKernelBlur === value) {
  58899. return;
  58900. }
  58901. this._useKernelBlur = value;
  58902. this._disposeBlurPostProcesses();
  58903. },
  58904. enumerable: true,
  58905. configurable: true
  58906. });
  58907. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  58908. /**
  58909. * Gets the depth scale used in ESM mode.
  58910. */
  58911. get: function () {
  58912. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  58913. },
  58914. /**
  58915. * Sets the depth scale used in ESM mode.
  58916. * This can override the scale stored on the light.
  58917. */
  58918. set: function (value) {
  58919. this._depthScale = value;
  58920. },
  58921. enumerable: true,
  58922. configurable: true
  58923. });
  58924. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  58925. /**
  58926. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  58927. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58928. */
  58929. get: function () {
  58930. return this._filter;
  58931. },
  58932. /**
  58933. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  58934. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  58935. */
  58936. set: function (value) {
  58937. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  58938. if (this._light.needCube()) {
  58939. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  58940. this.useExponentialShadowMap = true;
  58941. return;
  58942. }
  58943. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  58944. this.useCloseExponentialShadowMap = true;
  58945. return;
  58946. }
  58947. }
  58948. if (this._filter === value) {
  58949. return;
  58950. }
  58951. this._filter = value;
  58952. this._disposeBlurPostProcesses();
  58953. this._applyFilterValues();
  58954. this._light._markMeshesAsLightDirty();
  58955. },
  58956. enumerable: true,
  58957. configurable: true
  58958. });
  58959. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  58960. /**
  58961. * Gets if the current filter is set to Poisson Sampling aka PCF.
  58962. */
  58963. get: function () {
  58964. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  58965. },
  58966. /**
  58967. * Sets the current filter to Poisson Sampling aka PCF.
  58968. */
  58969. set: function (value) {
  58970. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  58971. return;
  58972. }
  58973. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  58974. },
  58975. enumerable: true,
  58976. configurable: true
  58977. });
  58978. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  58979. /**
  58980. * Gets if the current filter is set to VSM.
  58981. * DEPRECATED. Should use useExponentialShadowMap instead.
  58982. */
  58983. get: function () {
  58984. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58985. return this.useExponentialShadowMap;
  58986. },
  58987. /**
  58988. * Sets the current filter is to VSM.
  58989. * DEPRECATED. Should use useExponentialShadowMap instead.
  58990. */
  58991. set: function (value) {
  58992. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  58993. this.useExponentialShadowMap = value;
  58994. },
  58995. enumerable: true,
  58996. configurable: true
  58997. });
  58998. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  58999. /**
  59000. * Gets if the current filter is set to blurred VSM.
  59001. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59002. */
  59003. get: function () {
  59004. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59005. return this.useBlurExponentialShadowMap;
  59006. },
  59007. /**
  59008. * Sets the current filter is to blurred VSM.
  59009. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59010. */
  59011. set: function (value) {
  59012. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59013. this.useBlurExponentialShadowMap = value;
  59014. },
  59015. enumerable: true,
  59016. configurable: true
  59017. });
  59018. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59019. /**
  59020. * Gets if the current filter is set to ESM.
  59021. */
  59022. get: function () {
  59023. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59024. },
  59025. /**
  59026. * Sets the current filter is to ESM.
  59027. */
  59028. set: function (value) {
  59029. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59030. return;
  59031. }
  59032. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59033. },
  59034. enumerable: true,
  59035. configurable: true
  59036. });
  59037. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59038. /**
  59039. * Gets if the current filter is set to filtered ESM.
  59040. */
  59041. get: function () {
  59042. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59043. },
  59044. /**
  59045. * Gets if the current filter is set to filtered ESM.
  59046. */
  59047. set: function (value) {
  59048. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59049. return;
  59050. }
  59051. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59052. },
  59053. enumerable: true,
  59054. configurable: true
  59055. });
  59056. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59057. /**
  59058. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59059. * exponential to prevent steep falloff artifacts).
  59060. */
  59061. get: function () {
  59062. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59063. },
  59064. /**
  59065. * Sets the current filter to "close ESM" (using the inverse of the
  59066. * exponential to prevent steep falloff artifacts).
  59067. */
  59068. set: function (value) {
  59069. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59070. return;
  59071. }
  59072. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59073. },
  59074. enumerable: true,
  59075. configurable: true
  59076. });
  59077. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59078. /**
  59079. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59080. * exponential to prevent steep falloff artifacts).
  59081. */
  59082. get: function () {
  59083. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59084. },
  59085. /**
  59086. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59087. * exponential to prevent steep falloff artifacts).
  59088. */
  59089. set: function (value) {
  59090. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59091. return;
  59092. }
  59093. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59094. },
  59095. enumerable: true,
  59096. configurable: true
  59097. });
  59098. /**
  59099. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59100. * 0 means strongest and 1 would means no shadow.
  59101. * @returns the darkness.
  59102. */
  59103. ShadowGenerator.prototype.getDarkness = function () {
  59104. return this._darkness;
  59105. };
  59106. /**
  59107. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59108. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59109. * @returns the shadow generator allowing fluent coding.
  59110. */
  59111. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59112. if (darkness >= 1.0)
  59113. this._darkness = 1.0;
  59114. else if (darkness <= 0.0)
  59115. this._darkness = 0.0;
  59116. else
  59117. this._darkness = darkness;
  59118. return this;
  59119. };
  59120. /**
  59121. * Sets the ability to have transparent shadow (boolean).
  59122. * @param transparent True if transparent else False
  59123. * @returns the shadow generator allowing fluent coding
  59124. */
  59125. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59126. this._transparencyShadow = transparent;
  59127. return this;
  59128. };
  59129. /**
  59130. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59131. * @returns The render target texture if present otherwise, null
  59132. */
  59133. ShadowGenerator.prototype.getShadowMap = function () {
  59134. return this._shadowMap;
  59135. };
  59136. /**
  59137. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59138. * @returns The render target texture if the shadow map is present otherwise, null
  59139. */
  59140. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59141. if (this._shadowMap2) {
  59142. return this._shadowMap2;
  59143. }
  59144. return this._shadowMap;
  59145. };
  59146. /**
  59147. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59148. * @param mesh Mesh to add
  59149. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59150. * @returns the Shadow Generator itself
  59151. */
  59152. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59153. if (includeDescendants === void 0) { includeDescendants = true; }
  59154. if (!this._shadowMap) {
  59155. return this;
  59156. }
  59157. if (!this._shadowMap.renderList) {
  59158. this._shadowMap.renderList = [];
  59159. }
  59160. this._shadowMap.renderList.push(mesh);
  59161. if (includeDescendants) {
  59162. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59163. }
  59164. return this;
  59165. var _a;
  59166. };
  59167. /**
  59168. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59169. * @param mesh Mesh to remove
  59170. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59171. * @returns the Shadow Generator itself
  59172. */
  59173. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59174. if (includeDescendants === void 0) { includeDescendants = true; }
  59175. if (!this._shadowMap || !this._shadowMap.renderList) {
  59176. return this;
  59177. }
  59178. var index = this._shadowMap.renderList.indexOf(mesh);
  59179. if (index !== -1) {
  59180. this._shadowMap.renderList.splice(index, 1);
  59181. }
  59182. if (includeDescendants) {
  59183. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59184. var child = _a[_i];
  59185. this.removeShadowCaster(child);
  59186. }
  59187. }
  59188. return this;
  59189. };
  59190. /**
  59191. * Returns the associated light object.
  59192. * @returns the light generating the shadow
  59193. */
  59194. ShadowGenerator.prototype.getLight = function () {
  59195. return this._light;
  59196. };
  59197. ShadowGenerator.prototype._initializeGenerator = function () {
  59198. this._light._markMeshesAsLightDirty();
  59199. this._initializeShadowMap();
  59200. };
  59201. ShadowGenerator.prototype._initializeShadowMap = function () {
  59202. var _this = this;
  59203. // Render target
  59204. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59205. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59206. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59207. this._shadowMap.anisotropicFilteringLevel = 1;
  59208. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59209. this._shadowMap.renderParticles = false;
  59210. this._shadowMap.ignoreCameraViewport = true;
  59211. // Record Face Index before render.
  59212. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59213. _this._currentFaceIndex = faceIndex;
  59214. });
  59215. // Custom render function.
  59216. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59217. // Blur if required afer render.
  59218. this._shadowMap.onAfterUnbindObservable.add(function () {
  59219. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59220. return;
  59221. }
  59222. var shadowMap = _this.getShadowMapForRendering();
  59223. if (shadowMap) {
  59224. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59225. }
  59226. });
  59227. // Clear according to the chosen filter.
  59228. this._shadowMap.onClearObservable.add(function (engine) {
  59229. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59230. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59231. }
  59232. else {
  59233. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59234. }
  59235. });
  59236. };
  59237. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59238. var _this = this;
  59239. var engine = this._scene.getEngine();
  59240. var targetSize = this._mapSize / this.blurScale;
  59241. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59242. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59243. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59244. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59245. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59246. }
  59247. if (this.useKernelBlur) {
  59248. 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);
  59249. this._kernelBlurXPostprocess.width = targetSize;
  59250. this._kernelBlurXPostprocess.height = targetSize;
  59251. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59252. effect.setTexture("textureSampler", _this._shadowMap);
  59253. });
  59254. 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);
  59255. this._kernelBlurXPostprocess.autoClear = false;
  59256. this._kernelBlurYPostprocess.autoClear = false;
  59257. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59258. this._kernelBlurXPostprocess.packedFloat = true;
  59259. this._kernelBlurYPostprocess.packedFloat = true;
  59260. }
  59261. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59262. }
  59263. else {
  59264. 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);
  59265. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59266. effect.setFloat2("screenSize", targetSize, targetSize);
  59267. effect.setTexture("textureSampler", _this._shadowMap);
  59268. });
  59269. this._boxBlurPostprocess.autoClear = false;
  59270. this._blurPostProcesses = [this._boxBlurPostprocess];
  59271. }
  59272. };
  59273. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59274. var index;
  59275. var engine = this._scene.getEngine();
  59276. if (depthOnlySubMeshes.length) {
  59277. engine.setColorWrite(false);
  59278. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59279. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59280. }
  59281. engine.setColorWrite(true);
  59282. }
  59283. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59284. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59285. }
  59286. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59287. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59288. }
  59289. if (this._transparencyShadow) {
  59290. for (index = 0; index < transparentSubMeshes.length; index++) {
  59291. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59292. }
  59293. }
  59294. };
  59295. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59296. var _this = this;
  59297. var mesh = subMesh.getRenderingMesh();
  59298. var scene = this._scene;
  59299. var engine = scene.getEngine();
  59300. var material = subMesh.getMaterial();
  59301. if (!material) {
  59302. return;
  59303. }
  59304. // Culling
  59305. engine.setState(material.backFaceCulling);
  59306. // Managing instances
  59307. var batch = mesh._getInstancesRenderList(subMesh._id);
  59308. if (batch.mustReturn) {
  59309. return;
  59310. }
  59311. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59312. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59313. engine.enableEffect(this._effect);
  59314. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59315. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59316. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59317. this._effect.setVector3("lightPosition", this.getLight().position);
  59318. if (scene.activeCamera) {
  59319. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59320. }
  59321. // Alpha test
  59322. if (material && material.needAlphaTesting()) {
  59323. var alphaTexture = material.getAlphaTestTexture();
  59324. if (alphaTexture) {
  59325. this._effect.setTexture("diffuseSampler", alphaTexture);
  59326. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59327. }
  59328. }
  59329. // Bones
  59330. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59331. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59332. }
  59333. if (this.forceBackFacesOnly) {
  59334. engine.setState(true, 0, false, true);
  59335. }
  59336. // Draw
  59337. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59338. if (this.forceBackFacesOnly) {
  59339. engine.setState(true, 0, false, false);
  59340. }
  59341. }
  59342. else {
  59343. // Need to reset refresh rate of the shadowMap
  59344. if (this._shadowMap) {
  59345. this._shadowMap.resetRefreshCounter();
  59346. }
  59347. }
  59348. };
  59349. ShadowGenerator.prototype._applyFilterValues = function () {
  59350. if (!this._shadowMap) {
  59351. return;
  59352. }
  59353. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59354. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59355. }
  59356. else {
  59357. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59358. }
  59359. };
  59360. /**
  59361. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59362. * @param onCompiled Callback triggered at the and of the effects compilation
  59363. * @param options Sets of optional options forcing the compilation with different modes
  59364. */
  59365. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59366. var _this = this;
  59367. var localOptions = __assign({ useInstances: false }, options);
  59368. var shadowMap = this.getShadowMap();
  59369. if (!shadowMap) {
  59370. if (onCompiled) {
  59371. onCompiled(this);
  59372. }
  59373. return;
  59374. }
  59375. var renderList = shadowMap.renderList;
  59376. if (!renderList) {
  59377. if (onCompiled) {
  59378. onCompiled(this);
  59379. }
  59380. return;
  59381. }
  59382. var subMeshes = new Array();
  59383. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59384. var mesh = renderList_1[_i];
  59385. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59386. }
  59387. if (subMeshes.length === 0) {
  59388. if (onCompiled) {
  59389. onCompiled(this);
  59390. }
  59391. return;
  59392. }
  59393. var currentIndex = 0;
  59394. var checkReady = function () {
  59395. if (!_this._scene || !_this._scene.getEngine()) {
  59396. return;
  59397. }
  59398. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59399. currentIndex++;
  59400. if (currentIndex >= subMeshes.length) {
  59401. if (onCompiled) {
  59402. onCompiled(_this);
  59403. }
  59404. return;
  59405. }
  59406. }
  59407. setTimeout(checkReady, 16);
  59408. };
  59409. checkReady();
  59410. };
  59411. /**
  59412. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59413. * @param options Sets of optional options forcing the compilation with different modes
  59414. * @returns A promise that resolves when the compilation completes
  59415. */
  59416. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59417. var _this = this;
  59418. return new Promise(function (resolve) {
  59419. _this.forceCompilation(function () {
  59420. resolve();
  59421. }, options);
  59422. });
  59423. };
  59424. /**
  59425. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59426. * @param subMesh The submesh we want to render in the shadow map
  59427. * @param useInstances Defines wether will draw in the map using instances
  59428. * @returns true if ready otherwise, false
  59429. */
  59430. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59431. var defines = [];
  59432. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59433. defines.push("#define FLOAT");
  59434. }
  59435. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59436. defines.push("#define ESM");
  59437. }
  59438. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59439. var mesh = subMesh.getMesh();
  59440. var material = subMesh.getMaterial();
  59441. // Alpha test
  59442. if (material && material.needAlphaTesting()) {
  59443. var alphaTexture = material.getAlphaTestTexture();
  59444. if (alphaTexture) {
  59445. defines.push("#define ALPHATEST");
  59446. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59447. attribs.push(BABYLON.VertexBuffer.UVKind);
  59448. defines.push("#define UV1");
  59449. }
  59450. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59451. if (alphaTexture.coordinatesIndex === 1) {
  59452. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59453. defines.push("#define UV2");
  59454. }
  59455. }
  59456. }
  59457. }
  59458. // Bones
  59459. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59460. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59461. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59462. if (mesh.numBoneInfluencers > 4) {
  59463. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59464. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59465. }
  59466. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59467. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59468. }
  59469. else {
  59470. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59471. }
  59472. // Instances
  59473. if (useInstances) {
  59474. defines.push("#define INSTANCES");
  59475. attribs.push("world0");
  59476. attribs.push("world1");
  59477. attribs.push("world2");
  59478. attribs.push("world3");
  59479. }
  59480. // Get correct effect
  59481. var join = defines.join("\n");
  59482. if (this._cachedDefines !== join) {
  59483. this._cachedDefines = join;
  59484. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  59485. }
  59486. if (!this._effect.isReady()) {
  59487. return false;
  59488. }
  59489. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59490. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  59491. this._initializeBlurRTTAndPostProcesses();
  59492. }
  59493. }
  59494. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  59495. return false;
  59496. }
  59497. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  59498. return false;
  59499. }
  59500. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  59501. return false;
  59502. }
  59503. return true;
  59504. };
  59505. /**
  59506. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  59507. * @param defines Defines of the material we want to update
  59508. * @param lightIndex Index of the light in the enabled light list of the material
  59509. */
  59510. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  59511. var scene = this._scene;
  59512. var light = this._light;
  59513. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59514. return;
  59515. }
  59516. defines["SHADOW" + lightIndex] = true;
  59517. if (this.usePoissonSampling) {
  59518. defines["SHADOWPCF" + lightIndex] = true;
  59519. }
  59520. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59521. defines["SHADOWESM" + lightIndex] = true;
  59522. }
  59523. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  59524. defines["SHADOWCLOSEESM" + lightIndex] = true;
  59525. }
  59526. if (light.needCube()) {
  59527. defines["SHADOWCUBE" + lightIndex] = true;
  59528. }
  59529. };
  59530. /**
  59531. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  59532. * defined in the generator but impacting the effect).
  59533. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  59534. * @param effect The effect we are binfing the information for
  59535. */
  59536. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  59537. var light = this._light;
  59538. var scene = this._scene;
  59539. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  59540. return;
  59541. }
  59542. var camera = scene.activeCamera;
  59543. if (!camera) {
  59544. return;
  59545. }
  59546. var shadowMap = this.getShadowMap();
  59547. if (!shadowMap) {
  59548. return;
  59549. }
  59550. if (!light.needCube()) {
  59551. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  59552. }
  59553. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  59554. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  59555. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  59556. };
  59557. /**
  59558. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  59559. * (eq to shadow prjection matrix * light transform matrix)
  59560. * @returns The transform matrix used to create the shadow map
  59561. */
  59562. ShadowGenerator.prototype.getTransformMatrix = function () {
  59563. var scene = this._scene;
  59564. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  59565. return this._transformMatrix;
  59566. }
  59567. this._currentRenderID = scene.getRenderId();
  59568. this._currentFaceIndexCache = this._currentFaceIndex;
  59569. var lightPosition = this._light.position;
  59570. if (this._light.computeTransformedInformation()) {
  59571. lightPosition = this._light.transformedPosition;
  59572. }
  59573. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  59574. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  59575. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  59576. }
  59577. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  59578. this._cachedPosition = lightPosition.clone();
  59579. this._cachedDirection = this._lightDirection.clone();
  59580. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  59581. var shadowMap = this.getShadowMap();
  59582. if (shadowMap) {
  59583. var renderList = shadowMap.renderList;
  59584. if (renderList) {
  59585. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  59586. }
  59587. }
  59588. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  59589. }
  59590. return this._transformMatrix;
  59591. };
  59592. /**
  59593. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  59594. * Cube and 2D textures for instance.
  59595. */
  59596. ShadowGenerator.prototype.recreateShadowMap = function () {
  59597. var shadowMap = this._shadowMap;
  59598. if (!shadowMap) {
  59599. return;
  59600. }
  59601. // Track render list.
  59602. var renderList = shadowMap.renderList;
  59603. // Clean up existing data.
  59604. this._disposeRTTandPostProcesses();
  59605. // Reinitializes.
  59606. this._initializeGenerator();
  59607. // Reaffect the filter to ensure a correct fallback if necessary.
  59608. this.filter = this.filter;
  59609. // Reaffect the filter.
  59610. this._applyFilterValues();
  59611. // Reaffect Render List.
  59612. this._shadowMap.renderList = renderList;
  59613. };
  59614. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  59615. if (this._shadowMap2) {
  59616. this._shadowMap2.dispose();
  59617. this._shadowMap2 = null;
  59618. }
  59619. if (this._boxBlurPostprocess) {
  59620. this._boxBlurPostprocess.dispose();
  59621. this._boxBlurPostprocess = null;
  59622. }
  59623. if (this._kernelBlurXPostprocess) {
  59624. this._kernelBlurXPostprocess.dispose();
  59625. this._kernelBlurXPostprocess = null;
  59626. }
  59627. if (this._kernelBlurYPostprocess) {
  59628. this._kernelBlurYPostprocess.dispose();
  59629. this._kernelBlurYPostprocess = null;
  59630. }
  59631. this._blurPostProcesses = [];
  59632. };
  59633. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  59634. if (this._shadowMap) {
  59635. this._shadowMap.dispose();
  59636. this._shadowMap = null;
  59637. }
  59638. this._disposeBlurPostProcesses();
  59639. };
  59640. /**
  59641. * Disposes the ShadowGenerator.
  59642. * Returns nothing.
  59643. */
  59644. ShadowGenerator.prototype.dispose = function () {
  59645. this._disposeRTTandPostProcesses();
  59646. if (this._light) {
  59647. this._light._shadowGenerator = null;
  59648. this._light._markMeshesAsLightDirty();
  59649. }
  59650. };
  59651. /**
  59652. * Serializes the shadow generator setup to a json object.
  59653. * @returns The serialized JSON object
  59654. */
  59655. ShadowGenerator.prototype.serialize = function () {
  59656. var serializationObject = {};
  59657. var shadowMap = this.getShadowMap();
  59658. if (!shadowMap) {
  59659. return serializationObject;
  59660. }
  59661. serializationObject.lightId = this._light.id;
  59662. serializationObject.mapSize = shadowMap.getRenderSize();
  59663. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  59664. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  59665. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59666. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  59667. serializationObject.usePoissonSampling = this.usePoissonSampling;
  59668. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  59669. serializationObject.depthScale = this.depthScale;
  59670. serializationObject.darkness = this.getDarkness();
  59671. serializationObject.blurBoxOffset = this.blurBoxOffset;
  59672. serializationObject.blurKernel = this.blurKernel;
  59673. serializationObject.blurScale = this.blurScale;
  59674. serializationObject.useKernelBlur = this.useKernelBlur;
  59675. serializationObject.transparencyShadow = this._transparencyShadow;
  59676. serializationObject.renderList = [];
  59677. if (shadowMap.renderList) {
  59678. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  59679. var mesh = shadowMap.renderList[meshIndex];
  59680. serializationObject.renderList.push(mesh.id);
  59681. }
  59682. }
  59683. return serializationObject;
  59684. };
  59685. /**
  59686. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  59687. * @param parsedShadowGenerator The JSON object to parse
  59688. * @param scene The scene to create the shadow map for
  59689. * @returns The parsed shadow generator
  59690. */
  59691. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  59692. //casting to point light, as light is missing the position attr and typescript complains.
  59693. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  59694. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  59695. var shadowMap = shadowGenerator.getShadowMap();
  59696. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  59697. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  59698. meshes.forEach(function (mesh) {
  59699. if (!shadowMap) {
  59700. return;
  59701. }
  59702. if (!shadowMap.renderList) {
  59703. shadowMap.renderList = [];
  59704. }
  59705. shadowMap.renderList.push(mesh);
  59706. });
  59707. }
  59708. if (parsedShadowGenerator.usePoissonSampling) {
  59709. shadowGenerator.usePoissonSampling = true;
  59710. }
  59711. else if (parsedShadowGenerator.useExponentialShadowMap) {
  59712. shadowGenerator.useExponentialShadowMap = true;
  59713. }
  59714. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  59715. shadowGenerator.useBlurExponentialShadowMap = true;
  59716. }
  59717. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  59718. shadowGenerator.useCloseExponentialShadowMap = true;
  59719. }
  59720. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  59721. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  59722. }
  59723. else if (parsedShadowGenerator.useVarianceShadowMap) {
  59724. shadowGenerator.useExponentialShadowMap = true;
  59725. }
  59726. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  59727. shadowGenerator.useBlurExponentialShadowMap = true;
  59728. }
  59729. if (parsedShadowGenerator.depthScale) {
  59730. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  59731. }
  59732. if (parsedShadowGenerator.blurScale) {
  59733. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  59734. }
  59735. if (parsedShadowGenerator.blurBoxOffset) {
  59736. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  59737. }
  59738. if (parsedShadowGenerator.useKernelBlur) {
  59739. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  59740. }
  59741. if (parsedShadowGenerator.blurKernel) {
  59742. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  59743. }
  59744. if (parsedShadowGenerator.bias !== undefined) {
  59745. shadowGenerator.bias = parsedShadowGenerator.bias;
  59746. }
  59747. if (parsedShadowGenerator.darkness) {
  59748. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  59749. }
  59750. if (parsedShadowGenerator.transparencyShadow) {
  59751. shadowGenerator.setTransparencyShadow(true);
  59752. }
  59753. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  59754. return shadowGenerator;
  59755. };
  59756. ShadowGenerator._FILTER_NONE = 0;
  59757. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  59758. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  59759. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  59760. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  59761. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  59762. return ShadowGenerator;
  59763. }());
  59764. BABYLON.ShadowGenerator = ShadowGenerator;
  59765. })(BABYLON || (BABYLON = {}));
  59766. //# sourceMappingURL=babylon.shadowGenerator.js.map
  59767. var BABYLON;
  59768. (function (BABYLON) {
  59769. var DefaultLoadingScreen = /** @class */ (function () {
  59770. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  59771. if (_loadingText === void 0) { _loadingText = ""; }
  59772. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  59773. var _this = this;
  59774. this._renderingCanvas = _renderingCanvas;
  59775. this._loadingText = _loadingText;
  59776. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  59777. // Resize
  59778. this._resizeLoadingUI = function () {
  59779. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  59780. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  59781. if (!_this._loadingDiv) {
  59782. return;
  59783. }
  59784. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  59785. _this._loadingDiv.style.left = canvasRect.left + "px";
  59786. _this._loadingDiv.style.top = canvasRect.top + "px";
  59787. _this._loadingDiv.style.width = canvasRect.width + "px";
  59788. _this._loadingDiv.style.height = canvasRect.height + "px";
  59789. };
  59790. }
  59791. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  59792. if (this._loadingDiv) {
  59793. // Do not add a loading screen if there is already one
  59794. return;
  59795. }
  59796. this._loadingDiv = document.createElement("div");
  59797. this._loadingDiv.id = "babylonjsLoadingDiv";
  59798. this._loadingDiv.style.opacity = "0";
  59799. this._loadingDiv.style.transition = "opacity 1.5s ease";
  59800. this._loadingDiv.style.pointerEvents = "none";
  59801. // Loading text
  59802. this._loadingTextDiv = document.createElement("div");
  59803. this._loadingTextDiv.style.position = "absolute";
  59804. this._loadingTextDiv.style.left = "0";
  59805. this._loadingTextDiv.style.top = "50%";
  59806. this._loadingTextDiv.style.marginTop = "80px";
  59807. this._loadingTextDiv.style.width = "100%";
  59808. this._loadingTextDiv.style.height = "20px";
  59809. this._loadingTextDiv.style.fontFamily = "Arial";
  59810. this._loadingTextDiv.style.fontSize = "14px";
  59811. this._loadingTextDiv.style.color = "white";
  59812. this._loadingTextDiv.style.textAlign = "center";
  59813. this._loadingTextDiv.innerHTML = "Loading";
  59814. this._loadingDiv.appendChild(this._loadingTextDiv);
  59815. //set the predefined text
  59816. this._loadingTextDiv.innerHTML = this._loadingText;
  59817. // Generating keyframes
  59818. var style = document.createElement('style');
  59819. style.type = 'text/css';
  59820. 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 }";
  59821. style.innerHTML = keyFrames;
  59822. document.getElementsByTagName('head')[0].appendChild(style);
  59823. // Loading img
  59824. var imgBack = new Image();
  59825. 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";
  59826. imgBack.style.position = "absolute";
  59827. imgBack.style.left = "50%";
  59828. imgBack.style.top = "50%";
  59829. imgBack.style.marginLeft = "-60px";
  59830. imgBack.style.marginTop = "-60px";
  59831. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  59832. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  59833. imgBack.style.transformOrigin = "50% 50%";
  59834. imgBack.style.webkitTransformOrigin = "50% 50%";
  59835. this._loadingDiv.appendChild(imgBack);
  59836. this._resizeLoadingUI();
  59837. window.addEventListener("resize", this._resizeLoadingUI);
  59838. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59839. document.body.appendChild(this._loadingDiv);
  59840. this._loadingDiv.style.opacity = "1";
  59841. };
  59842. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  59843. var _this = this;
  59844. if (!this._loadingDiv) {
  59845. return;
  59846. }
  59847. var onTransitionEnd = function () {
  59848. if (!_this._loadingDiv) {
  59849. return;
  59850. }
  59851. document.body.removeChild(_this._loadingDiv);
  59852. window.removeEventListener("resize", _this._resizeLoadingUI);
  59853. _this._loadingDiv = null;
  59854. };
  59855. this._loadingDiv.style.opacity = "0";
  59856. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  59857. };
  59858. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  59859. set: function (text) {
  59860. this._loadingText = text;
  59861. if (this._loadingTextDiv) {
  59862. this._loadingTextDiv.innerHTML = this._loadingText;
  59863. }
  59864. },
  59865. enumerable: true,
  59866. configurable: true
  59867. });
  59868. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  59869. get: function () {
  59870. return this._loadingDivBackgroundColor;
  59871. },
  59872. set: function (color) {
  59873. this._loadingDivBackgroundColor = color;
  59874. if (!this._loadingDiv) {
  59875. return;
  59876. }
  59877. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  59878. },
  59879. enumerable: true,
  59880. configurable: true
  59881. });
  59882. return DefaultLoadingScreen;
  59883. }());
  59884. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  59885. })(BABYLON || (BABYLON = {}));
  59886. //# sourceMappingURL=babylon.loadingScreen.js.map
  59887. var BABYLON;
  59888. (function (BABYLON) {
  59889. var SceneLoaderProgressEvent = /** @class */ (function () {
  59890. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  59891. this.lengthComputable = lengthComputable;
  59892. this.loaded = loaded;
  59893. this.total = total;
  59894. }
  59895. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  59896. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  59897. };
  59898. return SceneLoaderProgressEvent;
  59899. }());
  59900. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  59901. var SceneLoader = /** @class */ (function () {
  59902. function SceneLoader() {
  59903. }
  59904. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  59905. get: function () {
  59906. return 0;
  59907. },
  59908. enumerable: true,
  59909. configurable: true
  59910. });
  59911. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  59912. get: function () {
  59913. return 1;
  59914. },
  59915. enumerable: true,
  59916. configurable: true
  59917. });
  59918. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  59919. get: function () {
  59920. return 2;
  59921. },
  59922. enumerable: true,
  59923. configurable: true
  59924. });
  59925. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  59926. get: function () {
  59927. return 3;
  59928. },
  59929. enumerable: true,
  59930. configurable: true
  59931. });
  59932. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  59933. get: function () {
  59934. return SceneLoader._ForceFullSceneLoadingForIncremental;
  59935. },
  59936. set: function (value) {
  59937. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  59938. },
  59939. enumerable: true,
  59940. configurable: true
  59941. });
  59942. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  59943. get: function () {
  59944. return SceneLoader._ShowLoadingScreen;
  59945. },
  59946. set: function (value) {
  59947. SceneLoader._ShowLoadingScreen = value;
  59948. },
  59949. enumerable: true,
  59950. configurable: true
  59951. });
  59952. Object.defineProperty(SceneLoader, "loggingLevel", {
  59953. get: function () {
  59954. return SceneLoader._loggingLevel;
  59955. },
  59956. set: function (value) {
  59957. SceneLoader._loggingLevel = value;
  59958. },
  59959. enumerable: true,
  59960. configurable: true
  59961. });
  59962. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  59963. get: function () {
  59964. return SceneLoader._CleanBoneMatrixWeights;
  59965. },
  59966. set: function (value) {
  59967. SceneLoader._CleanBoneMatrixWeights = value;
  59968. },
  59969. enumerable: true,
  59970. configurable: true
  59971. });
  59972. SceneLoader._getDefaultPlugin = function () {
  59973. return SceneLoader._registeredPlugins[".babylon"];
  59974. };
  59975. SceneLoader._getPluginForExtension = function (extension) {
  59976. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  59977. if (registeredPlugin) {
  59978. return registeredPlugin;
  59979. }
  59980. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  59981. return SceneLoader._getDefaultPlugin();
  59982. };
  59983. SceneLoader._getPluginForDirectLoad = function (data) {
  59984. for (var extension in SceneLoader._registeredPlugins) {
  59985. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  59986. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  59987. return SceneLoader._registeredPlugins[extension];
  59988. }
  59989. }
  59990. return SceneLoader._getDefaultPlugin();
  59991. };
  59992. SceneLoader._getPluginForFilename = function (sceneFilename) {
  59993. if (sceneFilename.name) {
  59994. sceneFilename = sceneFilename.name;
  59995. }
  59996. var queryStringPosition = sceneFilename.indexOf("?");
  59997. if (queryStringPosition !== -1) {
  59998. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  59999. }
  60000. var dotPosition = sceneFilename.lastIndexOf(".");
  60001. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60002. return SceneLoader._getPluginForExtension(extension);
  60003. };
  60004. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60005. SceneLoader._getDirectLoad = function (sceneFilename) {
  60006. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60007. return sceneFilename.substr(5);
  60008. }
  60009. return null;
  60010. };
  60011. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60012. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60013. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60014. var plugin;
  60015. if (registeredPlugin.plugin.createPlugin) {
  60016. plugin = registeredPlugin.plugin.createPlugin();
  60017. }
  60018. else {
  60019. plugin = registeredPlugin.plugin;
  60020. }
  60021. var useArrayBuffer = registeredPlugin.isBinary;
  60022. var database;
  60023. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60024. var dataCallback = function (data, responseURL) {
  60025. if (scene.isDisposed) {
  60026. onError("Scene has been disposed");
  60027. return;
  60028. }
  60029. scene.database = database;
  60030. onSuccess(plugin, data, responseURL);
  60031. };
  60032. var request = null;
  60033. var pluginDisposed = false;
  60034. var onDisposeObservable = plugin.onDisposeObservable;
  60035. if (onDisposeObservable) {
  60036. onDisposeObservable.add(function () {
  60037. pluginDisposed = true;
  60038. if (request) {
  60039. request.abort();
  60040. request = null;
  60041. }
  60042. onDispose();
  60043. });
  60044. }
  60045. var manifestChecked = function () {
  60046. if (pluginDisposed) {
  60047. return;
  60048. }
  60049. var url = rootUrl + sceneFilename;
  60050. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60051. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60052. } : undefined, database, useArrayBuffer, function (request, exception) {
  60053. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60054. });
  60055. };
  60056. if (directLoad) {
  60057. dataCallback(directLoad);
  60058. return plugin;
  60059. }
  60060. if (rootUrl.indexOf("file:") === -1) {
  60061. if (scene.getEngine().enableOfflineSupport) {
  60062. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60063. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60064. }
  60065. else {
  60066. manifestChecked();
  60067. }
  60068. }
  60069. else {
  60070. var fileOrString = sceneFilename;
  60071. if (fileOrString.name) {
  60072. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60073. }
  60074. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60075. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60076. }
  60077. else {
  60078. onError("Unable to find file named " + sceneFilename);
  60079. }
  60080. }
  60081. return plugin;
  60082. };
  60083. // Public functions
  60084. SceneLoader.GetPluginForExtension = function (extension) {
  60085. return SceneLoader._getPluginForExtension(extension).plugin;
  60086. };
  60087. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60088. return !!SceneLoader._registeredPlugins[extension];
  60089. };
  60090. SceneLoader.RegisterPlugin = function (plugin) {
  60091. if (typeof plugin.extensions === "string") {
  60092. var extension = plugin.extensions;
  60093. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60094. plugin: plugin,
  60095. isBinary: false
  60096. };
  60097. }
  60098. else {
  60099. var extensions = plugin.extensions;
  60100. Object.keys(extensions).forEach(function (extension) {
  60101. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60102. plugin: plugin,
  60103. isBinary: extensions[extension].isBinary
  60104. };
  60105. });
  60106. }
  60107. };
  60108. /**
  60109. * Import meshes into a scene
  60110. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60111. * @param rootUrl a string that defines the root url for scene and resources
  60112. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60113. * @param scene the instance of BABYLON.Scene to append to
  60114. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60115. * @param onProgress a callback with a progress event for each file being loaded
  60116. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60117. * @param pluginExtension the extension used to determine the plugin
  60118. * @returns The loaded plugin
  60119. */
  60120. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60121. if (onSuccess === void 0) { onSuccess = null; }
  60122. if (onProgress === void 0) { onProgress = null; }
  60123. if (onError === void 0) { onError = null; }
  60124. if (pluginExtension === void 0) { pluginExtension = null; }
  60125. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60126. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60127. return null;
  60128. }
  60129. var loadingToken = {};
  60130. scene._addPendingData(loadingToken);
  60131. var disposeHandler = function () {
  60132. scene._removePendingData(loadingToken);
  60133. };
  60134. var errorHandler = function (message, exception) {
  60135. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60136. if (onError) {
  60137. onError(scene, errorMessage, exception);
  60138. }
  60139. else {
  60140. BABYLON.Tools.Error(errorMessage);
  60141. // should the exception be thrown?
  60142. }
  60143. disposeHandler();
  60144. };
  60145. var progressHandler = onProgress ? function (event) {
  60146. try {
  60147. onProgress(event);
  60148. }
  60149. catch (e) {
  60150. errorHandler("Error in onProgress callback", e);
  60151. }
  60152. } : undefined;
  60153. var successHandler = function (meshes, particleSystems, skeletons) {
  60154. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60155. if (onSuccess) {
  60156. try {
  60157. onSuccess(meshes, particleSystems, skeletons);
  60158. }
  60159. catch (e) {
  60160. errorHandler("Error in onSuccess callback", e);
  60161. }
  60162. }
  60163. scene._removePendingData(loadingToken);
  60164. };
  60165. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60166. if (plugin.rewriteRootURL) {
  60167. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60168. }
  60169. if (sceneFilename === "") {
  60170. if (sceneFilename === "") {
  60171. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60172. }
  60173. }
  60174. if (plugin.importMesh) {
  60175. var syncedPlugin = plugin;
  60176. var meshes = new Array();
  60177. var particleSystems = new Array();
  60178. var skeletons = new Array();
  60179. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60180. return;
  60181. }
  60182. scene.loadingPluginName = plugin.name;
  60183. successHandler(meshes, particleSystems, skeletons);
  60184. }
  60185. else {
  60186. var asyncedPlugin = plugin;
  60187. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60188. scene.loadingPluginName = plugin.name;
  60189. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60190. }).catch(function (error) {
  60191. errorHandler(error.message, error);
  60192. });
  60193. }
  60194. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60195. };
  60196. /**
  60197. * Import meshes into a scene
  60198. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60199. * @param rootUrl a string that defines the root url for scene and resources
  60200. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60201. * @param scene the instance of BABYLON.Scene to append to
  60202. * @param onProgress a callback with a progress event for each file being loaded
  60203. * @param pluginExtension the extension used to determine the plugin
  60204. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60205. */
  60206. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60207. if (onProgress === void 0) { onProgress = null; }
  60208. if (pluginExtension === void 0) { pluginExtension = null; }
  60209. return new Promise(function (resolve, reject) {
  60210. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60211. resolve({
  60212. meshes: meshes,
  60213. particleSystems: particleSystems,
  60214. skeletons: skeletons
  60215. });
  60216. }, onProgress, function (scene, message, exception) {
  60217. reject(exception || new Error(message));
  60218. });
  60219. });
  60220. };
  60221. /**
  60222. * Load a scene
  60223. * @param rootUrl a string that defines the root url for scene and resources
  60224. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60225. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60226. * @param onSuccess a callback with the scene when import succeeds
  60227. * @param onProgress a callback with a progress event for each file being loaded
  60228. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60229. * @param pluginExtension the extension used to determine the plugin
  60230. * @returns The loaded plugin
  60231. */
  60232. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60233. if (onSuccess === void 0) { onSuccess = null; }
  60234. if (onProgress === void 0) { onProgress = null; }
  60235. if (onError === void 0) { onError = null; }
  60236. if (pluginExtension === void 0) { pluginExtension = null; }
  60237. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60238. };
  60239. /**
  60240. * Load a scene
  60241. * @param rootUrl a string that defines the root url for scene and resources
  60242. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60243. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60244. * @param onProgress a callback with a progress event for each file being loaded
  60245. * @param pluginExtension the extension used to determine the plugin
  60246. * @returns The loaded scene
  60247. */
  60248. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60249. if (onProgress === void 0) { onProgress = null; }
  60250. if (pluginExtension === void 0) { pluginExtension = null; }
  60251. return new Promise(function (resolve, reject) {
  60252. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60253. resolve(scene);
  60254. }, onProgress, function (scene, message, exception) {
  60255. reject(exception || new Error(message));
  60256. }, pluginExtension);
  60257. });
  60258. };
  60259. /**
  60260. * Append a scene
  60261. * @param rootUrl a string that defines the root url for scene and resources
  60262. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60263. * @param scene is the instance of BABYLON.Scene to append to
  60264. * @param onSuccess a callback with the scene when import succeeds
  60265. * @param onProgress a callback with a progress event for each file being loaded
  60266. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60267. * @param pluginExtension the extension used to determine the plugin
  60268. * @returns The loaded plugin
  60269. */
  60270. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60271. if (onSuccess === void 0) { onSuccess = null; }
  60272. if (onProgress === void 0) { onProgress = null; }
  60273. if (onError === void 0) { onError = null; }
  60274. if (pluginExtension === void 0) { pluginExtension = null; }
  60275. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60276. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60277. return null;
  60278. }
  60279. if (SceneLoader.ShowLoadingScreen) {
  60280. scene.getEngine().displayLoadingUI();
  60281. }
  60282. var loadingToken = {};
  60283. scene._addPendingData(loadingToken);
  60284. var disposeHandler = function () {
  60285. scene._removePendingData(loadingToken);
  60286. scene.getEngine().hideLoadingUI();
  60287. };
  60288. var errorHandler = function (message, exception) {
  60289. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60290. if (onError) {
  60291. onError(scene, errorMessage, exception);
  60292. }
  60293. else {
  60294. BABYLON.Tools.Error(errorMessage);
  60295. // should the exception be thrown?
  60296. }
  60297. disposeHandler();
  60298. };
  60299. var progressHandler = onProgress ? function (event) {
  60300. try {
  60301. onProgress(event);
  60302. }
  60303. catch (e) {
  60304. errorHandler("Error in onProgress callback", e);
  60305. }
  60306. } : undefined;
  60307. var successHandler = function () {
  60308. if (onSuccess) {
  60309. try {
  60310. onSuccess(scene);
  60311. }
  60312. catch (e) {
  60313. errorHandler("Error in onSuccess callback", e);
  60314. }
  60315. }
  60316. scene._removePendingData(loadingToken);
  60317. };
  60318. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60319. if (sceneFilename === "") {
  60320. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60321. }
  60322. if (plugin.load) {
  60323. var syncedPlugin = plugin;
  60324. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60325. return;
  60326. }
  60327. scene.loadingPluginName = plugin.name;
  60328. successHandler();
  60329. }
  60330. else {
  60331. var asyncedPlugin = plugin;
  60332. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60333. scene.loadingPluginName = plugin.name;
  60334. successHandler();
  60335. }).catch(function (error) {
  60336. errorHandler(error.message, error);
  60337. });
  60338. }
  60339. if (SceneLoader.ShowLoadingScreen) {
  60340. scene.executeWhenReady(function () {
  60341. scene.getEngine().hideLoadingUI();
  60342. });
  60343. }
  60344. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60345. };
  60346. /**
  60347. * Append a scene
  60348. * @param rootUrl a string that defines the root url for scene and resources
  60349. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60350. * @param scene is the instance of BABYLON.Scene to append to
  60351. * @param onProgress a callback with a progress event for each file being loaded
  60352. * @param pluginExtension the extension used to determine the plugin
  60353. * @returns The given scene
  60354. */
  60355. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60356. if (onProgress === void 0) { onProgress = null; }
  60357. if (pluginExtension === void 0) { pluginExtension = null; }
  60358. return new Promise(function (resolve, reject) {
  60359. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60360. resolve(scene);
  60361. }, onProgress, function (scene, message, exception) {
  60362. reject(exception || new Error(message));
  60363. }, pluginExtension);
  60364. });
  60365. };
  60366. /**
  60367. * Load a scene into an asset container
  60368. * @param rootUrl a string that defines the root url for scene and resources
  60369. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60370. * @param scene is the instance of BABYLON.Scene to append to
  60371. * @param onSuccess a callback with the scene when import succeeds
  60372. * @param onProgress a callback with a progress event for each file being loaded
  60373. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60374. * @param pluginExtension the extension used to determine the plugin
  60375. * @returns The loaded plugin
  60376. */
  60377. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60378. if (onSuccess === void 0) { onSuccess = null; }
  60379. if (onProgress === void 0) { onProgress = null; }
  60380. if (onError === void 0) { onError = null; }
  60381. if (pluginExtension === void 0) { pluginExtension = null; }
  60382. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60383. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60384. return null;
  60385. }
  60386. var loadingToken = {};
  60387. scene._addPendingData(loadingToken);
  60388. var disposeHandler = function () {
  60389. scene._removePendingData(loadingToken);
  60390. };
  60391. var errorHandler = function (message, exception) {
  60392. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60393. if (onError) {
  60394. onError(scene, errorMessage, exception);
  60395. }
  60396. else {
  60397. BABYLON.Tools.Error(errorMessage);
  60398. // should the exception be thrown?
  60399. }
  60400. disposeHandler();
  60401. };
  60402. var progressHandler = onProgress ? function (event) {
  60403. try {
  60404. onProgress(event);
  60405. }
  60406. catch (e) {
  60407. errorHandler("Error in onProgress callback", e);
  60408. }
  60409. } : undefined;
  60410. var successHandler = function (assets) {
  60411. if (onSuccess) {
  60412. try {
  60413. onSuccess(assets);
  60414. }
  60415. catch (e) {
  60416. errorHandler("Error in onSuccess callback", e);
  60417. }
  60418. }
  60419. scene._removePendingData(loadingToken);
  60420. };
  60421. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60422. if (plugin.loadAssetContainer) {
  60423. var syncedPlugin = plugin;
  60424. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60425. if (!assetContainer) {
  60426. return;
  60427. }
  60428. scene.loadingPluginName = plugin.name;
  60429. successHandler(assetContainer);
  60430. }
  60431. else if (plugin.loadAssetContainerAsync) {
  60432. var asyncedPlugin = plugin;
  60433. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60434. scene.loadingPluginName = plugin.name;
  60435. successHandler(assetContainer);
  60436. }).catch(function (error) {
  60437. errorHandler(error.message, error);
  60438. });
  60439. }
  60440. else {
  60441. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60442. }
  60443. if (SceneLoader.ShowLoadingScreen) {
  60444. scene.executeWhenReady(function () {
  60445. scene.getEngine().hideLoadingUI();
  60446. });
  60447. }
  60448. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60449. };
  60450. /**
  60451. * Load a scene into an asset container
  60452. * @param rootUrl a string that defines the root url for scene and resources
  60453. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60454. * @param scene is the instance of BABYLON.Scene to append to
  60455. * @param onProgress a callback with a progress event for each file being loaded
  60456. * @param pluginExtension the extension used to determine the plugin
  60457. * @returns The loaded asset container
  60458. */
  60459. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60460. if (onProgress === void 0) { onProgress = null; }
  60461. if (pluginExtension === void 0) { pluginExtension = null; }
  60462. return new Promise(function (resolve, reject) {
  60463. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  60464. resolve(assetContainer);
  60465. }, onProgress, function (scene, message, exception) {
  60466. reject(exception || new Error(message));
  60467. }, pluginExtension);
  60468. });
  60469. };
  60470. // Flags
  60471. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  60472. SceneLoader._ShowLoadingScreen = true;
  60473. SceneLoader._CleanBoneMatrixWeights = false;
  60474. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  60475. // Members
  60476. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  60477. SceneLoader._registeredPlugins = {};
  60478. return SceneLoader;
  60479. }());
  60480. BABYLON.SceneLoader = SceneLoader;
  60481. ;
  60482. })(BABYLON || (BABYLON = {}));
  60483. //# sourceMappingURL=babylon.sceneLoader.js.map
  60484. var BABYLON;
  60485. (function (BABYLON) {
  60486. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  60487. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60488. var parsedMaterial = parsedData.materials[index];
  60489. if (parsedMaterial.id === id) {
  60490. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60491. }
  60492. }
  60493. return null;
  60494. };
  60495. var isDescendantOf = function (mesh, names, hierarchyIds) {
  60496. for (var i in names) {
  60497. if (mesh.name === names[i]) {
  60498. hierarchyIds.push(mesh.id);
  60499. return true;
  60500. }
  60501. }
  60502. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  60503. hierarchyIds.push(mesh.id);
  60504. return true;
  60505. }
  60506. return false;
  60507. };
  60508. var logOperation = function (operation, producer) {
  60509. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  60510. };
  60511. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  60512. if (addToScene === void 0) { addToScene = false; }
  60513. var container = new BABYLON.AssetContainer(scene);
  60514. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60515. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60516. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60517. // and avoid problems with multiple concurrent .babylon loads.
  60518. var log = "importScene has failed JSON parse";
  60519. try {
  60520. var parsedData = JSON.parse(data);
  60521. log = "";
  60522. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60523. var index;
  60524. var cache;
  60525. // Lights
  60526. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  60527. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  60528. var parsedLight = parsedData.lights[index];
  60529. var light = BABYLON.Light.Parse(parsedLight, scene);
  60530. if (light) {
  60531. container.lights.push(light);
  60532. log += (index === 0 ? "\n\tLights:" : "");
  60533. log += "\n\t\t" + light.toString(fullDetails);
  60534. }
  60535. }
  60536. }
  60537. // Animations
  60538. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  60539. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  60540. var parsedAnimation = parsedData.animations[index];
  60541. var animation = BABYLON.Animation.Parse(parsedAnimation);
  60542. scene.animations.push(animation);
  60543. container.animations.push(animation);
  60544. log += (index === 0 ? "\n\tAnimations:" : "");
  60545. log += "\n\t\t" + animation.toString(fullDetails);
  60546. }
  60547. }
  60548. // Materials
  60549. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  60550. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  60551. var parsedMaterial = parsedData.materials[index];
  60552. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  60553. container.materials.push(mat);
  60554. log += (index === 0 ? "\n\tMaterials:" : "");
  60555. log += "\n\t\t" + mat.toString(fullDetails);
  60556. }
  60557. }
  60558. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60559. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  60560. var parsedMultiMaterial = parsedData.multiMaterials[index];
  60561. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60562. container.multiMaterials.push(mmat);
  60563. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  60564. log += "\n\t\t" + mmat.toString(fullDetails);
  60565. }
  60566. }
  60567. // Morph targets
  60568. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  60569. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  60570. var managerData = _a[_i];
  60571. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  60572. }
  60573. }
  60574. // Skeletons
  60575. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60576. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  60577. var parsedSkeleton = parsedData.skeletons[index];
  60578. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60579. container.skeletons.push(skeleton);
  60580. log += (index === 0 ? "\n\tSkeletons:" : "");
  60581. log += "\n\t\t" + skeleton.toString(fullDetails);
  60582. }
  60583. }
  60584. // Geometries
  60585. var geometries = parsedData.geometries;
  60586. if (geometries !== undefined && geometries !== null) {
  60587. var addedGeometry = new Array();
  60588. // Boxes
  60589. var boxes = geometries.boxes;
  60590. if (boxes !== undefined && boxes !== null) {
  60591. for (index = 0, cache = boxes.length; index < cache; index++) {
  60592. var parsedBox = boxes[index];
  60593. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  60594. }
  60595. }
  60596. // Spheres
  60597. var spheres = geometries.spheres;
  60598. if (spheres !== undefined && spheres !== null) {
  60599. for (index = 0, cache = spheres.length; index < cache; index++) {
  60600. var parsedSphere = spheres[index];
  60601. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  60602. }
  60603. }
  60604. // Cylinders
  60605. var cylinders = geometries.cylinders;
  60606. if (cylinders !== undefined && cylinders !== null) {
  60607. for (index = 0, cache = cylinders.length; index < cache; index++) {
  60608. var parsedCylinder = cylinders[index];
  60609. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  60610. }
  60611. }
  60612. // Toruses
  60613. var toruses = geometries.toruses;
  60614. if (toruses !== undefined && toruses !== null) {
  60615. for (index = 0, cache = toruses.length; index < cache; index++) {
  60616. var parsedTorus = toruses[index];
  60617. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  60618. }
  60619. }
  60620. // Grounds
  60621. var grounds = geometries.grounds;
  60622. if (grounds !== undefined && grounds !== null) {
  60623. for (index = 0, cache = grounds.length; index < cache; index++) {
  60624. var parsedGround = grounds[index];
  60625. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  60626. }
  60627. }
  60628. // Planes
  60629. var planes = geometries.planes;
  60630. if (planes !== undefined && planes !== null) {
  60631. for (index = 0, cache = planes.length; index < cache; index++) {
  60632. var parsedPlane = planes[index];
  60633. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  60634. }
  60635. }
  60636. // TorusKnots
  60637. var torusKnots = geometries.torusKnots;
  60638. if (torusKnots !== undefined && torusKnots !== null) {
  60639. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  60640. var parsedTorusKnot = torusKnots[index];
  60641. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  60642. }
  60643. }
  60644. // VertexData
  60645. var vertexData = geometries.vertexData;
  60646. if (vertexData !== undefined && vertexData !== null) {
  60647. for (index = 0, cache = vertexData.length; index < cache; index++) {
  60648. var parsedVertexData = vertexData[index];
  60649. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  60650. }
  60651. }
  60652. addedGeometry.forEach(function (g) {
  60653. if (g) {
  60654. container.geometries.push(g);
  60655. }
  60656. });
  60657. }
  60658. // Transform nodes
  60659. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  60660. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  60661. var parsedTransformNode = parsedData.transformNodes[index];
  60662. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  60663. container.transformNodes.push(node);
  60664. }
  60665. }
  60666. // Meshes
  60667. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60668. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60669. var parsedMesh = parsedData.meshes[index];
  60670. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60671. container.meshes.push(mesh);
  60672. log += (index === 0 ? "\n\tMeshes:" : "");
  60673. log += "\n\t\t" + mesh.toString(fullDetails);
  60674. }
  60675. }
  60676. // Cameras
  60677. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  60678. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  60679. var parsedCamera = parsedData.cameras[index];
  60680. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  60681. container.cameras.push(camera);
  60682. log += (index === 0 ? "\n\tCameras:" : "");
  60683. log += "\n\t\t" + camera.toString(fullDetails);
  60684. }
  60685. }
  60686. // Browsing all the graph to connect the dots
  60687. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  60688. var camera = scene.cameras[index];
  60689. if (camera._waitingParentId) {
  60690. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  60691. camera._waitingParentId = null;
  60692. }
  60693. }
  60694. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60695. var light_1 = scene.lights[index];
  60696. if (light_1 && light_1._waitingParentId) {
  60697. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  60698. light_1._waitingParentId = null;
  60699. }
  60700. }
  60701. // Sounds
  60702. // TODO: add sound
  60703. var loadedSounds = [];
  60704. var loadedSound;
  60705. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  60706. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  60707. var parsedSound = parsedData.sounds[index];
  60708. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  60709. if (!parsedSound.url)
  60710. parsedSound.url = parsedSound.name;
  60711. if (!loadedSounds[parsedSound.url]) {
  60712. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  60713. loadedSounds[parsedSound.url] = loadedSound;
  60714. container.sounds.push(loadedSound);
  60715. }
  60716. else {
  60717. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  60718. }
  60719. }
  60720. else {
  60721. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  60722. }
  60723. }
  60724. }
  60725. loadedSounds = [];
  60726. // Connect parents & children and parse actions
  60727. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  60728. var transformNode = scene.transformNodes[index];
  60729. if (transformNode._waitingParentId) {
  60730. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  60731. transformNode._waitingParentId = null;
  60732. }
  60733. }
  60734. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60735. var mesh = scene.meshes[index];
  60736. if (mesh._waitingParentId) {
  60737. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  60738. mesh._waitingParentId = null;
  60739. }
  60740. if (mesh._waitingActions) {
  60741. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  60742. mesh._waitingActions = null;
  60743. }
  60744. }
  60745. // freeze world matrix application
  60746. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60747. var currentMesh = scene.meshes[index];
  60748. if (currentMesh._waitingFreezeWorldMatrix) {
  60749. currentMesh.freezeWorldMatrix();
  60750. currentMesh._waitingFreezeWorldMatrix = null;
  60751. }
  60752. else {
  60753. currentMesh.computeWorldMatrix(true);
  60754. }
  60755. }
  60756. // Particles Systems
  60757. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60758. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60759. var parsedParticleSystem = parsedData.particleSystems[index];
  60760. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  60761. container.particleSystems.push(ps);
  60762. }
  60763. }
  60764. // Lens flares
  60765. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  60766. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  60767. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  60768. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  60769. container.lensFlareSystems.push(lf);
  60770. }
  60771. }
  60772. // Shadows
  60773. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  60774. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  60775. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  60776. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  60777. container.shadowGenerators.push(sg);
  60778. }
  60779. }
  60780. // Lights exclusions / inclusions
  60781. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  60782. var light_2 = scene.lights[index];
  60783. // Excluded check
  60784. if (light_2._excludedMeshesIds.length > 0) {
  60785. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  60786. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  60787. if (excludedMesh) {
  60788. light_2.excludedMeshes.push(excludedMesh);
  60789. }
  60790. }
  60791. light_2._excludedMeshesIds = [];
  60792. }
  60793. // Included check
  60794. if (light_2._includedOnlyMeshesIds.length > 0) {
  60795. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  60796. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  60797. if (includedOnlyMesh) {
  60798. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  60799. }
  60800. }
  60801. light_2._includedOnlyMeshesIds = [];
  60802. }
  60803. }
  60804. // Actions (scene)
  60805. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  60806. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  60807. }
  60808. if (!addToScene) {
  60809. container.removeAllFromScene();
  60810. }
  60811. }
  60812. catch (err) {
  60813. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  60814. if (onError) {
  60815. onError(msg, err);
  60816. }
  60817. else {
  60818. BABYLON.Tools.Log(msg);
  60819. throw err;
  60820. }
  60821. }
  60822. finally {
  60823. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  60824. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  60825. }
  60826. }
  60827. return container;
  60828. };
  60829. BABYLON.SceneLoader.RegisterPlugin({
  60830. name: "babylon.js",
  60831. extensions: ".babylon",
  60832. canDirectLoad: function (data) {
  60833. if (data.indexOf("babylon") !== -1) {
  60834. return true;
  60835. }
  60836. return false;
  60837. },
  60838. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  60839. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  60840. // when SceneLoader.debugLogging = true (default), or exception encountered.
  60841. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  60842. // and avoid problems with multiple concurrent .babylon loads.
  60843. var log = "importMesh has failed JSON parse";
  60844. try {
  60845. var parsedData = JSON.parse(data);
  60846. log = "";
  60847. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  60848. if (!meshesNames) {
  60849. meshesNames = null;
  60850. }
  60851. else if (!Array.isArray(meshesNames)) {
  60852. meshesNames = [meshesNames];
  60853. }
  60854. var hierarchyIds = new Array();
  60855. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  60856. var loadedSkeletonsIds = [];
  60857. var loadedMaterialsIds = [];
  60858. var index;
  60859. var cache;
  60860. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  60861. var parsedMesh = parsedData.meshes[index];
  60862. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  60863. if (meshesNames !== null) {
  60864. // Remove found mesh name from list.
  60865. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  60866. }
  60867. //Geometry?
  60868. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  60869. //does the file contain geometries?
  60870. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  60871. //find the correct geometry and add it to the scene
  60872. var found = false;
  60873. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  60874. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  60875. return;
  60876. }
  60877. else {
  60878. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  60879. if (parsedGeometryData.id === parsedMesh.geometryId) {
  60880. switch (geometryType) {
  60881. case "boxes":
  60882. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  60883. break;
  60884. case "spheres":
  60885. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  60886. break;
  60887. case "cylinders":
  60888. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  60889. break;
  60890. case "toruses":
  60891. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  60892. break;
  60893. case "grounds":
  60894. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  60895. break;
  60896. case "planes":
  60897. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  60898. break;
  60899. case "torusKnots":
  60900. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  60901. break;
  60902. case "vertexData":
  60903. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  60904. break;
  60905. }
  60906. found = true;
  60907. }
  60908. });
  60909. }
  60910. });
  60911. if (found === false) {
  60912. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  60913. }
  60914. }
  60915. }
  60916. // Material ?
  60917. if (parsedMesh.materialId) {
  60918. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  60919. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  60920. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  60921. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  60922. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  60923. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  60924. var subMatId = parsedMultiMaterial.materials[matIndex];
  60925. loadedMaterialsIds.push(subMatId);
  60926. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  60927. if (mat) {
  60928. log += "\n\tMaterial " + mat.toString(fullDetails);
  60929. }
  60930. }
  60931. loadedMaterialsIds.push(parsedMultiMaterial.id);
  60932. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  60933. if (mmat) {
  60934. materialFound = true;
  60935. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  60936. }
  60937. break;
  60938. }
  60939. }
  60940. }
  60941. if (materialFound === false) {
  60942. loadedMaterialsIds.push(parsedMesh.materialId);
  60943. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  60944. if (!mat) {
  60945. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  60946. }
  60947. else {
  60948. log += "\n\tMaterial " + mat.toString(fullDetails);
  60949. }
  60950. }
  60951. }
  60952. // Skeleton ?
  60953. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  60954. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  60955. if (skeletonAlreadyLoaded === false) {
  60956. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  60957. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  60958. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  60959. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  60960. skeletons.push(skeleton);
  60961. loadedSkeletonsIds.push(parsedSkeleton.id);
  60962. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  60963. }
  60964. }
  60965. }
  60966. }
  60967. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  60968. meshes.push(mesh);
  60969. log += "\n\tMesh " + mesh.toString(fullDetails);
  60970. }
  60971. }
  60972. // Connecting parents
  60973. var currentMesh;
  60974. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60975. currentMesh = scene.meshes[index];
  60976. if (currentMesh._waitingParentId) {
  60977. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  60978. currentMesh._waitingParentId = null;
  60979. }
  60980. }
  60981. // freeze and compute world matrix application
  60982. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  60983. currentMesh = scene.meshes[index];
  60984. if (currentMesh._waitingFreezeWorldMatrix) {
  60985. currentMesh.freezeWorldMatrix();
  60986. currentMesh._waitingFreezeWorldMatrix = null;
  60987. }
  60988. else {
  60989. currentMesh.computeWorldMatrix(true);
  60990. }
  60991. }
  60992. }
  60993. // Particles
  60994. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  60995. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  60996. var parsedParticleSystem = parsedData.particleSystems[index];
  60997. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  60998. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  60999. }
  61000. }
  61001. }
  61002. return true;
  61003. }
  61004. catch (err) {
  61005. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61006. if (onError) {
  61007. onError(msg, err);
  61008. }
  61009. else {
  61010. BABYLON.Tools.Log(msg);
  61011. throw err;
  61012. }
  61013. }
  61014. finally {
  61015. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61016. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61017. }
  61018. }
  61019. return false;
  61020. },
  61021. load: function (scene, data, rootUrl, onError) {
  61022. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61023. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61024. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61025. // and avoid problems with multiple concurrent .babylon loads.
  61026. var log = "importScene has failed JSON parse";
  61027. try {
  61028. var parsedData = JSON.parse(data);
  61029. log = "";
  61030. // Scene
  61031. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61032. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61033. }
  61034. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61035. scene.autoClear = parsedData.autoClear;
  61036. }
  61037. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61038. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61039. }
  61040. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61041. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61042. }
  61043. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61044. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61045. }
  61046. // Fog
  61047. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61048. scene.fogMode = parsedData.fogMode;
  61049. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61050. scene.fogStart = parsedData.fogStart;
  61051. scene.fogEnd = parsedData.fogEnd;
  61052. scene.fogDensity = parsedData.fogDensity;
  61053. log += "\tFog mode for scene: ";
  61054. switch (scene.fogMode) {
  61055. // getters not compiling, so using hardcoded
  61056. case 1:
  61057. log += "exp\n";
  61058. break;
  61059. case 2:
  61060. log += "exp2\n";
  61061. break;
  61062. case 3:
  61063. log += "linear\n";
  61064. break;
  61065. }
  61066. }
  61067. //Physics
  61068. if (parsedData.physicsEnabled) {
  61069. var physicsPlugin;
  61070. if (parsedData.physicsEngine === "cannon") {
  61071. physicsPlugin = new BABYLON.CannonJSPlugin();
  61072. }
  61073. else if (parsedData.physicsEngine === "oimo") {
  61074. physicsPlugin = new BABYLON.OimoJSPlugin();
  61075. }
  61076. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61077. //else - default engine, which is currently oimo
  61078. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61079. scene.enablePhysics(physicsGravity, physicsPlugin);
  61080. }
  61081. // Metadata
  61082. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61083. scene.metadata = parsedData.metadata;
  61084. }
  61085. //collisions, if defined. otherwise, default is true
  61086. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61087. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61088. }
  61089. scene.workerCollisions = !!parsedData.workerCollisions;
  61090. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61091. if (!container) {
  61092. return false;
  61093. }
  61094. if (parsedData.autoAnimate) {
  61095. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61096. }
  61097. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61098. scene.setActiveCameraByID(parsedData.activeCameraID);
  61099. }
  61100. // Environment texture
  61101. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61102. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61103. if (parsedData.createDefaultSkybox === true) {
  61104. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61105. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61106. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61107. }
  61108. }
  61109. // Finish
  61110. return true;
  61111. }
  61112. catch (err) {
  61113. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61114. if (onError) {
  61115. onError(msg, err);
  61116. }
  61117. else {
  61118. BABYLON.Tools.Log(msg);
  61119. throw err;
  61120. }
  61121. }
  61122. finally {
  61123. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61124. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61125. }
  61126. }
  61127. return false;
  61128. },
  61129. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61130. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61131. return container;
  61132. }
  61133. });
  61134. })(BABYLON || (BABYLON = {}));
  61135. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61136. var BABYLON;
  61137. (function (BABYLON) {
  61138. var FilesInput = /** @class */ (function () {
  61139. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61140. this.onProcessFileCallback = function () { return true; };
  61141. this._engine = engine;
  61142. this._currentScene = scene;
  61143. this._sceneLoadedCallback = sceneLoadedCallback;
  61144. this._progressCallback = progressCallback;
  61145. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61146. this._textureLoadingCallback = textureLoadingCallback;
  61147. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61148. this._onReloadCallback = onReloadCallback;
  61149. this._errorCallback = errorCallback;
  61150. }
  61151. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61152. var _this = this;
  61153. if (elementToMonitor) {
  61154. this._elementToMonitor = elementToMonitor;
  61155. this._dragEnterHandler = function (e) { _this.drag(e); };
  61156. this._dragOverHandler = function (e) { _this.drag(e); };
  61157. this._dropHandler = function (e) { _this.drop(e); };
  61158. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61159. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61160. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61161. }
  61162. };
  61163. FilesInput.prototype.dispose = function () {
  61164. if (!this._elementToMonitor) {
  61165. return;
  61166. }
  61167. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61168. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61169. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61170. };
  61171. FilesInput.prototype.renderFunction = function () {
  61172. if (this._additionalRenderLoopLogicCallback) {
  61173. this._additionalRenderLoopLogicCallback();
  61174. }
  61175. if (this._currentScene) {
  61176. if (this._textureLoadingCallback) {
  61177. var remaining = this._currentScene.getWaitingItemsCount();
  61178. if (remaining > 0) {
  61179. this._textureLoadingCallback(remaining);
  61180. }
  61181. }
  61182. this._currentScene.render();
  61183. }
  61184. };
  61185. FilesInput.prototype.drag = function (e) {
  61186. e.stopPropagation();
  61187. e.preventDefault();
  61188. };
  61189. FilesInput.prototype.drop = function (eventDrop) {
  61190. eventDrop.stopPropagation();
  61191. eventDrop.preventDefault();
  61192. this.loadFiles(eventDrop);
  61193. };
  61194. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61195. var _this = this;
  61196. var reader = folder.createReader();
  61197. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61198. reader.readEntries(function (entries) {
  61199. remaining.count += entries.length;
  61200. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61201. var entry = entries_1[_i];
  61202. if (entry.isFile) {
  61203. entry.file(function (file) {
  61204. file.correctName = relativePath + file.name;
  61205. files.push(file);
  61206. if (--remaining.count === 0) {
  61207. callback();
  61208. }
  61209. });
  61210. }
  61211. else if (entry.isDirectory) {
  61212. _this._traverseFolder(entry, files, remaining, callback);
  61213. }
  61214. }
  61215. if (--remaining.count) {
  61216. callback();
  61217. }
  61218. });
  61219. };
  61220. FilesInput.prototype._processFiles = function (files) {
  61221. for (var i = 0; i < files.length; i++) {
  61222. var name = files[i].correctName.toLowerCase();
  61223. var extension = name.split('.').pop();
  61224. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61225. continue;
  61226. }
  61227. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61228. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61229. this._sceneFileToLoad = files[i];
  61230. }
  61231. else {
  61232. FilesInput.FilesToLoad[name] = files[i];
  61233. }
  61234. }
  61235. };
  61236. FilesInput.prototype.loadFiles = function (event) {
  61237. var _this = this;
  61238. if (this._startingProcessingFilesCallback)
  61239. this._startingProcessingFilesCallback();
  61240. // Handling data transfer via drag'n'drop
  61241. if (event && event.dataTransfer && event.dataTransfer.files) {
  61242. this._filesToLoad = event.dataTransfer.files;
  61243. }
  61244. // Handling files from input files
  61245. if (event && event.target && event.target.files) {
  61246. this._filesToLoad = event.target.files;
  61247. }
  61248. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61249. var files_1 = new Array();
  61250. var folders = [];
  61251. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61252. for (var i = 0; i < this._filesToLoad.length; i++) {
  61253. var fileToLoad = this._filesToLoad[i];
  61254. var name_1 = fileToLoad.name.toLowerCase();
  61255. var entry = void 0;
  61256. fileToLoad.correctName = name_1;
  61257. if (items) {
  61258. var item = items[i];
  61259. if (item.getAsEntry) {
  61260. entry = item.getAsEntry();
  61261. }
  61262. else if (item.webkitGetAsEntry) {
  61263. entry = item.webkitGetAsEntry();
  61264. }
  61265. }
  61266. if (!entry) {
  61267. files_1.push(fileToLoad);
  61268. }
  61269. else {
  61270. if (entry.isDirectory) {
  61271. folders.push(entry);
  61272. }
  61273. else {
  61274. files_1.push(fileToLoad);
  61275. }
  61276. }
  61277. }
  61278. if (folders.length === 0) {
  61279. this._processFiles(files_1);
  61280. this._processReload();
  61281. }
  61282. else {
  61283. var remaining = { count: folders.length };
  61284. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61285. var folder = folders_1[_i];
  61286. this._traverseFolder(folder, files_1, remaining, function () {
  61287. _this._processFiles(files_1);
  61288. if (remaining.count === 0) {
  61289. _this._processReload();
  61290. }
  61291. });
  61292. }
  61293. }
  61294. }
  61295. };
  61296. FilesInput.prototype._processReload = function () {
  61297. if (this._onReloadCallback) {
  61298. this._onReloadCallback(this._sceneFileToLoad);
  61299. }
  61300. else {
  61301. this.reload();
  61302. }
  61303. };
  61304. FilesInput.prototype.reload = function () {
  61305. var _this = this;
  61306. // If a scene file has been provided
  61307. if (this._sceneFileToLoad) {
  61308. if (this._currentScene) {
  61309. if (BABYLON.Tools.errorsCount > 0) {
  61310. BABYLON.Tools.ClearLogCache();
  61311. }
  61312. this._engine.stopRenderLoop();
  61313. this._currentScene.dispose();
  61314. }
  61315. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61316. if (_this._progressCallback) {
  61317. _this._progressCallback(progress);
  61318. }
  61319. }).then(function (scene) {
  61320. _this._currentScene = scene;
  61321. if (_this._sceneLoadedCallback) {
  61322. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61323. }
  61324. // Wait for textures and shaders to be ready
  61325. _this._currentScene.executeWhenReady(function () {
  61326. _this._engine.runRenderLoop(function () {
  61327. _this.renderFunction();
  61328. });
  61329. });
  61330. }).catch(function (error) {
  61331. if (_this._errorCallback) {
  61332. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61333. }
  61334. });
  61335. }
  61336. else {
  61337. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61338. }
  61339. };
  61340. FilesInput.FilesToLoad = {};
  61341. return FilesInput;
  61342. }());
  61343. BABYLON.FilesInput = FilesInput;
  61344. })(BABYLON || (BABYLON = {}));
  61345. //# sourceMappingURL=babylon.filesInput.js.map
  61346. var BABYLON;
  61347. (function (BABYLON) {
  61348. /**
  61349. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61350. * The underlying implementation relies on an associative array to ensure the best performances.
  61351. * The value can be anything including 'null' but except 'undefined'
  61352. */
  61353. var StringDictionary = /** @class */ (function () {
  61354. function StringDictionary() {
  61355. this._count = 0;
  61356. this._data = {};
  61357. }
  61358. /**
  61359. * This will clear this dictionary and copy the content from the 'source' one.
  61360. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61361. * @param source the dictionary to take the content from and copy to this dictionary
  61362. */
  61363. StringDictionary.prototype.copyFrom = function (source) {
  61364. var _this = this;
  61365. this.clear();
  61366. source.forEach(function (t, v) { return _this.add(t, v); });
  61367. };
  61368. /**
  61369. * Get a value based from its key
  61370. * @param key the given key to get the matching value from
  61371. * @return the value if found, otherwise undefined is returned
  61372. */
  61373. StringDictionary.prototype.get = function (key) {
  61374. var val = this._data[key];
  61375. if (val !== undefined) {
  61376. return val;
  61377. }
  61378. return undefined;
  61379. };
  61380. /**
  61381. * Get a value from its key or add it if it doesn't exist.
  61382. * This method will ensure you that a given key/data will be present in the dictionary.
  61383. * @param key the given key to get the matching value from
  61384. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61385. * The factory will only be invoked if there's no data for the given key.
  61386. * @return the value corresponding to the key.
  61387. */
  61388. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61389. var val = this.get(key);
  61390. if (val !== undefined) {
  61391. return val;
  61392. }
  61393. val = factory(key);
  61394. if (val) {
  61395. this.add(key, val);
  61396. }
  61397. return val;
  61398. };
  61399. /**
  61400. * Get a value from its key if present in the dictionary otherwise add it
  61401. * @param key the key to get the value from
  61402. * @param val if there's no such key/value pair in the dictionary add it with this value
  61403. * @return the value corresponding to the key
  61404. */
  61405. StringDictionary.prototype.getOrAdd = function (key, val) {
  61406. var curVal = this.get(key);
  61407. if (curVal !== undefined) {
  61408. return curVal;
  61409. }
  61410. this.add(key, val);
  61411. return val;
  61412. };
  61413. /**
  61414. * Check if there's a given key in the dictionary
  61415. * @param key the key to check for
  61416. * @return true if the key is present, false otherwise
  61417. */
  61418. StringDictionary.prototype.contains = function (key) {
  61419. return this._data[key] !== undefined;
  61420. };
  61421. /**
  61422. * Add a new key and its corresponding value
  61423. * @param key the key to add
  61424. * @param value the value corresponding to the key
  61425. * @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
  61426. */
  61427. StringDictionary.prototype.add = function (key, value) {
  61428. if (this._data[key] !== undefined) {
  61429. return false;
  61430. }
  61431. this._data[key] = value;
  61432. ++this._count;
  61433. return true;
  61434. };
  61435. StringDictionary.prototype.set = function (key, value) {
  61436. if (this._data[key] === undefined) {
  61437. return false;
  61438. }
  61439. this._data[key] = value;
  61440. return true;
  61441. };
  61442. /**
  61443. * Get the element of the given key and remove it from the dictionary
  61444. * @param key
  61445. */
  61446. StringDictionary.prototype.getAndRemove = function (key) {
  61447. var val = this.get(key);
  61448. if (val !== undefined) {
  61449. delete this._data[key];
  61450. --this._count;
  61451. return val;
  61452. }
  61453. return null;
  61454. };
  61455. /**
  61456. * Remove a key/value from the dictionary.
  61457. * @param key the key to remove
  61458. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  61459. */
  61460. StringDictionary.prototype.remove = function (key) {
  61461. if (this.contains(key)) {
  61462. delete this._data[key];
  61463. --this._count;
  61464. return true;
  61465. }
  61466. return false;
  61467. };
  61468. /**
  61469. * Clear the whole content of the dictionary
  61470. */
  61471. StringDictionary.prototype.clear = function () {
  61472. this._data = {};
  61473. this._count = 0;
  61474. };
  61475. Object.defineProperty(StringDictionary.prototype, "count", {
  61476. get: function () {
  61477. return this._count;
  61478. },
  61479. enumerable: true,
  61480. configurable: true
  61481. });
  61482. /**
  61483. * Execute a callback on each key/val of the dictionary.
  61484. * Note that you can remove any element in this dictionary in the callback implementation
  61485. * @param callback the callback to execute on a given key/value pair
  61486. */
  61487. StringDictionary.prototype.forEach = function (callback) {
  61488. for (var cur in this._data) {
  61489. var val = this._data[cur];
  61490. callback(cur, val);
  61491. }
  61492. };
  61493. /**
  61494. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  61495. * If the callback returns null or undefined the method will iterate to the next key/value pair
  61496. * Note that you can remove any element in this dictionary in the callback implementation
  61497. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  61498. */
  61499. StringDictionary.prototype.first = function (callback) {
  61500. for (var cur in this._data) {
  61501. var val = this._data[cur];
  61502. var res = callback(cur, val);
  61503. if (res) {
  61504. return res;
  61505. }
  61506. }
  61507. return null;
  61508. };
  61509. return StringDictionary;
  61510. }());
  61511. BABYLON.StringDictionary = StringDictionary;
  61512. })(BABYLON || (BABYLON = {}));
  61513. //# sourceMappingURL=babylon.stringDictionary.js.map
  61514. var BABYLON;
  61515. (function (BABYLON) {
  61516. var Tags = /** @class */ (function () {
  61517. function Tags() {
  61518. }
  61519. Tags.EnableFor = function (obj) {
  61520. obj._tags = obj._tags || {};
  61521. obj.hasTags = function () {
  61522. return Tags.HasTags(obj);
  61523. };
  61524. obj.addTags = function (tagsString) {
  61525. return Tags.AddTagsTo(obj, tagsString);
  61526. };
  61527. obj.removeTags = function (tagsString) {
  61528. return Tags.RemoveTagsFrom(obj, tagsString);
  61529. };
  61530. obj.matchesTagsQuery = function (tagsQuery) {
  61531. return Tags.MatchesQuery(obj, tagsQuery);
  61532. };
  61533. };
  61534. Tags.DisableFor = function (obj) {
  61535. delete obj._tags;
  61536. delete obj.hasTags;
  61537. delete obj.addTags;
  61538. delete obj.removeTags;
  61539. delete obj.matchesTagsQuery;
  61540. };
  61541. Tags.HasTags = function (obj) {
  61542. if (!obj._tags) {
  61543. return false;
  61544. }
  61545. return !BABYLON.Tools.IsEmpty(obj._tags);
  61546. };
  61547. Tags.GetTags = function (obj, asString) {
  61548. if (asString === void 0) { asString = true; }
  61549. if (!obj._tags) {
  61550. return null;
  61551. }
  61552. if (asString) {
  61553. var tagsArray = [];
  61554. for (var tag in obj._tags) {
  61555. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  61556. tagsArray.push(tag);
  61557. }
  61558. }
  61559. return tagsArray.join(" ");
  61560. }
  61561. else {
  61562. return obj._tags;
  61563. }
  61564. };
  61565. // the tags 'true' and 'false' are reserved and cannot be used as tags
  61566. // a tag cannot start with '||', '&&', and '!'
  61567. // it cannot contain whitespaces
  61568. Tags.AddTagsTo = function (obj, tagsString) {
  61569. if (!tagsString) {
  61570. return;
  61571. }
  61572. if (typeof tagsString !== "string") {
  61573. return;
  61574. }
  61575. var tags = tagsString.split(" ");
  61576. tags.forEach(function (tag, index, array) {
  61577. Tags._AddTagTo(obj, tag);
  61578. });
  61579. };
  61580. Tags._AddTagTo = function (obj, tag) {
  61581. tag = tag.trim();
  61582. if (tag === "" || tag === "true" || tag === "false") {
  61583. return;
  61584. }
  61585. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  61586. return;
  61587. }
  61588. Tags.EnableFor(obj);
  61589. obj._tags[tag] = true;
  61590. };
  61591. Tags.RemoveTagsFrom = function (obj, tagsString) {
  61592. if (!Tags.HasTags(obj)) {
  61593. return;
  61594. }
  61595. var tags = tagsString.split(" ");
  61596. for (var t in tags) {
  61597. Tags._RemoveTagFrom(obj, tags[t]);
  61598. }
  61599. };
  61600. Tags._RemoveTagFrom = function (obj, tag) {
  61601. delete obj._tags[tag];
  61602. };
  61603. Tags.MatchesQuery = function (obj, tagsQuery) {
  61604. if (tagsQuery === undefined) {
  61605. return true;
  61606. }
  61607. if (tagsQuery === "") {
  61608. return Tags.HasTags(obj);
  61609. }
  61610. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  61611. };
  61612. return Tags;
  61613. }());
  61614. BABYLON.Tags = Tags;
  61615. })(BABYLON || (BABYLON = {}));
  61616. //# sourceMappingURL=babylon.tags.js.map
  61617. var BABYLON;
  61618. (function (BABYLON) {
  61619. var AndOrNotEvaluator = /** @class */ (function () {
  61620. function AndOrNotEvaluator() {
  61621. }
  61622. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  61623. if (!query.match(/\([^\(\)]*\)/g)) {
  61624. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  61625. }
  61626. else {
  61627. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  61628. // remove parenthesis
  61629. r = r.slice(1, r.length - 1);
  61630. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  61631. });
  61632. }
  61633. if (query === "true") {
  61634. return true;
  61635. }
  61636. if (query === "false") {
  61637. return false;
  61638. }
  61639. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  61640. };
  61641. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  61642. evaluateCallback = evaluateCallback || (function (r) {
  61643. return r === "true" ? true : false;
  61644. });
  61645. var result;
  61646. var or = parenthesisContent.split("||");
  61647. for (var i in or) {
  61648. if (or.hasOwnProperty(i)) {
  61649. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  61650. var and = ori.split("&&");
  61651. if (and.length > 1) {
  61652. for (var j = 0; j < and.length; ++j) {
  61653. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  61654. if (andj !== "true" && andj !== "false") {
  61655. if (andj[0] === "!") {
  61656. result = !evaluateCallback(andj.substring(1));
  61657. }
  61658. else {
  61659. result = evaluateCallback(andj);
  61660. }
  61661. }
  61662. else {
  61663. result = andj === "true" ? true : false;
  61664. }
  61665. if (!result) {
  61666. ori = "false";
  61667. break;
  61668. }
  61669. }
  61670. }
  61671. if (result || ori === "true") {
  61672. result = true;
  61673. break;
  61674. }
  61675. // result equals false (or undefined)
  61676. if (ori !== "true" && ori !== "false") {
  61677. if (ori[0] === "!") {
  61678. result = !evaluateCallback(ori.substring(1));
  61679. }
  61680. else {
  61681. result = evaluateCallback(ori);
  61682. }
  61683. }
  61684. else {
  61685. result = ori === "true" ? true : false;
  61686. }
  61687. }
  61688. }
  61689. // the whole parenthesis scope is replaced by 'true' or 'false'
  61690. return result ? "true" : "false";
  61691. };
  61692. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  61693. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  61694. // remove whitespaces
  61695. r = r.replace(/[\s]/g, function () { return ""; });
  61696. return r.length % 2 ? "!" : "";
  61697. });
  61698. booleanString = booleanString.trim();
  61699. if (booleanString === "!true") {
  61700. booleanString = "false";
  61701. }
  61702. else if (booleanString === "!false") {
  61703. booleanString = "true";
  61704. }
  61705. return booleanString;
  61706. };
  61707. return AndOrNotEvaluator;
  61708. }());
  61709. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  61710. })(BABYLON || (BABYLON = {}));
  61711. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  61712. var BABYLON;
  61713. (function (BABYLON) {
  61714. var Database = /** @class */ (function () {
  61715. function Database(urlToScene, callbackManifestChecked) {
  61716. // Handling various flavors of prefixed version of IndexedDB
  61717. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  61718. this.callbackManifestChecked = callbackManifestChecked;
  61719. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  61720. this.db = null;
  61721. this._enableSceneOffline = false;
  61722. this._enableTexturesOffline = false;
  61723. this.manifestVersionFound = 0;
  61724. this.mustUpdateRessources = false;
  61725. this.hasReachedQuota = false;
  61726. if (!Database.IDBStorageEnabled) {
  61727. this.callbackManifestChecked(true);
  61728. }
  61729. else {
  61730. this.checkManifestFile();
  61731. }
  61732. }
  61733. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  61734. get: function () {
  61735. return this._enableSceneOffline;
  61736. },
  61737. enumerable: true,
  61738. configurable: true
  61739. });
  61740. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  61741. get: function () {
  61742. return this._enableTexturesOffline;
  61743. },
  61744. enumerable: true,
  61745. configurable: true
  61746. });
  61747. Database.prototype.checkManifestFile = function () {
  61748. var _this = this;
  61749. var noManifestFile = function () {
  61750. _this._enableSceneOffline = false;
  61751. _this._enableTexturesOffline = false;
  61752. _this.callbackManifestChecked(false);
  61753. };
  61754. var timeStampUsed = false;
  61755. var manifestURL = this.currentSceneUrl + ".manifest";
  61756. var xhr = new XMLHttpRequest();
  61757. if (navigator.onLine) {
  61758. // Adding a timestamp to by-pass browsers' cache
  61759. timeStampUsed = true;
  61760. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  61761. }
  61762. xhr.open("GET", manifestURL, true);
  61763. xhr.addEventListener("load", function () {
  61764. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  61765. try {
  61766. var manifestFile = JSON.parse(xhr.response);
  61767. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  61768. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  61769. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  61770. _this.manifestVersionFound = manifestFile.version;
  61771. }
  61772. if (_this.callbackManifestChecked) {
  61773. _this.callbackManifestChecked(true);
  61774. }
  61775. }
  61776. catch (ex) {
  61777. noManifestFile();
  61778. }
  61779. }
  61780. else {
  61781. noManifestFile();
  61782. }
  61783. }, false);
  61784. xhr.addEventListener("error", function (event) {
  61785. if (timeStampUsed) {
  61786. timeStampUsed = false;
  61787. // Let's retry without the timeStamp
  61788. // It could fail when coupled with HTML5 Offline API
  61789. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  61790. xhr.open("GET", retryManifestURL, true);
  61791. xhr.send();
  61792. }
  61793. else {
  61794. noManifestFile();
  61795. }
  61796. }, false);
  61797. try {
  61798. xhr.send();
  61799. }
  61800. catch (ex) {
  61801. BABYLON.Tools.Error("Error on XHR send request.");
  61802. this.callbackManifestChecked(false);
  61803. }
  61804. };
  61805. Database.prototype.openAsync = function (successCallback, errorCallback) {
  61806. var _this = this;
  61807. var handleError = function () {
  61808. _this.isSupported = false;
  61809. if (errorCallback)
  61810. errorCallback();
  61811. };
  61812. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  61813. // Your browser doesn't support IndexedDB
  61814. this.isSupported = false;
  61815. if (errorCallback)
  61816. errorCallback();
  61817. }
  61818. else {
  61819. // If the DB hasn't been opened or created yet
  61820. if (!this.db) {
  61821. this.hasReachedQuota = false;
  61822. this.isSupported = true;
  61823. var request = this.idbFactory.open("babylonjs", 1);
  61824. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  61825. request.onerror = function (event) {
  61826. handleError();
  61827. };
  61828. // executes when a version change transaction cannot complete due to other active transactions
  61829. request.onblocked = function (event) {
  61830. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  61831. handleError();
  61832. };
  61833. // DB has been opened successfully
  61834. request.onsuccess = function (event) {
  61835. _this.db = request.result;
  61836. successCallback();
  61837. };
  61838. // Initialization of the DB. Creating Scenes & Textures stores
  61839. request.onupgradeneeded = function (event) {
  61840. _this.db = (event.target).result;
  61841. if (_this.db) {
  61842. try {
  61843. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  61844. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  61845. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  61846. }
  61847. catch (ex) {
  61848. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  61849. handleError();
  61850. }
  61851. }
  61852. };
  61853. }
  61854. else {
  61855. if (successCallback)
  61856. successCallback();
  61857. }
  61858. }
  61859. };
  61860. Database.prototype.loadImageFromDB = function (url, image) {
  61861. var _this = this;
  61862. var completeURL = Database.ReturnFullUrlLocation(url);
  61863. var saveAndLoadImage = function () {
  61864. if (!_this.hasReachedQuota && _this.db !== null) {
  61865. // the texture is not yet in the DB, let's try to save it
  61866. _this._saveImageIntoDBAsync(completeURL, image);
  61867. }
  61868. else {
  61869. image.src = url;
  61870. }
  61871. };
  61872. if (!this.mustUpdateRessources) {
  61873. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  61874. }
  61875. else {
  61876. saveAndLoadImage();
  61877. }
  61878. };
  61879. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  61880. if (this.isSupported && this.db !== null) {
  61881. var texture;
  61882. var transaction = this.db.transaction(["textures"]);
  61883. transaction.onabort = function (event) {
  61884. image.src = url;
  61885. };
  61886. transaction.oncomplete = function (event) {
  61887. var blobTextureURL;
  61888. if (texture) {
  61889. var URL = window.URL || window.webkitURL;
  61890. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  61891. image.onerror = function () {
  61892. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  61893. image.src = url;
  61894. };
  61895. image.src = blobTextureURL;
  61896. }
  61897. else {
  61898. notInDBCallback();
  61899. }
  61900. };
  61901. var getRequest = transaction.objectStore("textures").get(url);
  61902. getRequest.onsuccess = function (event) {
  61903. texture = (event.target).result;
  61904. };
  61905. getRequest.onerror = function (event) {
  61906. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  61907. image.src = url;
  61908. };
  61909. }
  61910. else {
  61911. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61912. image.src = url;
  61913. }
  61914. };
  61915. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  61916. var _this = this;
  61917. if (this.isSupported) {
  61918. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  61919. var generateBlobUrl = function () {
  61920. var blobTextureURL;
  61921. if (blob) {
  61922. var URL = window.URL || window.webkitURL;
  61923. try {
  61924. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  61925. }
  61926. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  61927. catch (ex) {
  61928. blobTextureURL = URL.createObjectURL(blob);
  61929. }
  61930. }
  61931. if (blobTextureURL) {
  61932. image.src = blobTextureURL;
  61933. }
  61934. };
  61935. if (Database.IsUASupportingBlobStorage) {
  61936. var xhr = new XMLHttpRequest(), blob;
  61937. xhr.open("GET", url, true);
  61938. xhr.responseType = "blob";
  61939. xhr.addEventListener("load", function () {
  61940. if (xhr.status === 200 && _this.db) {
  61941. // Blob as response (XHR2)
  61942. blob = xhr.response;
  61943. var transaction = _this.db.transaction(["textures"], "readwrite");
  61944. // the transaction could abort because of a QuotaExceededError error
  61945. transaction.onabort = function (event) {
  61946. try {
  61947. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  61948. var srcElement = (event.srcElement || event.target);
  61949. var error = srcElement.error;
  61950. if (error && error.name === "QuotaExceededError") {
  61951. _this.hasReachedQuota = true;
  61952. }
  61953. }
  61954. catch (ex) { }
  61955. generateBlobUrl();
  61956. };
  61957. transaction.oncomplete = function (event) {
  61958. generateBlobUrl();
  61959. };
  61960. var newTexture = { textureUrl: url, data: blob };
  61961. try {
  61962. // Put the blob into the dabase
  61963. var addRequest = transaction.objectStore("textures").put(newTexture);
  61964. addRequest.onsuccess = function (event) {
  61965. };
  61966. addRequest.onerror = function (event) {
  61967. generateBlobUrl();
  61968. };
  61969. }
  61970. catch (ex) {
  61971. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  61972. if (ex.code === 25) {
  61973. Database.IsUASupportingBlobStorage = false;
  61974. }
  61975. image.src = url;
  61976. }
  61977. }
  61978. else {
  61979. image.src = url;
  61980. }
  61981. }, false);
  61982. xhr.addEventListener("error", function (event) {
  61983. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  61984. image.src = url;
  61985. }, false);
  61986. xhr.send();
  61987. }
  61988. else {
  61989. image.src = url;
  61990. }
  61991. }
  61992. else {
  61993. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  61994. image.src = url;
  61995. }
  61996. };
  61997. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  61998. var _this = this;
  61999. var updateVersion = function () {
  62000. // the version is not yet in the DB or we need to update it
  62001. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62002. };
  62003. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62004. };
  62005. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62006. var _this = this;
  62007. if (this.isSupported && this.db) {
  62008. var version;
  62009. try {
  62010. var transaction = this.db.transaction(["versions"]);
  62011. transaction.oncomplete = function (event) {
  62012. if (version) {
  62013. // If the version in the JSON file is > than the version in DB
  62014. if (_this.manifestVersionFound > version.data) {
  62015. _this.mustUpdateRessources = true;
  62016. updateInDBCallback();
  62017. }
  62018. else {
  62019. callback(version.data);
  62020. }
  62021. }
  62022. else {
  62023. _this.mustUpdateRessources = true;
  62024. updateInDBCallback();
  62025. }
  62026. };
  62027. transaction.onabort = function (event) {
  62028. callback(-1);
  62029. };
  62030. var getRequest = transaction.objectStore("versions").get(url);
  62031. getRequest.onsuccess = function (event) {
  62032. version = (event.target).result;
  62033. };
  62034. getRequest.onerror = function (event) {
  62035. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62036. callback(-1);
  62037. };
  62038. }
  62039. catch (ex) {
  62040. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62041. callback(-1);
  62042. }
  62043. }
  62044. else {
  62045. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62046. callback(-1);
  62047. }
  62048. };
  62049. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62050. var _this = this;
  62051. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62052. try {
  62053. // Open a transaction to the database
  62054. var transaction = this.db.transaction(["versions"], "readwrite");
  62055. // the transaction could abort because of a QuotaExceededError error
  62056. transaction.onabort = function (event) {
  62057. try {
  62058. var error = event.srcElement['error'];
  62059. if (error && error.name === "QuotaExceededError") {
  62060. _this.hasReachedQuota = true;
  62061. }
  62062. }
  62063. catch (ex) { }
  62064. callback(-1);
  62065. };
  62066. transaction.oncomplete = function (event) {
  62067. callback(_this.manifestVersionFound);
  62068. };
  62069. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62070. // Put the scene into the database
  62071. var addRequest = transaction.objectStore("versions").put(newVersion);
  62072. addRequest.onsuccess = function (event) {
  62073. };
  62074. addRequest.onerror = function (event) {
  62075. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62076. };
  62077. }
  62078. catch (ex) {
  62079. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62080. callback(-1);
  62081. }
  62082. }
  62083. else {
  62084. callback(-1);
  62085. }
  62086. };
  62087. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62088. var _this = this;
  62089. var completeUrl = Database.ReturnFullUrlLocation(url);
  62090. var saveAndLoadFile = function () {
  62091. // the scene is not yet in the DB, let's try to save it
  62092. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62093. };
  62094. this._checkVersionFromDB(completeUrl, function (version) {
  62095. if (version !== -1) {
  62096. if (!_this.mustUpdateRessources) {
  62097. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62098. }
  62099. else {
  62100. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62101. }
  62102. }
  62103. else {
  62104. if (errorCallback) {
  62105. errorCallback();
  62106. }
  62107. }
  62108. });
  62109. };
  62110. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62111. if (this.isSupported && this.db) {
  62112. var targetStore;
  62113. if (url.indexOf(".babylon") !== -1) {
  62114. targetStore = "scenes";
  62115. }
  62116. else {
  62117. targetStore = "textures";
  62118. }
  62119. var file;
  62120. var transaction = this.db.transaction([targetStore]);
  62121. transaction.oncomplete = function (event) {
  62122. if (file) {
  62123. callback(file.data);
  62124. }
  62125. else {
  62126. notInDBCallback();
  62127. }
  62128. };
  62129. transaction.onabort = function (event) {
  62130. notInDBCallback();
  62131. };
  62132. var getRequest = transaction.objectStore(targetStore).get(url);
  62133. getRequest.onsuccess = function (event) {
  62134. file = (event.target).result;
  62135. };
  62136. getRequest.onerror = function (event) {
  62137. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62138. notInDBCallback();
  62139. };
  62140. }
  62141. else {
  62142. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62143. callback();
  62144. }
  62145. };
  62146. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62147. var _this = this;
  62148. if (this.isSupported) {
  62149. var targetStore;
  62150. if (url.indexOf(".babylon") !== -1) {
  62151. targetStore = "scenes";
  62152. }
  62153. else {
  62154. targetStore = "textures";
  62155. }
  62156. // Create XHR
  62157. var xhr = new XMLHttpRequest();
  62158. var fileData;
  62159. xhr.open("GET", url, true);
  62160. if (useArrayBuffer) {
  62161. xhr.responseType = "arraybuffer";
  62162. }
  62163. if (progressCallback) {
  62164. xhr.onprogress = progressCallback;
  62165. }
  62166. xhr.addEventListener("load", function () {
  62167. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62168. // Blob as response (XHR2)
  62169. //fileData = xhr.responseText;
  62170. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62171. if (!_this.hasReachedQuota && _this.db) {
  62172. // Open a transaction to the database
  62173. var transaction = _this.db.transaction([targetStore], "readwrite");
  62174. // the transaction could abort because of a QuotaExceededError error
  62175. transaction.onabort = function (event) {
  62176. try {
  62177. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62178. var error = event.srcElement['error'];
  62179. if (error && error.name === "QuotaExceededError") {
  62180. _this.hasReachedQuota = true;
  62181. }
  62182. }
  62183. catch (ex) { }
  62184. callback(fileData);
  62185. };
  62186. transaction.oncomplete = function (event) {
  62187. callback(fileData);
  62188. };
  62189. var newFile;
  62190. if (targetStore === "scenes") {
  62191. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62192. }
  62193. else {
  62194. newFile = { textureUrl: url, data: fileData };
  62195. }
  62196. try {
  62197. // Put the scene into the database
  62198. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62199. addRequest.onsuccess = function (event) {
  62200. };
  62201. addRequest.onerror = function (event) {
  62202. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62203. };
  62204. }
  62205. catch (ex) {
  62206. callback(fileData);
  62207. }
  62208. }
  62209. else {
  62210. callback(fileData);
  62211. }
  62212. }
  62213. else {
  62214. callback();
  62215. }
  62216. }, false);
  62217. xhr.addEventListener("error", function (event) {
  62218. BABYLON.Tools.Error("error on XHR request.");
  62219. callback();
  62220. }, false);
  62221. xhr.send();
  62222. }
  62223. else {
  62224. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62225. callback();
  62226. }
  62227. };
  62228. Database.IsUASupportingBlobStorage = true;
  62229. Database.IDBStorageEnabled = true;
  62230. Database.parseURL = function (url) {
  62231. var a = document.createElement('a');
  62232. a.href = url;
  62233. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62234. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62235. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62236. return absLocation;
  62237. };
  62238. Database.ReturnFullUrlLocation = function (url) {
  62239. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62240. return (Database.parseURL(window.location.href) + url);
  62241. }
  62242. else {
  62243. return url;
  62244. }
  62245. };
  62246. return Database;
  62247. }());
  62248. BABYLON.Database = Database;
  62249. })(BABYLON || (BABYLON = {}));
  62250. //# sourceMappingURL=babylon.database.js.map
  62251. var BABYLON;
  62252. (function (BABYLON) {
  62253. var FresnelParameters = /** @class */ (function () {
  62254. function FresnelParameters() {
  62255. this._isEnabled = true;
  62256. this.leftColor = BABYLON.Color3.White();
  62257. this.rightColor = BABYLON.Color3.Black();
  62258. this.bias = 0;
  62259. this.power = 1;
  62260. }
  62261. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62262. get: function () {
  62263. return this._isEnabled;
  62264. },
  62265. set: function (value) {
  62266. if (this._isEnabled === value) {
  62267. return;
  62268. }
  62269. this._isEnabled = value;
  62270. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62271. },
  62272. enumerable: true,
  62273. configurable: true
  62274. });
  62275. FresnelParameters.prototype.clone = function () {
  62276. var newFresnelParameters = new FresnelParameters();
  62277. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62278. return newFresnelParameters;
  62279. };
  62280. FresnelParameters.prototype.serialize = function () {
  62281. var serializationObject = {};
  62282. serializationObject.isEnabled = this.isEnabled;
  62283. serializationObject.leftColor = this.leftColor;
  62284. serializationObject.rightColor = this.rightColor;
  62285. serializationObject.bias = this.bias;
  62286. serializationObject.power = this.power;
  62287. return serializationObject;
  62288. };
  62289. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62290. var fresnelParameters = new FresnelParameters();
  62291. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62292. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62293. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62294. fresnelParameters.bias = parsedFresnelParameters.bias;
  62295. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62296. return fresnelParameters;
  62297. };
  62298. return FresnelParameters;
  62299. }());
  62300. BABYLON.FresnelParameters = FresnelParameters;
  62301. })(BABYLON || (BABYLON = {}));
  62302. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62303. var BABYLON;
  62304. (function (BABYLON) {
  62305. var MultiMaterial = /** @class */ (function (_super) {
  62306. __extends(MultiMaterial, _super);
  62307. function MultiMaterial(name, scene) {
  62308. var _this = _super.call(this, name, scene, true) || this;
  62309. scene.multiMaterials.push(_this);
  62310. _this.subMaterials = new Array();
  62311. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62312. return _this;
  62313. }
  62314. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62315. get: function () {
  62316. return this._subMaterials;
  62317. },
  62318. set: function (value) {
  62319. this._subMaterials = value;
  62320. this._hookArray(value);
  62321. },
  62322. enumerable: true,
  62323. configurable: true
  62324. });
  62325. MultiMaterial.prototype._hookArray = function (array) {
  62326. var _this = this;
  62327. var oldPush = array.push;
  62328. array.push = function () {
  62329. var items = [];
  62330. for (var _i = 0; _i < arguments.length; _i++) {
  62331. items[_i] = arguments[_i];
  62332. }
  62333. var result = oldPush.apply(array, items);
  62334. _this._markAllSubMeshesAsTexturesDirty();
  62335. return result;
  62336. };
  62337. var oldSplice = array.splice;
  62338. array.splice = function (index, deleteCount) {
  62339. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62340. _this._markAllSubMeshesAsTexturesDirty();
  62341. return deleted;
  62342. };
  62343. };
  62344. // Properties
  62345. MultiMaterial.prototype.getSubMaterial = function (index) {
  62346. if (index < 0 || index >= this.subMaterials.length) {
  62347. return this.getScene().defaultMaterial;
  62348. }
  62349. return this.subMaterials[index];
  62350. };
  62351. MultiMaterial.prototype.getActiveTextures = function () {
  62352. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62353. if (subMaterial) {
  62354. return subMaterial.getActiveTextures();
  62355. }
  62356. else {
  62357. return [];
  62358. }
  62359. }));
  62360. var _a;
  62361. };
  62362. // Methods
  62363. MultiMaterial.prototype.getClassName = function () {
  62364. return "MultiMaterial";
  62365. };
  62366. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62367. for (var index = 0; index < this.subMaterials.length; index++) {
  62368. var subMaterial = this.subMaterials[index];
  62369. if (subMaterial) {
  62370. if (subMaterial.storeEffectOnSubMeshes) {
  62371. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62372. return false;
  62373. }
  62374. continue;
  62375. }
  62376. if (!subMaterial.isReady(mesh)) {
  62377. return false;
  62378. }
  62379. }
  62380. }
  62381. return true;
  62382. };
  62383. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62384. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62385. for (var index = 0; index < this.subMaterials.length; index++) {
  62386. var subMaterial = null;
  62387. var current = this.subMaterials[index];
  62388. if (cloneChildren && current) {
  62389. subMaterial = current.clone(name + "-" + current.name);
  62390. }
  62391. else {
  62392. subMaterial = this.subMaterials[index];
  62393. }
  62394. newMultiMaterial.subMaterials.push(subMaterial);
  62395. }
  62396. return newMultiMaterial;
  62397. };
  62398. MultiMaterial.prototype.serialize = function () {
  62399. var serializationObject = {};
  62400. serializationObject.name = this.name;
  62401. serializationObject.id = this.id;
  62402. if (BABYLON.Tags) {
  62403. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62404. }
  62405. serializationObject.materials = [];
  62406. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62407. var subMat = this.subMaterials[matIndex];
  62408. if (subMat) {
  62409. serializationObject.materials.push(subMat.id);
  62410. }
  62411. else {
  62412. serializationObject.materials.push(null);
  62413. }
  62414. }
  62415. return serializationObject;
  62416. };
  62417. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62418. var scene = this.getScene();
  62419. if (!scene) {
  62420. return;
  62421. }
  62422. var index = scene.multiMaterials.indexOf(this);
  62423. if (index >= 0) {
  62424. scene.multiMaterials.splice(index, 1);
  62425. }
  62426. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62427. };
  62428. return MultiMaterial;
  62429. }(BABYLON.Material));
  62430. BABYLON.MultiMaterial = MultiMaterial;
  62431. })(BABYLON || (BABYLON = {}));
  62432. //# sourceMappingURL=babylon.multiMaterial.js.map
  62433. var BABYLON;
  62434. (function (BABYLON) {
  62435. var FreeCameraTouchInput = /** @class */ (function () {
  62436. function FreeCameraTouchInput() {
  62437. this._offsetX = null;
  62438. this._offsetY = null;
  62439. this._pointerPressed = new Array();
  62440. this.touchAngularSensibility = 200000.0;
  62441. this.touchMoveSensibility = 250.0;
  62442. }
  62443. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62444. var _this = this;
  62445. var previousPosition = null;
  62446. if (this._pointerInput === undefined) {
  62447. this._onLostFocus = function (evt) {
  62448. _this._offsetX = null;
  62449. _this._offsetY = null;
  62450. };
  62451. this._pointerInput = function (p, s) {
  62452. var evt = p.event;
  62453. if (evt.pointerType === "mouse") {
  62454. return;
  62455. }
  62456. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  62457. if (!noPreventDefault) {
  62458. evt.preventDefault();
  62459. }
  62460. _this._pointerPressed.push(evt.pointerId);
  62461. if (_this._pointerPressed.length !== 1) {
  62462. return;
  62463. }
  62464. previousPosition = {
  62465. x: evt.clientX,
  62466. y: evt.clientY
  62467. };
  62468. }
  62469. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  62470. if (!noPreventDefault) {
  62471. evt.preventDefault();
  62472. }
  62473. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62474. if (index === -1) {
  62475. return;
  62476. }
  62477. _this._pointerPressed.splice(index, 1);
  62478. if (index != 0) {
  62479. return;
  62480. }
  62481. previousPosition = null;
  62482. _this._offsetX = null;
  62483. _this._offsetY = null;
  62484. }
  62485. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  62486. if (!noPreventDefault) {
  62487. evt.preventDefault();
  62488. }
  62489. if (!previousPosition) {
  62490. return;
  62491. }
  62492. var index = _this._pointerPressed.indexOf(evt.pointerId);
  62493. if (index != 0) {
  62494. return;
  62495. }
  62496. _this._offsetX = evt.clientX - previousPosition.x;
  62497. _this._offsetY = -(evt.clientY - previousPosition.y);
  62498. }
  62499. };
  62500. }
  62501. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  62502. if (this._onLostFocus) {
  62503. element.addEventListener("blur", this._onLostFocus);
  62504. }
  62505. };
  62506. FreeCameraTouchInput.prototype.detachControl = function (element) {
  62507. if (this._pointerInput && element) {
  62508. if (this._observer) {
  62509. this.camera.getScene().onPointerObservable.remove(this._observer);
  62510. this._observer = null;
  62511. }
  62512. if (this._onLostFocus) {
  62513. element.removeEventListener("blur", this._onLostFocus);
  62514. this._onLostFocus = null;
  62515. }
  62516. this._pointerPressed = [];
  62517. this._offsetX = null;
  62518. this._offsetY = null;
  62519. }
  62520. };
  62521. FreeCameraTouchInput.prototype.checkInputs = function () {
  62522. if (this._offsetX && this._offsetY) {
  62523. var camera = this.camera;
  62524. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  62525. if (this._pointerPressed.length > 1) {
  62526. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  62527. }
  62528. else {
  62529. var speed = camera._computeLocalCameraSpeed();
  62530. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  62531. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  62532. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  62533. }
  62534. }
  62535. };
  62536. FreeCameraTouchInput.prototype.getClassName = function () {
  62537. return "FreeCameraTouchInput";
  62538. };
  62539. FreeCameraTouchInput.prototype.getSimpleName = function () {
  62540. return "touch";
  62541. };
  62542. __decorate([
  62543. BABYLON.serialize()
  62544. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  62545. __decorate([
  62546. BABYLON.serialize()
  62547. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  62548. return FreeCameraTouchInput;
  62549. }());
  62550. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  62551. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  62552. })(BABYLON || (BABYLON = {}));
  62553. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  62554. var BABYLON;
  62555. (function (BABYLON) {
  62556. // We're mainly based on the logic defined into the FreeCamera code
  62557. var TouchCamera = /** @class */ (function (_super) {
  62558. __extends(TouchCamera, _super);
  62559. //-- end properties for backward compatibility for inputs
  62560. function TouchCamera(name, position, scene) {
  62561. var _this = _super.call(this, name, position, scene) || this;
  62562. _this.inputs.addTouch();
  62563. _this._setupInputs();
  62564. return _this;
  62565. }
  62566. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  62567. //-- Begin properties for backward compatibility for inputs
  62568. get: function () {
  62569. var touch = this.inputs.attached["touch"];
  62570. if (touch)
  62571. return touch.touchAngularSensibility;
  62572. return 0;
  62573. },
  62574. set: function (value) {
  62575. var touch = this.inputs.attached["touch"];
  62576. if (touch)
  62577. touch.touchAngularSensibility = value;
  62578. },
  62579. enumerable: true,
  62580. configurable: true
  62581. });
  62582. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  62583. get: function () {
  62584. var touch = this.inputs.attached["touch"];
  62585. if (touch)
  62586. return touch.touchMoveSensibility;
  62587. return 0;
  62588. },
  62589. set: function (value) {
  62590. var touch = this.inputs.attached["touch"];
  62591. if (touch)
  62592. touch.touchMoveSensibility = value;
  62593. },
  62594. enumerable: true,
  62595. configurable: true
  62596. });
  62597. TouchCamera.prototype.getClassName = function () {
  62598. return "TouchCamera";
  62599. };
  62600. TouchCamera.prototype._setupInputs = function () {
  62601. var mouse = this.inputs.attached["mouse"];
  62602. if (mouse) {
  62603. mouse.touchEnabled = false;
  62604. }
  62605. };
  62606. return TouchCamera;
  62607. }(BABYLON.FreeCamera));
  62608. BABYLON.TouchCamera = TouchCamera;
  62609. })(BABYLON || (BABYLON = {}));
  62610. //# sourceMappingURL=babylon.touchCamera.js.map
  62611. var BABYLON;
  62612. (function (BABYLON) {
  62613. var ProceduralTexture = /** @class */ (function (_super) {
  62614. __extends(ProceduralTexture, _super);
  62615. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  62616. if (fallbackTexture === void 0) { fallbackTexture = null; }
  62617. if (generateMipMaps === void 0) { generateMipMaps = true; }
  62618. if (isCube === void 0) { isCube = false; }
  62619. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62620. _this.isCube = isCube;
  62621. _this.isEnabled = true;
  62622. _this._currentRefreshId = -1;
  62623. _this._refreshRate = 1;
  62624. _this._vertexBuffers = {};
  62625. _this._uniforms = new Array();
  62626. _this._samplers = new Array();
  62627. _this._textures = {};
  62628. _this._floats = {};
  62629. _this._floatsArrays = {};
  62630. _this._colors3 = {};
  62631. _this._colors4 = {};
  62632. _this._vectors2 = {};
  62633. _this._vectors3 = {};
  62634. _this._matrices = {};
  62635. _this._fallbackTextureUsed = false;
  62636. scene._proceduralTextures.push(_this);
  62637. _this._engine = scene.getEngine();
  62638. _this.name = name;
  62639. _this.isRenderTarget = true;
  62640. _this._size = size;
  62641. _this._generateMipMaps = generateMipMaps;
  62642. _this.setFragment(fragment);
  62643. _this._fallbackTexture = fallbackTexture;
  62644. if (isCube) {
  62645. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  62646. _this.setFloat("face", 0);
  62647. }
  62648. else {
  62649. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  62650. }
  62651. // VBO
  62652. var vertices = [];
  62653. vertices.push(1, 1);
  62654. vertices.push(-1, 1);
  62655. vertices.push(-1, -1);
  62656. vertices.push(1, -1);
  62657. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  62658. _this._createIndexBuffer();
  62659. return _this;
  62660. }
  62661. ProceduralTexture.prototype._createIndexBuffer = function () {
  62662. var engine = this._engine;
  62663. // Indices
  62664. var indices = [];
  62665. indices.push(0);
  62666. indices.push(1);
  62667. indices.push(2);
  62668. indices.push(0);
  62669. indices.push(2);
  62670. indices.push(3);
  62671. this._indexBuffer = engine.createIndexBuffer(indices);
  62672. };
  62673. ProceduralTexture.prototype._rebuild = function () {
  62674. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62675. if (vb) {
  62676. vb._rebuild();
  62677. }
  62678. this._createIndexBuffer();
  62679. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  62680. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  62681. }
  62682. };
  62683. ProceduralTexture.prototype.reset = function () {
  62684. if (this._effect === undefined) {
  62685. return;
  62686. }
  62687. var engine = this._engine;
  62688. engine._releaseEffect(this._effect);
  62689. };
  62690. ProceduralTexture.prototype.isReady = function () {
  62691. var _this = this;
  62692. var engine = this._engine;
  62693. var shaders;
  62694. if (!this._fragment) {
  62695. return false;
  62696. }
  62697. if (this._fallbackTextureUsed) {
  62698. return true;
  62699. }
  62700. if (this._fragment.fragmentElement !== undefined) {
  62701. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  62702. }
  62703. else {
  62704. shaders = { vertex: "procedural", fragment: this._fragment };
  62705. }
  62706. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  62707. _this.releaseInternalTexture();
  62708. if (_this._fallbackTexture) {
  62709. _this._texture = _this._fallbackTexture._texture;
  62710. if (_this._texture) {
  62711. _this._texture.incrementReferences();
  62712. }
  62713. }
  62714. _this._fallbackTextureUsed = true;
  62715. });
  62716. return this._effect.isReady();
  62717. };
  62718. ProceduralTexture.prototype.resetRefreshCounter = function () {
  62719. this._currentRefreshId = -1;
  62720. };
  62721. ProceduralTexture.prototype.setFragment = function (fragment) {
  62722. this._fragment = fragment;
  62723. };
  62724. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  62725. get: function () {
  62726. return this._refreshRate;
  62727. },
  62728. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62729. set: function (value) {
  62730. this._refreshRate = value;
  62731. this.resetRefreshCounter();
  62732. },
  62733. enumerable: true,
  62734. configurable: true
  62735. });
  62736. ProceduralTexture.prototype._shouldRender = function () {
  62737. if (!this.isEnabled || !this.isReady() || !this._texture) {
  62738. return false;
  62739. }
  62740. if (this._fallbackTextureUsed) {
  62741. return false;
  62742. }
  62743. if (this._currentRefreshId === -1) {
  62744. this._currentRefreshId = 1;
  62745. return true;
  62746. }
  62747. if (this.refreshRate === this._currentRefreshId) {
  62748. this._currentRefreshId = 1;
  62749. return true;
  62750. }
  62751. this._currentRefreshId++;
  62752. return false;
  62753. };
  62754. ProceduralTexture.prototype.getRenderSize = function () {
  62755. return this._size;
  62756. };
  62757. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  62758. if (this._fallbackTextureUsed) {
  62759. return;
  62760. }
  62761. this.releaseInternalTexture();
  62762. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  62763. };
  62764. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  62765. if (this._uniforms.indexOf(uniformName) === -1) {
  62766. this._uniforms.push(uniformName);
  62767. }
  62768. };
  62769. ProceduralTexture.prototype.setTexture = function (name, texture) {
  62770. if (this._samplers.indexOf(name) === -1) {
  62771. this._samplers.push(name);
  62772. }
  62773. this._textures[name] = texture;
  62774. return this;
  62775. };
  62776. ProceduralTexture.prototype.setFloat = function (name, value) {
  62777. this._checkUniform(name);
  62778. this._floats[name] = value;
  62779. return this;
  62780. };
  62781. ProceduralTexture.prototype.setFloats = function (name, value) {
  62782. this._checkUniform(name);
  62783. this._floatsArrays[name] = value;
  62784. return this;
  62785. };
  62786. ProceduralTexture.prototype.setColor3 = function (name, value) {
  62787. this._checkUniform(name);
  62788. this._colors3[name] = value;
  62789. return this;
  62790. };
  62791. ProceduralTexture.prototype.setColor4 = function (name, value) {
  62792. this._checkUniform(name);
  62793. this._colors4[name] = value;
  62794. return this;
  62795. };
  62796. ProceduralTexture.prototype.setVector2 = function (name, value) {
  62797. this._checkUniform(name);
  62798. this._vectors2[name] = value;
  62799. return this;
  62800. };
  62801. ProceduralTexture.prototype.setVector3 = function (name, value) {
  62802. this._checkUniform(name);
  62803. this._vectors3[name] = value;
  62804. return this;
  62805. };
  62806. ProceduralTexture.prototype.setMatrix = function (name, value) {
  62807. this._checkUniform(name);
  62808. this._matrices[name] = value;
  62809. return this;
  62810. };
  62811. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62812. var scene = this.getScene();
  62813. if (!scene) {
  62814. return;
  62815. }
  62816. var engine = this._engine;
  62817. // Render
  62818. engine.enableEffect(this._effect);
  62819. engine.setState(false);
  62820. // Texture
  62821. for (var name in this._textures) {
  62822. this._effect.setTexture(name, this._textures[name]);
  62823. }
  62824. // Float
  62825. for (name in this._floats) {
  62826. this._effect.setFloat(name, this._floats[name]);
  62827. }
  62828. // Floats
  62829. for (name in this._floatsArrays) {
  62830. this._effect.setArray(name, this._floatsArrays[name]);
  62831. }
  62832. // Color3
  62833. for (name in this._colors3) {
  62834. this._effect.setColor3(name, this._colors3[name]);
  62835. }
  62836. // Color4
  62837. for (name in this._colors4) {
  62838. var color = this._colors4[name];
  62839. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62840. }
  62841. // Vector2
  62842. for (name in this._vectors2) {
  62843. this._effect.setVector2(name, this._vectors2[name]);
  62844. }
  62845. // Vector3
  62846. for (name in this._vectors3) {
  62847. this._effect.setVector3(name, this._vectors3[name]);
  62848. }
  62849. // Matrix
  62850. for (name in this._matrices) {
  62851. this._effect.setMatrix(name, this._matrices[name]);
  62852. }
  62853. if (!this._texture) {
  62854. return;
  62855. }
  62856. if (this.isCube) {
  62857. for (var face = 0; face < 6; face++) {
  62858. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  62859. // VBOs
  62860. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62861. this._effect.setFloat("face", face);
  62862. // Clear
  62863. engine.clear(scene.clearColor, true, true, true);
  62864. // Draw order
  62865. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62866. // Mipmaps
  62867. if (face === 5) {
  62868. engine.generateMipMapsForCubemap(this._texture);
  62869. }
  62870. }
  62871. }
  62872. else {
  62873. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  62874. // VBOs
  62875. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  62876. // Clear
  62877. engine.clear(scene.clearColor, true, true, true);
  62878. // Draw order
  62879. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  62880. }
  62881. // Unbind
  62882. engine.unBindFramebuffer(this._texture, this.isCube);
  62883. if (this.onGenerated) {
  62884. this.onGenerated();
  62885. }
  62886. };
  62887. ProceduralTexture.prototype.clone = function () {
  62888. var textureSize = this.getSize();
  62889. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  62890. // Base texture
  62891. newTexture.hasAlpha = this.hasAlpha;
  62892. newTexture.level = this.level;
  62893. // RenderTarget Texture
  62894. newTexture.coordinatesMode = this.coordinatesMode;
  62895. return newTexture;
  62896. };
  62897. ProceduralTexture.prototype.dispose = function () {
  62898. var scene = this.getScene();
  62899. if (!scene) {
  62900. return;
  62901. }
  62902. var index = scene._proceduralTextures.indexOf(this);
  62903. if (index >= 0) {
  62904. scene._proceduralTextures.splice(index, 1);
  62905. }
  62906. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  62907. if (vertexBuffer) {
  62908. vertexBuffer.dispose();
  62909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  62910. }
  62911. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  62912. this._indexBuffer = null;
  62913. }
  62914. _super.prototype.dispose.call(this);
  62915. };
  62916. return ProceduralTexture;
  62917. }(BABYLON.Texture));
  62918. BABYLON.ProceduralTexture = ProceduralTexture;
  62919. })(BABYLON || (BABYLON = {}));
  62920. //# sourceMappingURL=babylon.proceduralTexture.js.map
  62921. var BABYLON;
  62922. (function (BABYLON) {
  62923. var CustomProceduralTexture = /** @class */ (function (_super) {
  62924. __extends(CustomProceduralTexture, _super);
  62925. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  62926. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  62927. _this._animate = true;
  62928. _this._time = 0;
  62929. _this._texturePath = texturePath;
  62930. //Try to load json
  62931. _this.loadJson(texturePath);
  62932. _this.refreshRate = 1;
  62933. return _this;
  62934. }
  62935. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  62936. var _this = this;
  62937. var noConfigFile = function () {
  62938. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  62939. try {
  62940. _this.setFragment(_this._texturePath);
  62941. }
  62942. catch (ex) {
  62943. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  62944. }
  62945. };
  62946. var configFileUrl = jsonUrl + "/config.json";
  62947. var xhr = new XMLHttpRequest();
  62948. xhr.open("GET", configFileUrl, true);
  62949. xhr.addEventListener("load", function () {
  62950. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62951. try {
  62952. _this._config = JSON.parse(xhr.response);
  62953. _this.updateShaderUniforms();
  62954. _this.updateTextures();
  62955. _this.setFragment(_this._texturePath + "/custom");
  62956. _this._animate = _this._config.animate;
  62957. _this.refreshRate = _this._config.refreshrate;
  62958. }
  62959. catch (ex) {
  62960. noConfigFile();
  62961. }
  62962. }
  62963. else {
  62964. noConfigFile();
  62965. }
  62966. }, false);
  62967. xhr.addEventListener("error", function () {
  62968. noConfigFile();
  62969. }, false);
  62970. try {
  62971. xhr.send();
  62972. }
  62973. catch (ex) {
  62974. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  62975. }
  62976. };
  62977. CustomProceduralTexture.prototype.isReady = function () {
  62978. if (!_super.prototype.isReady.call(this)) {
  62979. return false;
  62980. }
  62981. for (var name in this._textures) {
  62982. var texture = this._textures[name];
  62983. if (!texture.isReady()) {
  62984. return false;
  62985. }
  62986. }
  62987. return true;
  62988. };
  62989. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  62990. var scene = this.getScene();
  62991. if (this._animate && scene) {
  62992. this._time += scene.getAnimationRatio() * 0.03;
  62993. this.updateShaderUniforms();
  62994. }
  62995. _super.prototype.render.call(this, useCameraPostProcess);
  62996. };
  62997. CustomProceduralTexture.prototype.updateTextures = function () {
  62998. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  62999. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63000. }
  63001. };
  63002. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63003. if (this._config) {
  63004. for (var j = 0; j < this._config.uniforms.length; j++) {
  63005. var uniform = this._config.uniforms[j];
  63006. switch (uniform.type) {
  63007. case "float":
  63008. this.setFloat(uniform.name, uniform.value);
  63009. break;
  63010. case "color3":
  63011. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63012. break;
  63013. case "color4":
  63014. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63015. break;
  63016. case "vector2":
  63017. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63018. break;
  63019. case "vector3":
  63020. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63021. break;
  63022. }
  63023. }
  63024. }
  63025. this.setFloat("time", this._time);
  63026. };
  63027. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63028. get: function () {
  63029. return this._animate;
  63030. },
  63031. set: function (value) {
  63032. this._animate = value;
  63033. },
  63034. enumerable: true,
  63035. configurable: true
  63036. });
  63037. return CustomProceduralTexture;
  63038. }(BABYLON.ProceduralTexture));
  63039. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63040. })(BABYLON || (BABYLON = {}));
  63041. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63042. var BABYLON;
  63043. (function (BABYLON) {
  63044. var FreeCameraGamepadInput = /** @class */ (function () {
  63045. function FreeCameraGamepadInput() {
  63046. this.gamepadAngularSensibility = 200;
  63047. this.gamepadMoveSensibility = 40;
  63048. // private members
  63049. this._cameraTransform = BABYLON.Matrix.Identity();
  63050. this._deltaTransform = BABYLON.Vector3.Zero();
  63051. this._vector3 = BABYLON.Vector3.Zero();
  63052. this._vector2 = BABYLON.Vector2.Zero();
  63053. }
  63054. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63055. var _this = this;
  63056. var manager = this.camera.getScene().gamepadManager;
  63057. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63058. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63059. // prioritize XBOX gamepads.
  63060. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63061. _this.gamepad = gamepad;
  63062. }
  63063. }
  63064. });
  63065. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63066. if (_this.gamepad === gamepad) {
  63067. _this.gamepad = null;
  63068. }
  63069. });
  63070. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63071. };
  63072. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63073. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63074. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63075. this.gamepad = null;
  63076. };
  63077. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63078. if (this.gamepad && this.gamepad.leftStick) {
  63079. var camera = this.camera;
  63080. var LSValues = this.gamepad.leftStick;
  63081. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63082. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63083. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63084. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63085. var RSValues = this.gamepad.rightStick;
  63086. if (RSValues) {
  63087. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63088. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63089. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63090. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63091. }
  63092. else {
  63093. RSValues = { x: 0, y: 0 };
  63094. }
  63095. if (!camera.rotationQuaternion) {
  63096. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63097. }
  63098. else {
  63099. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63100. }
  63101. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63102. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63103. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63104. camera.cameraDirection.addInPlace(this._deltaTransform);
  63105. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63106. camera.cameraRotation.addInPlace(this._vector2);
  63107. }
  63108. };
  63109. FreeCameraGamepadInput.prototype.getClassName = function () {
  63110. return "FreeCameraGamepadInput";
  63111. };
  63112. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63113. return "gamepad";
  63114. };
  63115. __decorate([
  63116. BABYLON.serialize()
  63117. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63118. __decorate([
  63119. BABYLON.serialize()
  63120. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63121. return FreeCameraGamepadInput;
  63122. }());
  63123. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63124. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63125. })(BABYLON || (BABYLON = {}));
  63126. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63127. var BABYLON;
  63128. (function (BABYLON) {
  63129. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63130. function ArcRotateCameraGamepadInput() {
  63131. this.gamepadRotationSensibility = 80;
  63132. this.gamepadMoveSensibility = 40;
  63133. }
  63134. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63135. var _this = this;
  63136. var manager = this.camera.getScene().gamepadManager;
  63137. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63138. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63139. // prioritize XBOX gamepads.
  63140. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63141. _this.gamepad = gamepad;
  63142. }
  63143. }
  63144. });
  63145. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63146. if (_this.gamepad === gamepad) {
  63147. _this.gamepad = null;
  63148. }
  63149. });
  63150. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63151. };
  63152. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63153. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63154. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63155. this.gamepad = null;
  63156. };
  63157. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63158. if (this.gamepad) {
  63159. var camera = this.camera;
  63160. var RSValues = this.gamepad.rightStick;
  63161. if (RSValues) {
  63162. if (RSValues.x != 0) {
  63163. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63164. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63165. camera.inertialAlphaOffset += normalizedRX;
  63166. }
  63167. }
  63168. if (RSValues.y != 0) {
  63169. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63170. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63171. camera.inertialBetaOffset += normalizedRY;
  63172. }
  63173. }
  63174. }
  63175. var LSValues = this.gamepad.leftStick;
  63176. if (LSValues && LSValues.y != 0) {
  63177. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63178. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63179. this.camera.inertialRadiusOffset -= normalizedLY;
  63180. }
  63181. }
  63182. }
  63183. };
  63184. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63185. return "ArcRotateCameraGamepadInput";
  63186. };
  63187. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63188. return "gamepad";
  63189. };
  63190. __decorate([
  63191. BABYLON.serialize()
  63192. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63193. __decorate([
  63194. BABYLON.serialize()
  63195. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63196. return ArcRotateCameraGamepadInput;
  63197. }());
  63198. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63199. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63200. })(BABYLON || (BABYLON = {}));
  63201. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63202. var BABYLON;
  63203. (function (BABYLON) {
  63204. var GamepadManager = /** @class */ (function () {
  63205. function GamepadManager(_scene) {
  63206. var _this = this;
  63207. this._scene = _scene;
  63208. this._babylonGamepads = [];
  63209. this._oneGamepadConnected = false;
  63210. this._isMonitoring = false;
  63211. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63212. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63213. this._gamepadEventSupported = false;
  63214. }
  63215. else {
  63216. this._gamepadEventSupported = 'GamepadEvent' in window;
  63217. this._gamepadSupport = (navigator.getGamepads ||
  63218. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63219. }
  63220. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63221. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63222. for (var i in _this._babylonGamepads) {
  63223. var gamepad = _this._babylonGamepads[i];
  63224. if (gamepad && gamepad._isConnected) {
  63225. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63226. }
  63227. }
  63228. });
  63229. this._onGamepadConnectedEvent = function (evt) {
  63230. var gamepad = evt.gamepad;
  63231. if (gamepad.index in _this._babylonGamepads) {
  63232. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63233. return;
  63234. }
  63235. }
  63236. var newGamepad;
  63237. if (_this._babylonGamepads[gamepad.index]) {
  63238. newGamepad = _this._babylonGamepads[gamepad.index];
  63239. newGamepad.browserGamepad = gamepad;
  63240. newGamepad._isConnected = true;
  63241. }
  63242. else {
  63243. newGamepad = _this._addNewGamepad(gamepad);
  63244. }
  63245. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63246. _this._startMonitoringGamepads();
  63247. };
  63248. this._onGamepadDisconnectedEvent = function (evt) {
  63249. var gamepad = evt.gamepad;
  63250. // Remove the gamepad from the list of gamepads to monitor.
  63251. for (var i in _this._babylonGamepads) {
  63252. if (_this._babylonGamepads[i].index === gamepad.index) {
  63253. var disconnectedGamepad = _this._babylonGamepads[i];
  63254. disconnectedGamepad._isConnected = false;
  63255. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63256. break;
  63257. }
  63258. }
  63259. };
  63260. if (this._gamepadSupport) {
  63261. //first add already-connected gamepads
  63262. this._updateGamepadObjects();
  63263. if (this._babylonGamepads.length) {
  63264. this._startMonitoringGamepads();
  63265. }
  63266. // Checking if the gamepad connected event is supported (like in Firefox)
  63267. if (this._gamepadEventSupported) {
  63268. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63269. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63270. }
  63271. else {
  63272. this._startMonitoringGamepads();
  63273. }
  63274. }
  63275. }
  63276. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63277. get: function () {
  63278. return this._babylonGamepads;
  63279. },
  63280. enumerable: true,
  63281. configurable: true
  63282. });
  63283. GamepadManager.prototype.getGamepadByType = function (type) {
  63284. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63285. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63286. var gamepad = _a[_i];
  63287. if (gamepad && gamepad.type === type) {
  63288. return gamepad;
  63289. }
  63290. }
  63291. return null;
  63292. };
  63293. GamepadManager.prototype.dispose = function () {
  63294. if (this._gamepadEventSupported) {
  63295. if (this._onGamepadConnectedEvent) {
  63296. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63297. }
  63298. if (this._onGamepadDisconnectedEvent) {
  63299. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63300. }
  63301. this._onGamepadConnectedEvent = null;
  63302. this._onGamepadDisconnectedEvent = null;
  63303. }
  63304. this._babylonGamepads.forEach(function (gamepad) {
  63305. gamepad.dispose();
  63306. });
  63307. this.onGamepadConnectedObservable.clear();
  63308. this.onGamepadDisconnectedObservable.clear();
  63309. this._oneGamepadConnected = false;
  63310. this._stopMonitoringGamepads();
  63311. this._babylonGamepads = [];
  63312. };
  63313. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63314. if (!this._oneGamepadConnected) {
  63315. this._oneGamepadConnected = true;
  63316. }
  63317. var newGamepad;
  63318. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63319. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63320. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63321. }
  63322. else if (gamepad.pose) {
  63323. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63324. }
  63325. else {
  63326. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63327. }
  63328. this._babylonGamepads[newGamepad.index] = newGamepad;
  63329. return newGamepad;
  63330. };
  63331. GamepadManager.prototype._startMonitoringGamepads = function () {
  63332. if (!this._isMonitoring) {
  63333. this._isMonitoring = true;
  63334. //back-comp
  63335. if (!this._scene) {
  63336. this._checkGamepadsStatus();
  63337. }
  63338. }
  63339. };
  63340. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63341. this._isMonitoring = false;
  63342. };
  63343. GamepadManager.prototype._checkGamepadsStatus = function () {
  63344. var _this = this;
  63345. // Hack to be compatible Chrome
  63346. this._updateGamepadObjects();
  63347. for (var i in this._babylonGamepads) {
  63348. var gamepad = this._babylonGamepads[i];
  63349. if (!gamepad || !gamepad.isConnected) {
  63350. continue;
  63351. }
  63352. gamepad.update();
  63353. }
  63354. if (this._isMonitoring && !this._scene) {
  63355. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63356. }
  63357. };
  63358. // This function is called only on Chrome, which does not properly support
  63359. // connection/disconnection events and forces you to recopy again the gamepad object
  63360. GamepadManager.prototype._updateGamepadObjects = function () {
  63361. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63362. for (var i = 0; i < gamepads.length; i++) {
  63363. if (gamepads[i]) {
  63364. if (!this._babylonGamepads[gamepads[i].index]) {
  63365. var newGamepad = this._addNewGamepad(gamepads[i]);
  63366. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63367. }
  63368. else {
  63369. // Forced to copy again this object for Chrome for unknown reason
  63370. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63371. if (!this._babylonGamepads[i].isConnected) {
  63372. this._babylonGamepads[i]._isConnected = true;
  63373. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63374. }
  63375. }
  63376. }
  63377. }
  63378. };
  63379. return GamepadManager;
  63380. }());
  63381. BABYLON.GamepadManager = GamepadManager;
  63382. })(BABYLON || (BABYLON = {}));
  63383. //# sourceMappingURL=babylon.gamepadManager.js.map
  63384. var BABYLON;
  63385. (function (BABYLON) {
  63386. var StickValues = /** @class */ (function () {
  63387. function StickValues(x, y) {
  63388. this.x = x;
  63389. this.y = y;
  63390. }
  63391. return StickValues;
  63392. }());
  63393. BABYLON.StickValues = StickValues;
  63394. var Gamepad = /** @class */ (function () {
  63395. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63396. if (leftStickX === void 0) { leftStickX = 0; }
  63397. if (leftStickY === void 0) { leftStickY = 1; }
  63398. if (rightStickX === void 0) { rightStickX = 2; }
  63399. if (rightStickY === void 0) { rightStickY = 3; }
  63400. this.id = id;
  63401. this.index = index;
  63402. this.browserGamepad = browserGamepad;
  63403. this._isConnected = true;
  63404. this._invertLeftStickY = false;
  63405. this.type = Gamepad.GAMEPAD;
  63406. this._leftStickAxisX = leftStickX;
  63407. this._leftStickAxisY = leftStickY;
  63408. this._rightStickAxisX = rightStickX;
  63409. this._rightStickAxisY = rightStickY;
  63410. if (this.browserGamepad.axes.length >= 2) {
  63411. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63412. }
  63413. if (this.browserGamepad.axes.length >= 4) {
  63414. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63415. }
  63416. }
  63417. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63418. get: function () {
  63419. return this._isConnected;
  63420. },
  63421. enumerable: true,
  63422. configurable: true
  63423. });
  63424. Gamepad.prototype.onleftstickchanged = function (callback) {
  63425. this._onleftstickchanged = callback;
  63426. };
  63427. Gamepad.prototype.onrightstickchanged = function (callback) {
  63428. this._onrightstickchanged = callback;
  63429. };
  63430. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63431. get: function () {
  63432. return this._leftStick;
  63433. },
  63434. set: function (newValues) {
  63435. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63436. this._onleftstickchanged(newValues);
  63437. }
  63438. this._leftStick = newValues;
  63439. },
  63440. enumerable: true,
  63441. configurable: true
  63442. });
  63443. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63444. get: function () {
  63445. return this._rightStick;
  63446. },
  63447. set: function (newValues) {
  63448. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  63449. this._onrightstickchanged(newValues);
  63450. }
  63451. this._rightStick = newValues;
  63452. },
  63453. enumerable: true,
  63454. configurable: true
  63455. });
  63456. Gamepad.prototype.update = function () {
  63457. if (this._leftStick) {
  63458. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63459. if (this._invertLeftStickY) {
  63460. this.leftStick.y *= -1;
  63461. }
  63462. }
  63463. if (this._rightStick) {
  63464. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63465. }
  63466. };
  63467. Gamepad.prototype.dispose = function () {
  63468. };
  63469. Gamepad.GAMEPAD = 0;
  63470. Gamepad.GENERIC = 1;
  63471. Gamepad.XBOX = 2;
  63472. Gamepad.POSE_ENABLED = 3;
  63473. return Gamepad;
  63474. }());
  63475. BABYLON.Gamepad = Gamepad;
  63476. var GenericPad = /** @class */ (function (_super) {
  63477. __extends(GenericPad, _super);
  63478. function GenericPad(id, index, browserGamepad) {
  63479. var _this = _super.call(this, id, index, browserGamepad) || this;
  63480. _this.onButtonDownObservable = new BABYLON.Observable();
  63481. _this.onButtonUpObservable = new BABYLON.Observable();
  63482. _this.type = Gamepad.GENERIC;
  63483. _this._buttons = new Array(browserGamepad.buttons.length);
  63484. return _this;
  63485. }
  63486. GenericPad.prototype.onbuttondown = function (callback) {
  63487. this._onbuttondown = callback;
  63488. };
  63489. GenericPad.prototype.onbuttonup = function (callback) {
  63490. this._onbuttonup = callback;
  63491. };
  63492. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  63493. if (newValue !== currentValue) {
  63494. if (newValue === 1) {
  63495. if (this._onbuttondown) {
  63496. this._onbuttondown(buttonIndex);
  63497. }
  63498. this.onButtonDownObservable.notifyObservers(buttonIndex);
  63499. }
  63500. if (newValue === 0) {
  63501. if (this._onbuttonup) {
  63502. this._onbuttonup(buttonIndex);
  63503. }
  63504. this.onButtonUpObservable.notifyObservers(buttonIndex);
  63505. }
  63506. }
  63507. return newValue;
  63508. };
  63509. GenericPad.prototype.update = function () {
  63510. _super.prototype.update.call(this);
  63511. for (var index = 0; index < this._buttons.length; index++) {
  63512. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  63513. }
  63514. };
  63515. GenericPad.prototype.dispose = function () {
  63516. _super.prototype.dispose.call(this);
  63517. this.onButtonDownObservable.clear();
  63518. this.onButtonUpObservable.clear();
  63519. };
  63520. return GenericPad;
  63521. }(Gamepad));
  63522. BABYLON.GenericPad = GenericPad;
  63523. })(BABYLON || (BABYLON = {}));
  63524. //# sourceMappingURL=babylon.gamepad.js.map
  63525. var BABYLON;
  63526. (function (BABYLON) {
  63527. var Xbox360Button;
  63528. (function (Xbox360Button) {
  63529. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  63530. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  63531. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  63532. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  63533. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  63534. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  63535. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  63536. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  63537. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  63538. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  63539. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  63540. var Xbox360Dpad;
  63541. (function (Xbox360Dpad) {
  63542. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  63543. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  63544. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  63545. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  63546. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  63547. var Xbox360Pad = /** @class */ (function (_super) {
  63548. __extends(Xbox360Pad, _super);
  63549. function Xbox360Pad(id, index, gamepad, xboxOne) {
  63550. if (xboxOne === void 0) { xboxOne = false; }
  63551. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  63552. _this._leftTrigger = 0;
  63553. _this._rightTrigger = 0;
  63554. _this.onButtonDownObservable = new BABYLON.Observable();
  63555. _this.onButtonUpObservable = new BABYLON.Observable();
  63556. _this.onPadDownObservable = new BABYLON.Observable();
  63557. _this.onPadUpObservable = new BABYLON.Observable();
  63558. _this._buttonA = 0;
  63559. _this._buttonB = 0;
  63560. _this._buttonX = 0;
  63561. _this._buttonY = 0;
  63562. _this._buttonBack = 0;
  63563. _this._buttonStart = 0;
  63564. _this._buttonLB = 0;
  63565. _this._buttonRB = 0;
  63566. _this._buttonLeftStick = 0;
  63567. _this._buttonRightStick = 0;
  63568. _this._dPadUp = 0;
  63569. _this._dPadDown = 0;
  63570. _this._dPadLeft = 0;
  63571. _this._dPadRight = 0;
  63572. _this._isXboxOnePad = false;
  63573. _this.type = BABYLON.Gamepad.XBOX;
  63574. _this._isXboxOnePad = xboxOne;
  63575. return _this;
  63576. }
  63577. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  63578. this._onlefttriggerchanged = callback;
  63579. };
  63580. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  63581. this._onrighttriggerchanged = callback;
  63582. };
  63583. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  63584. get: function () {
  63585. return this._leftTrigger;
  63586. },
  63587. set: function (newValue) {
  63588. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  63589. this._onlefttriggerchanged(newValue);
  63590. }
  63591. this._leftTrigger = newValue;
  63592. },
  63593. enumerable: true,
  63594. configurable: true
  63595. });
  63596. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  63597. get: function () {
  63598. return this._rightTrigger;
  63599. },
  63600. set: function (newValue) {
  63601. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  63602. this._onrighttriggerchanged(newValue);
  63603. }
  63604. this._rightTrigger = newValue;
  63605. },
  63606. enumerable: true,
  63607. configurable: true
  63608. });
  63609. Xbox360Pad.prototype.onbuttondown = function (callback) {
  63610. this._onbuttondown = callback;
  63611. };
  63612. Xbox360Pad.prototype.onbuttonup = function (callback) {
  63613. this._onbuttonup = callback;
  63614. };
  63615. Xbox360Pad.prototype.ondpaddown = function (callback) {
  63616. this._ondpaddown = callback;
  63617. };
  63618. Xbox360Pad.prototype.ondpadup = function (callback) {
  63619. this._ondpadup = callback;
  63620. };
  63621. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  63622. if (newValue !== currentValue) {
  63623. if (newValue === 1) {
  63624. if (this._onbuttondown) {
  63625. this._onbuttondown(buttonType);
  63626. }
  63627. this.onButtonDownObservable.notifyObservers(buttonType);
  63628. }
  63629. if (newValue === 0) {
  63630. if (this._onbuttonup) {
  63631. this._onbuttonup(buttonType);
  63632. }
  63633. this.onButtonUpObservable.notifyObservers(buttonType);
  63634. }
  63635. }
  63636. return newValue;
  63637. };
  63638. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  63639. if (newValue !== currentValue) {
  63640. if (newValue === 1) {
  63641. if (this._ondpaddown) {
  63642. this._ondpaddown(buttonType);
  63643. }
  63644. this.onPadDownObservable.notifyObservers(buttonType);
  63645. }
  63646. if (newValue === 0) {
  63647. if (this._ondpadup) {
  63648. this._ondpadup(buttonType);
  63649. }
  63650. this.onPadUpObservable.notifyObservers(buttonType);
  63651. }
  63652. }
  63653. return newValue;
  63654. };
  63655. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  63656. get: function () {
  63657. return this._buttonA;
  63658. },
  63659. set: function (value) {
  63660. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  63661. },
  63662. enumerable: true,
  63663. configurable: true
  63664. });
  63665. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  63666. get: function () {
  63667. return this._buttonB;
  63668. },
  63669. set: function (value) {
  63670. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  63671. },
  63672. enumerable: true,
  63673. configurable: true
  63674. });
  63675. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  63676. get: function () {
  63677. return this._buttonX;
  63678. },
  63679. set: function (value) {
  63680. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  63681. },
  63682. enumerable: true,
  63683. configurable: true
  63684. });
  63685. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  63686. get: function () {
  63687. return this._buttonY;
  63688. },
  63689. set: function (value) {
  63690. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  63691. },
  63692. enumerable: true,
  63693. configurable: true
  63694. });
  63695. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  63696. get: function () {
  63697. return this._buttonStart;
  63698. },
  63699. set: function (value) {
  63700. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  63701. },
  63702. enumerable: true,
  63703. configurable: true
  63704. });
  63705. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  63706. get: function () {
  63707. return this._buttonBack;
  63708. },
  63709. set: function (value) {
  63710. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  63711. },
  63712. enumerable: true,
  63713. configurable: true
  63714. });
  63715. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  63716. get: function () {
  63717. return this._buttonLB;
  63718. },
  63719. set: function (value) {
  63720. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  63721. },
  63722. enumerable: true,
  63723. configurable: true
  63724. });
  63725. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  63726. get: function () {
  63727. return this._buttonRB;
  63728. },
  63729. set: function (value) {
  63730. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  63731. },
  63732. enumerable: true,
  63733. configurable: true
  63734. });
  63735. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  63736. get: function () {
  63737. return this._buttonLeftStick;
  63738. },
  63739. set: function (value) {
  63740. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  63741. },
  63742. enumerable: true,
  63743. configurable: true
  63744. });
  63745. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  63746. get: function () {
  63747. return this._buttonRightStick;
  63748. },
  63749. set: function (value) {
  63750. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  63751. },
  63752. enumerable: true,
  63753. configurable: true
  63754. });
  63755. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  63756. get: function () {
  63757. return this._dPadUp;
  63758. },
  63759. set: function (value) {
  63760. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  63761. },
  63762. enumerable: true,
  63763. configurable: true
  63764. });
  63765. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  63766. get: function () {
  63767. return this._dPadDown;
  63768. },
  63769. set: function (value) {
  63770. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  63771. },
  63772. enumerable: true,
  63773. configurable: true
  63774. });
  63775. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  63776. get: function () {
  63777. return this._dPadLeft;
  63778. },
  63779. set: function (value) {
  63780. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  63781. },
  63782. enumerable: true,
  63783. configurable: true
  63784. });
  63785. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  63786. get: function () {
  63787. return this._dPadRight;
  63788. },
  63789. set: function (value) {
  63790. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  63791. },
  63792. enumerable: true,
  63793. configurable: true
  63794. });
  63795. Xbox360Pad.prototype.update = function () {
  63796. _super.prototype.update.call(this);
  63797. if (this._isXboxOnePad) {
  63798. this.buttonA = this.browserGamepad.buttons[0].value;
  63799. this.buttonB = this.browserGamepad.buttons[1].value;
  63800. this.buttonX = this.browserGamepad.buttons[2].value;
  63801. this.buttonY = this.browserGamepad.buttons[3].value;
  63802. this.buttonLB = this.browserGamepad.buttons[4].value;
  63803. this.buttonRB = this.browserGamepad.buttons[5].value;
  63804. this.leftTrigger = this.browserGamepad.axes[2];
  63805. this.rightTrigger = this.browserGamepad.axes[5];
  63806. this.buttonBack = this.browserGamepad.buttons[9].value;
  63807. this.buttonStart = this.browserGamepad.buttons[8].value;
  63808. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  63809. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  63810. this.dPadUp = this.browserGamepad.buttons[11].value;
  63811. this.dPadDown = this.browserGamepad.buttons[12].value;
  63812. this.dPadLeft = this.browserGamepad.buttons[13].value;
  63813. this.dPadRight = this.browserGamepad.buttons[14].value;
  63814. }
  63815. else {
  63816. this.buttonA = this.browserGamepad.buttons[0].value;
  63817. this.buttonB = this.browserGamepad.buttons[1].value;
  63818. this.buttonX = this.browserGamepad.buttons[2].value;
  63819. this.buttonY = this.browserGamepad.buttons[3].value;
  63820. this.buttonLB = this.browserGamepad.buttons[4].value;
  63821. this.buttonRB = this.browserGamepad.buttons[5].value;
  63822. this.leftTrigger = this.browserGamepad.buttons[6].value;
  63823. this.rightTrigger = this.browserGamepad.buttons[7].value;
  63824. this.buttonBack = this.browserGamepad.buttons[8].value;
  63825. this.buttonStart = this.browserGamepad.buttons[9].value;
  63826. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  63827. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  63828. this.dPadUp = this.browserGamepad.buttons[12].value;
  63829. this.dPadDown = this.browserGamepad.buttons[13].value;
  63830. this.dPadLeft = this.browserGamepad.buttons[14].value;
  63831. this.dPadRight = this.browserGamepad.buttons[15].value;
  63832. }
  63833. };
  63834. Xbox360Pad.prototype.dispose = function () {
  63835. _super.prototype.dispose.call(this);
  63836. this.onButtonDownObservable.clear();
  63837. this.onButtonUpObservable.clear();
  63838. this.onPadDownObservable.clear();
  63839. this.onPadUpObservable.clear();
  63840. };
  63841. return Xbox360Pad;
  63842. }(BABYLON.Gamepad));
  63843. BABYLON.Xbox360Pad = Xbox360Pad;
  63844. })(BABYLON || (BABYLON = {}));
  63845. //# sourceMappingURL=babylon.xboxGamepad.js.map
  63846. var BABYLON;
  63847. (function (BABYLON) {
  63848. var PoseEnabledControllerType;
  63849. (function (PoseEnabledControllerType) {
  63850. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  63851. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  63852. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  63853. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  63854. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  63855. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  63856. var PoseEnabledControllerHelper = /** @class */ (function () {
  63857. function PoseEnabledControllerHelper() {
  63858. }
  63859. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  63860. // Oculus Touch
  63861. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  63862. return new BABYLON.OculusTouchController(vrGamepad);
  63863. }
  63864. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  63865. return new BABYLON.WindowsMotionController(vrGamepad);
  63866. }
  63867. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  63868. return new BABYLON.ViveController(vrGamepad);
  63869. }
  63870. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  63871. return new BABYLON.GearVRController(vrGamepad);
  63872. }
  63873. else {
  63874. return new BABYLON.GenericController(vrGamepad);
  63875. }
  63876. };
  63877. return PoseEnabledControllerHelper;
  63878. }());
  63879. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  63880. var PoseEnabledController = /** @class */ (function (_super) {
  63881. __extends(PoseEnabledController, _super);
  63882. function PoseEnabledController(browserGamepad) {
  63883. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  63884. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  63885. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  63886. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  63887. // Represents device position and rotation in babylon space
  63888. _this.devicePosition = BABYLON.Vector3.Zero();
  63889. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  63890. _this.deviceScaleFactor = 1;
  63891. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  63892. _this._deviceToWorld = BABYLON.Matrix.Identity();
  63893. _this._workingMatrix = BABYLON.Matrix.Identity();
  63894. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  63895. _this.controllerType = PoseEnabledControllerType.GENERIC;
  63896. _this.position = BABYLON.Vector3.Zero();
  63897. _this.rotationQuaternion = new BABYLON.Quaternion();
  63898. _this._calculatedPosition = BABYLON.Vector3.Zero();
  63899. _this._calculatedRotation = new BABYLON.Quaternion();
  63900. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  63901. return _this;
  63902. }
  63903. PoseEnabledController.prototype.update = function () {
  63904. _super.prototype.update.call(this);
  63905. var pose = this.browserGamepad.pose;
  63906. this.updateFromDevice(pose);
  63907. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  63908. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  63909. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  63910. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  63911. if (this._mesh) {
  63912. this._mesh.position.copyFrom(this.devicePosition);
  63913. if (this._mesh.rotationQuaternion) {
  63914. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  63915. }
  63916. }
  63917. };
  63918. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  63919. if (poseData) {
  63920. this.rawPose = poseData;
  63921. if (poseData.position) {
  63922. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  63923. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  63924. this._deviceRoomPosition.z *= -1;
  63925. }
  63926. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  63927. this._calculatedPosition.addInPlace(this.position);
  63928. }
  63929. var pose = this.rawPose;
  63930. if (poseData.orientation && pose.orientation) {
  63931. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  63932. if (this._mesh) {
  63933. if (this._mesh.getScene().useRightHandedSystem) {
  63934. this._deviceRoomRotationQuaternion.z *= -1;
  63935. this._deviceRoomRotationQuaternion.w *= -1;
  63936. }
  63937. else {
  63938. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  63939. }
  63940. }
  63941. // if the camera is set, rotate to the camera's rotation
  63942. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  63943. }
  63944. }
  63945. };
  63946. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  63947. if (this._mesh) {
  63948. this._mesh.parent = null;
  63949. }
  63950. this._mesh = mesh;
  63951. if (this._poseControlledCamera) {
  63952. this._mesh.parent = this._poseControlledCamera;
  63953. }
  63954. if (!this._mesh.rotationQuaternion) {
  63955. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  63956. }
  63957. };
  63958. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  63959. this._poseControlledCamera = camera;
  63960. if (this._mesh) {
  63961. this._mesh.parent = this._poseControlledCamera;
  63962. }
  63963. };
  63964. PoseEnabledController.prototype.dispose = function () {
  63965. if (this._mesh) {
  63966. this._mesh.dispose();
  63967. }
  63968. this._mesh = null;
  63969. _super.prototype.dispose.call(this);
  63970. };
  63971. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  63972. get: function () {
  63973. return this._mesh;
  63974. },
  63975. enumerable: true,
  63976. configurable: true
  63977. });
  63978. PoseEnabledController.prototype.getForwardRay = function (length) {
  63979. if (length === void 0) { length = 100; }
  63980. if (!this.mesh) {
  63981. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  63982. }
  63983. var m = this.mesh.getWorldMatrix();
  63984. var origin = m.getTranslation();
  63985. var forward = new BABYLON.Vector3(0, 0, -1);
  63986. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  63987. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  63988. return new BABYLON.Ray(origin, direction, length);
  63989. };
  63990. return PoseEnabledController;
  63991. }(BABYLON.Gamepad));
  63992. BABYLON.PoseEnabledController = PoseEnabledController;
  63993. })(BABYLON || (BABYLON = {}));
  63994. //# sourceMappingURL=babylon.poseEnabledController.js.map
  63995. var BABYLON;
  63996. (function (BABYLON) {
  63997. var WebVRController = /** @class */ (function (_super) {
  63998. __extends(WebVRController, _super);
  63999. function WebVRController(vrGamepad) {
  64000. var _this = _super.call(this, vrGamepad) || this;
  64001. // Observables
  64002. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64003. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64004. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64005. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64006. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64007. _this.pad = { x: 0, y: 0 };
  64008. // avoid GC, store state in a tmp object
  64009. _this._changes = {
  64010. pressChanged: false,
  64011. touchChanged: false,
  64012. valueChanged: false,
  64013. changed: false
  64014. };
  64015. _this._buttons = new Array(vrGamepad.buttons.length);
  64016. _this.hand = vrGamepad.hand;
  64017. return _this;
  64018. }
  64019. WebVRController.prototype.onButtonStateChange = function (callback) {
  64020. this._onButtonStateChange = callback;
  64021. };
  64022. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64023. get: function () {
  64024. return this._defaultModel;
  64025. },
  64026. enumerable: true,
  64027. configurable: true
  64028. });
  64029. WebVRController.prototype.update = function () {
  64030. _super.prototype.update.call(this);
  64031. for (var index = 0; index < this._buttons.length; index++) {
  64032. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64033. }
  64034. ;
  64035. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64036. this.pad.x = this.leftStick.x;
  64037. this.pad.y = this.leftStick.y;
  64038. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64039. }
  64040. };
  64041. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64042. if (!newState) {
  64043. newState = {
  64044. pressed: false,
  64045. touched: false,
  64046. value: 0
  64047. };
  64048. }
  64049. if (!currentState) {
  64050. this._buttons[buttonIndex] = {
  64051. pressed: newState.pressed,
  64052. touched: newState.touched,
  64053. value: newState.value
  64054. };
  64055. return;
  64056. }
  64057. this._checkChanges(newState, currentState);
  64058. if (this._changes.changed) {
  64059. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64060. this.handleButtonChange(buttonIndex, newState, this._changes);
  64061. }
  64062. this._buttons[buttonIndex].pressed = newState.pressed;
  64063. this._buttons[buttonIndex].touched = newState.touched;
  64064. // oculus triggers are never 0, thou not touched.
  64065. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64066. };
  64067. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64068. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64069. this._changes.touchChanged = newState.touched !== currentState.touched;
  64070. this._changes.valueChanged = newState.value !== currentState.value;
  64071. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64072. return this._changes;
  64073. };
  64074. WebVRController.prototype.dispose = function () {
  64075. _super.prototype.dispose.call(this);
  64076. this.onTriggerStateChangedObservable.clear();
  64077. this.onMainButtonStateChangedObservable.clear();
  64078. this.onSecondaryButtonStateChangedObservable.clear();
  64079. this.onPadStateChangedObservable.clear();
  64080. this.onPadValuesChangedObservable.clear();
  64081. };
  64082. return WebVRController;
  64083. }(BABYLON.PoseEnabledController));
  64084. BABYLON.WebVRController = WebVRController;
  64085. })(BABYLON || (BABYLON = {}));
  64086. //# sourceMappingURL=babylon.webVRController.js.map
  64087. var BABYLON;
  64088. (function (BABYLON) {
  64089. var OculusTouchController = /** @class */ (function (_super) {
  64090. __extends(OculusTouchController, _super);
  64091. function OculusTouchController(vrGamepad) {
  64092. var _this = _super.call(this, vrGamepad) || this;
  64093. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64094. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64095. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64096. return _this;
  64097. }
  64098. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64099. var _this = this;
  64100. var meshName;
  64101. // Hand
  64102. if (this.hand === 'left') {
  64103. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64104. }
  64105. else {
  64106. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64107. }
  64108. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64109. /*
  64110. Parent Mesh name: oculus_touch_left
  64111. - body
  64112. - trigger
  64113. - thumbstick
  64114. - grip
  64115. - button_y
  64116. - button_x
  64117. - button_enter
  64118. */
  64119. _this._defaultModel = newMeshes[1];
  64120. _this.attachToMesh(_this._defaultModel);
  64121. if (meshLoaded) {
  64122. meshLoaded(_this._defaultModel);
  64123. }
  64124. });
  64125. };
  64126. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64127. // helper getters for left and right hand.
  64128. get: function () {
  64129. if (this.hand === 'right') {
  64130. return this.onMainButtonStateChangedObservable;
  64131. }
  64132. else {
  64133. throw new Error('No A button on left hand');
  64134. }
  64135. },
  64136. enumerable: true,
  64137. configurable: true
  64138. });
  64139. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64140. get: function () {
  64141. if (this.hand === 'right') {
  64142. return this.onSecondaryButtonStateChangedObservable;
  64143. }
  64144. else {
  64145. throw new Error('No B button on left hand');
  64146. }
  64147. },
  64148. enumerable: true,
  64149. configurable: true
  64150. });
  64151. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64152. get: function () {
  64153. if (this.hand === 'left') {
  64154. return this.onMainButtonStateChangedObservable;
  64155. }
  64156. else {
  64157. throw new Error('No X button on right hand');
  64158. }
  64159. },
  64160. enumerable: true,
  64161. configurable: true
  64162. });
  64163. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64164. get: function () {
  64165. if (this.hand === 'left') {
  64166. return this.onSecondaryButtonStateChangedObservable;
  64167. }
  64168. else {
  64169. throw new Error('No Y button on right hand');
  64170. }
  64171. },
  64172. enumerable: true,
  64173. configurable: true
  64174. });
  64175. /*
  64176. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64177. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64178. 2) secondary trigger (same)
  64179. 3) A (right) X (left), touch, pressed = value
  64180. 4) B / Y
  64181. 5) thumb rest
  64182. */
  64183. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64184. var notifyObject = state; //{ state: state, changes: changes };
  64185. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64186. switch (buttonIdx) {
  64187. case 0:
  64188. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64189. return;
  64190. case 1:// index trigger
  64191. if (this._defaultModel) {
  64192. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64193. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64194. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64195. }
  64196. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64197. return;
  64198. case 2:// secondary trigger
  64199. if (this._defaultModel) {
  64200. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64201. }
  64202. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64203. return;
  64204. case 3:
  64205. if (this._defaultModel) {
  64206. if (notifyObject.pressed) {
  64207. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64208. }
  64209. else {
  64210. (this._defaultModel.getChildren()[1]).position.y = 0;
  64211. }
  64212. }
  64213. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64214. return;
  64215. case 4:
  64216. if (this._defaultModel) {
  64217. if (notifyObject.pressed) {
  64218. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64219. }
  64220. else {
  64221. (this._defaultModel.getChildren()[2]).position.y = 0;
  64222. }
  64223. }
  64224. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64225. return;
  64226. case 5:
  64227. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64228. return;
  64229. }
  64230. };
  64231. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64232. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64233. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64234. return OculusTouchController;
  64235. }(BABYLON.WebVRController));
  64236. BABYLON.OculusTouchController = OculusTouchController;
  64237. })(BABYLON || (BABYLON = {}));
  64238. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64239. var BABYLON;
  64240. (function (BABYLON) {
  64241. var ViveController = /** @class */ (function (_super) {
  64242. __extends(ViveController, _super);
  64243. function ViveController(vrGamepad) {
  64244. var _this = _super.call(this, vrGamepad) || this;
  64245. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64246. _this._invertLeftStickY = true;
  64247. return _this;
  64248. }
  64249. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64250. var _this = this;
  64251. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64252. /*
  64253. Parent Mesh name: ViveWand
  64254. - body
  64255. - r_gripper
  64256. - l_gripper
  64257. - menu_button
  64258. - system_button
  64259. - trackpad
  64260. - trigger
  64261. - LED
  64262. */
  64263. _this._defaultModel = newMeshes[1];
  64264. _this.attachToMesh(_this._defaultModel);
  64265. if (meshLoaded) {
  64266. meshLoaded(_this._defaultModel);
  64267. }
  64268. });
  64269. };
  64270. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64271. get: function () {
  64272. return this.onMainButtonStateChangedObservable;
  64273. },
  64274. enumerable: true,
  64275. configurable: true
  64276. });
  64277. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64278. get: function () {
  64279. return this.onMainButtonStateChangedObservable;
  64280. },
  64281. enumerable: true,
  64282. configurable: true
  64283. });
  64284. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64285. get: function () {
  64286. return this.onSecondaryButtonStateChangedObservable;
  64287. },
  64288. enumerable: true,
  64289. configurable: true
  64290. });
  64291. /**
  64292. * Vive mapping:
  64293. * 0: touchpad
  64294. * 1: trigger
  64295. * 2: left AND right buttons
  64296. * 3: menu button
  64297. */
  64298. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64299. var notifyObject = state; //{ state: state, changes: changes };
  64300. switch (buttonIdx) {
  64301. case 0:
  64302. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64303. return;
  64304. case 1:// index trigger
  64305. if (this._defaultModel) {
  64306. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64307. }
  64308. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64309. return;
  64310. case 2:// left AND right button
  64311. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64312. return;
  64313. case 3:
  64314. if (this._defaultModel) {
  64315. if (notifyObject.pressed) {
  64316. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64317. }
  64318. else {
  64319. (this._defaultModel.getChildren()[2]).position.y = 0;
  64320. }
  64321. }
  64322. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64323. return;
  64324. }
  64325. };
  64326. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64327. ViveController.MODEL_FILENAME = 'wand.babylon';
  64328. return ViveController;
  64329. }(BABYLON.WebVRController));
  64330. BABYLON.ViveController = ViveController;
  64331. })(BABYLON || (BABYLON = {}));
  64332. //# sourceMappingURL=babylon.viveController.js.map
  64333. var BABYLON;
  64334. (function (BABYLON) {
  64335. var GenericController = /** @class */ (function (_super) {
  64336. __extends(GenericController, _super);
  64337. function GenericController(vrGamepad) {
  64338. return _super.call(this, vrGamepad) || this;
  64339. }
  64340. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64341. var _this = this;
  64342. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64343. _this._defaultModel = newMeshes[1];
  64344. _this.attachToMesh(_this._defaultModel);
  64345. if (meshLoaded) {
  64346. meshLoaded(_this._defaultModel);
  64347. }
  64348. });
  64349. };
  64350. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64351. console.log("Button id: " + buttonIdx + "state: ");
  64352. console.dir(state);
  64353. };
  64354. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64355. GenericController.MODEL_FILENAME = 'generic.babylon';
  64356. return GenericController;
  64357. }(BABYLON.WebVRController));
  64358. BABYLON.GenericController = GenericController;
  64359. })(BABYLON || (BABYLON = {}));
  64360. //# sourceMappingURL=babylon.genericController.js.map
  64361. var BABYLON;
  64362. (function (BABYLON) {
  64363. var LoadedMeshInfo = /** @class */ (function () {
  64364. function LoadedMeshInfo() {
  64365. this.buttonMeshes = {};
  64366. this.axisMeshes = {};
  64367. }
  64368. return LoadedMeshInfo;
  64369. }());
  64370. var WindowsMotionController = /** @class */ (function (_super) {
  64371. __extends(WindowsMotionController, _super);
  64372. function WindowsMotionController(vrGamepad) {
  64373. var _this = _super.call(this, vrGamepad) || this;
  64374. _this._mapping = {
  64375. // Semantic button names
  64376. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64377. // A mapping of the button name to glTF model node name
  64378. // that should be transformed by button value.
  64379. buttonMeshNames: {
  64380. 'trigger': 'SELECT',
  64381. 'menu': 'MENU',
  64382. 'grip': 'GRASP',
  64383. 'thumbstick': 'THUMBSTICK_PRESS',
  64384. 'trackpad': 'TOUCHPAD_PRESS'
  64385. },
  64386. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64387. buttonObservableNames: {
  64388. 'trigger': 'onTriggerStateChangedObservable',
  64389. 'menu': 'onSecondaryButtonStateChangedObservable',
  64390. 'grip': 'onMainButtonStateChangedObservable',
  64391. 'thumbstick': 'onPadStateChangedObservable',
  64392. 'trackpad': 'onTrackpadChangedObservable'
  64393. },
  64394. // A mapping of the axis name to glTF model node name
  64395. // that should be transformed by axis value.
  64396. // This array mirrors the browserGamepad.axes array, such that
  64397. // the mesh corresponding to axis 0 is in this array index 0.
  64398. axisMeshNames: [
  64399. 'THUMBSTICK_X',
  64400. 'THUMBSTICK_Y',
  64401. 'TOUCHPAD_TOUCH_X',
  64402. 'TOUCHPAD_TOUCH_Y'
  64403. ],
  64404. pointingPoseMeshName: 'POINTING_POSE'
  64405. };
  64406. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64407. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64408. _this.trackpad = { x: 0, y: 0 };
  64409. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64410. _this._loadedMeshInfo = null;
  64411. return _this;
  64412. }
  64413. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64414. get: function () {
  64415. return this.onTriggerStateChangedObservable;
  64416. },
  64417. enumerable: true,
  64418. configurable: true
  64419. });
  64420. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64421. get: function () {
  64422. return this.onSecondaryButtonStateChangedObservable;
  64423. },
  64424. enumerable: true,
  64425. configurable: true
  64426. });
  64427. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64428. get: function () {
  64429. return this.onMainButtonStateChangedObservable;
  64430. },
  64431. enumerable: true,
  64432. configurable: true
  64433. });
  64434. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64435. get: function () {
  64436. return this.onPadStateChangedObservable;
  64437. },
  64438. enumerable: true,
  64439. configurable: true
  64440. });
  64441. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64442. get: function () {
  64443. return this.onTrackpadChangedObservable;
  64444. },
  64445. enumerable: true,
  64446. configurable: true
  64447. });
  64448. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  64449. get: function () {
  64450. return this.onTrackpadValuesChangedObservable;
  64451. },
  64452. enumerable: true,
  64453. configurable: true
  64454. });
  64455. /**
  64456. * Called once per frame by the engine.
  64457. */
  64458. WindowsMotionController.prototype.update = function () {
  64459. _super.prototype.update.call(this);
  64460. // Only need to animate axes if there is a loaded mesh
  64461. if (this._loadedMeshInfo) {
  64462. if (this.browserGamepad.axes) {
  64463. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  64464. this.trackpad.x = this.browserGamepad["axes"][2];
  64465. this.trackpad.y = this.browserGamepad["axes"][3];
  64466. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  64467. }
  64468. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  64469. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  64470. }
  64471. }
  64472. }
  64473. };
  64474. /**
  64475. * Called once for each button that changed state since the last frame
  64476. * @param buttonIdx Which button index changed
  64477. * @param state New state of the button
  64478. * @param changes Which properties on the state changed since last frame
  64479. */
  64480. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64481. var buttonName = this._mapping.buttons[buttonIdx];
  64482. if (!buttonName) {
  64483. return;
  64484. }
  64485. // Only emit events for buttons that we know how to map from index to name
  64486. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  64487. if (observable) {
  64488. observable.notifyObservers(state);
  64489. }
  64490. this.lerpButtonTransform(buttonName, state.value);
  64491. };
  64492. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  64493. // If there is no loaded mesh, there is nothing to transform.
  64494. if (!this._loadedMeshInfo) {
  64495. return;
  64496. }
  64497. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  64498. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64499. return;
  64500. }
  64501. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  64502. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  64503. };
  64504. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  64505. if (!this._loadedMeshInfo) {
  64506. return;
  64507. }
  64508. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  64509. if (!meshInfo) {
  64510. return;
  64511. }
  64512. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  64513. return;
  64514. }
  64515. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  64516. var lerpValue = axisValue * 0.5 + 0.5;
  64517. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  64518. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  64519. };
  64520. /**
  64521. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  64522. * @param scene scene in which to add meshes
  64523. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  64524. */
  64525. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  64526. var _this = this;
  64527. if (forceDefault === void 0) { forceDefault = false; }
  64528. var path;
  64529. var filename;
  64530. // Checking if GLB loader is present
  64531. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  64532. // Determine the device specific folder based on the ID suffix
  64533. var device = 'default';
  64534. if (this.id && !forceDefault) {
  64535. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  64536. device = ((match && match[0]) || device);
  64537. }
  64538. // Hand
  64539. if (this.hand === 'left') {
  64540. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  64541. }
  64542. else {
  64543. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  64544. }
  64545. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  64546. }
  64547. else {
  64548. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  64549. path = BABYLON.GenericController.MODEL_BASE_URL;
  64550. filename = BABYLON.GenericController.MODEL_FILENAME;
  64551. }
  64552. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  64553. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  64554. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  64555. if (!_this._loadedMeshInfo) {
  64556. return;
  64557. }
  64558. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  64559. _this.attachToMesh(_this._defaultModel);
  64560. if (meshLoaded) {
  64561. meshLoaded(_this._defaultModel);
  64562. }
  64563. }, null, function (scene, message) {
  64564. BABYLON.Tools.Log(message);
  64565. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  64566. if (!forceDefault) {
  64567. _this.initControllerMesh(scene, meshLoaded, true);
  64568. }
  64569. });
  64570. };
  64571. /**
  64572. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  64573. * can be transformed by button presses and axes values, based on this._mapping.
  64574. *
  64575. * @param scene scene in which the meshes exist
  64576. * @param meshes list of meshes that make up the controller model to process
  64577. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  64578. */
  64579. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  64580. var loadedMeshInfo = null;
  64581. // Create a new mesh to contain the glTF hierarchy
  64582. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  64583. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  64584. var childMesh = null;
  64585. for (var i = 0; i < meshes.length; i++) {
  64586. var mesh = meshes[i];
  64587. if (!mesh.parent) {
  64588. // Exclude controller meshes from picking results
  64589. mesh.isPickable = false;
  64590. // Handle root node, attach to the new parentMesh
  64591. childMesh = mesh;
  64592. break;
  64593. }
  64594. }
  64595. if (childMesh) {
  64596. childMesh.setParent(parentMesh);
  64597. // Create our mesh info. Note that this method will always return non-null.
  64598. loadedMeshInfo = this.createMeshInfo(parentMesh);
  64599. }
  64600. else {
  64601. BABYLON.Tools.Warn('Could not find root node in model file.');
  64602. }
  64603. return loadedMeshInfo;
  64604. };
  64605. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  64606. var loadedMeshInfo = new LoadedMeshInfo();
  64607. var i;
  64608. loadedMeshInfo.rootNode = rootNode;
  64609. // Reset the caches
  64610. loadedMeshInfo.buttonMeshes = {};
  64611. loadedMeshInfo.axisMeshes = {};
  64612. // Button Meshes
  64613. for (i = 0; i < this._mapping.buttons.length; i++) {
  64614. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  64615. if (!buttonMeshName) {
  64616. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  64617. continue;
  64618. }
  64619. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  64620. if (!buttonMesh) {
  64621. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  64622. continue;
  64623. }
  64624. var buttonMeshInfo = {
  64625. index: i,
  64626. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  64627. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  64628. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  64629. };
  64630. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  64631. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  64632. }
  64633. else {
  64634. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  64635. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  64636. '(VALUE: ' + !!buttonMeshInfo.value +
  64637. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  64638. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  64639. ')');
  64640. }
  64641. }
  64642. // Axis Meshes
  64643. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  64644. var axisMeshName = this._mapping.axisMeshNames[i];
  64645. if (!axisMeshName) {
  64646. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  64647. continue;
  64648. }
  64649. var axisMesh = getChildByName(rootNode, axisMeshName);
  64650. if (!axisMesh) {
  64651. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  64652. continue;
  64653. }
  64654. var axisMeshInfo = {
  64655. index: i,
  64656. value: getImmediateChildByName(axisMesh, 'VALUE'),
  64657. min: getImmediateChildByName(axisMesh, 'MIN'),
  64658. max: getImmediateChildByName(axisMesh, 'MAX')
  64659. };
  64660. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  64661. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  64662. }
  64663. else {
  64664. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  64665. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  64666. '(VALUE: ' + !!axisMeshInfo.value +
  64667. ', MIN: ' + !!axisMeshInfo.min +
  64668. ', MAX:' + !!axisMeshInfo.max +
  64669. ')');
  64670. }
  64671. }
  64672. // Pointing Ray
  64673. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  64674. if (!loadedMeshInfo.pointingPoseNode) {
  64675. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  64676. }
  64677. return loadedMeshInfo;
  64678. // Look through all children recursively. This will return null if no mesh exists with the given name.
  64679. function getChildByName(node, name) {
  64680. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  64681. }
  64682. // Look through only immediate children. This will return null if no mesh exists with the given name.
  64683. function getImmediateChildByName(node, name) {
  64684. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  64685. }
  64686. };
  64687. WindowsMotionController.prototype.getForwardRay = function (length) {
  64688. if (length === void 0) { length = 100; }
  64689. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  64690. return _super.prototype.getForwardRay.call(this, length);
  64691. }
  64692. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  64693. var origin = m.getTranslation();
  64694. var forward = new BABYLON.Vector3(0, 0, -1);
  64695. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64696. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64697. return new BABYLON.Ray(origin, direction, length);
  64698. };
  64699. WindowsMotionController.prototype.dispose = function () {
  64700. _super.prototype.dispose.call(this);
  64701. this.onTrackpadChangedObservable.clear();
  64702. };
  64703. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  64704. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  64705. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  64706. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  64707. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  64708. return WindowsMotionController;
  64709. }(BABYLON.WebVRController));
  64710. BABYLON.WindowsMotionController = WindowsMotionController;
  64711. })(BABYLON || (BABYLON = {}));
  64712. //# sourceMappingURL=babylon.windowsMotionController.js.map
  64713. var BABYLON;
  64714. (function (BABYLON) {
  64715. var GearVRController = /** @class */ (function (_super) {
  64716. __extends(GearVRController, _super);
  64717. function GearVRController(vrGamepad) {
  64718. var _this = _super.call(this, vrGamepad) || this;
  64719. _this._buttonIndexToObservableNameMap = [
  64720. 'onTrackpadChangedObservable',
  64721. 'onTriggerStateChangedObservable' // Trigger
  64722. ];
  64723. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  64724. return _this;
  64725. }
  64726. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64727. var _this = this;
  64728. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  64729. _this._defaultModel = newMeshes[1];
  64730. _this.attachToMesh(_this._defaultModel);
  64731. if (meshLoaded) {
  64732. meshLoaded(_this._defaultModel);
  64733. }
  64734. });
  64735. };
  64736. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64737. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  64738. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  64739. // Only emit events for buttons that we know how to map from index to observable
  64740. var observable = this[observableName];
  64741. if (observable) {
  64742. observable.notifyObservers(state);
  64743. }
  64744. }
  64745. };
  64746. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64747. GearVRController.MODEL_FILENAME = 'generic.babylon';
  64748. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  64749. return GearVRController;
  64750. }(BABYLON.WebVRController));
  64751. BABYLON.GearVRController = GearVRController;
  64752. })(BABYLON || (BABYLON = {}));
  64753. //# sourceMappingURL=babylon.gearVRController.js.map
  64754. var BABYLON;
  64755. (function (BABYLON) {
  64756. var FollowCamera = /** @class */ (function (_super) {
  64757. __extends(FollowCamera, _super);
  64758. function FollowCamera(name, position, scene, lockedTarget) {
  64759. if (lockedTarget === void 0) { lockedTarget = null; }
  64760. var _this = _super.call(this, name, position, scene) || this;
  64761. _this.radius = 12;
  64762. _this.rotationOffset = 0;
  64763. _this.heightOffset = 4;
  64764. _this.cameraAcceleration = 0.05;
  64765. _this.maxCameraSpeed = 20;
  64766. _this.lockedTarget = lockedTarget;
  64767. return _this;
  64768. }
  64769. FollowCamera.prototype.getRadians = function (degrees) {
  64770. return degrees * Math.PI / 180;
  64771. };
  64772. FollowCamera.prototype.follow = function (cameraTarget) {
  64773. if (!cameraTarget)
  64774. return;
  64775. var yRotation;
  64776. if (cameraTarget.rotationQuaternion) {
  64777. var rotMatrix = new BABYLON.Matrix();
  64778. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  64779. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  64780. }
  64781. else {
  64782. yRotation = cameraTarget.rotation.y;
  64783. }
  64784. var radians = this.getRadians(this.rotationOffset) + yRotation;
  64785. var targetPosition = cameraTarget.getAbsolutePosition();
  64786. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  64787. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  64788. var dx = targetX - this.position.x;
  64789. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  64790. var dz = (targetZ) - this.position.z;
  64791. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  64792. var vy = dy * this.cameraAcceleration;
  64793. var vz = dz * this.cameraAcceleration * 2;
  64794. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  64795. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64796. }
  64797. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  64798. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64799. }
  64800. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  64801. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  64802. }
  64803. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  64804. this.setTarget(targetPosition);
  64805. };
  64806. FollowCamera.prototype._checkInputs = function () {
  64807. _super.prototype._checkInputs.call(this);
  64808. if (this.lockedTarget) {
  64809. this.follow(this.lockedTarget);
  64810. }
  64811. };
  64812. FollowCamera.prototype.getClassName = function () {
  64813. return "FollowCamera";
  64814. };
  64815. __decorate([
  64816. BABYLON.serialize()
  64817. ], FollowCamera.prototype, "radius", void 0);
  64818. __decorate([
  64819. BABYLON.serialize()
  64820. ], FollowCamera.prototype, "rotationOffset", void 0);
  64821. __decorate([
  64822. BABYLON.serialize()
  64823. ], FollowCamera.prototype, "heightOffset", void 0);
  64824. __decorate([
  64825. BABYLON.serialize()
  64826. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  64827. __decorate([
  64828. BABYLON.serialize()
  64829. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  64830. __decorate([
  64831. BABYLON.serializeAsMeshReference("lockedTargetId")
  64832. ], FollowCamera.prototype, "lockedTarget", void 0);
  64833. return FollowCamera;
  64834. }(BABYLON.TargetCamera));
  64835. BABYLON.FollowCamera = FollowCamera;
  64836. var ArcFollowCamera = /** @class */ (function (_super) {
  64837. __extends(ArcFollowCamera, _super);
  64838. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  64839. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  64840. _this.alpha = alpha;
  64841. _this.beta = beta;
  64842. _this.radius = radius;
  64843. _this.target = target;
  64844. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  64845. _this.follow();
  64846. return _this;
  64847. }
  64848. ArcFollowCamera.prototype.follow = function () {
  64849. if (!this.target) {
  64850. return;
  64851. }
  64852. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  64853. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  64854. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  64855. var targetPosition = this.target.getAbsolutePosition();
  64856. this.position = targetPosition.add(this._cartesianCoordinates);
  64857. this.setTarget(targetPosition);
  64858. };
  64859. ArcFollowCamera.prototype._checkInputs = function () {
  64860. _super.prototype._checkInputs.call(this);
  64861. this.follow();
  64862. };
  64863. ArcFollowCamera.prototype.getClassName = function () {
  64864. return "ArcFollowCamera";
  64865. };
  64866. return ArcFollowCamera;
  64867. }(BABYLON.TargetCamera));
  64868. BABYLON.ArcFollowCamera = ArcFollowCamera;
  64869. })(BABYLON || (BABYLON = {}));
  64870. //# sourceMappingURL=babylon.followCamera.js.map
  64871. var BABYLON;
  64872. (function (BABYLON) {
  64873. // We're mainly based on the logic defined into the FreeCamera code
  64874. var UniversalCamera = /** @class */ (function (_super) {
  64875. __extends(UniversalCamera, _super);
  64876. //-- end properties for backward compatibility for inputs
  64877. function UniversalCamera(name, position, scene) {
  64878. var _this = _super.call(this, name, position, scene) || this;
  64879. _this.inputs.addGamepad();
  64880. return _this;
  64881. }
  64882. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  64883. //-- Begin properties for backward compatibility for inputs
  64884. get: function () {
  64885. var gamepad = this.inputs.attached["gamepad"];
  64886. if (gamepad)
  64887. return gamepad.gamepadAngularSensibility;
  64888. return 0;
  64889. },
  64890. set: function (value) {
  64891. var gamepad = this.inputs.attached["gamepad"];
  64892. if (gamepad)
  64893. gamepad.gamepadAngularSensibility = value;
  64894. },
  64895. enumerable: true,
  64896. configurable: true
  64897. });
  64898. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  64899. get: function () {
  64900. var gamepad = this.inputs.attached["gamepad"];
  64901. if (gamepad)
  64902. return gamepad.gamepadMoveSensibility;
  64903. return 0;
  64904. },
  64905. set: function (value) {
  64906. var gamepad = this.inputs.attached["gamepad"];
  64907. if (gamepad)
  64908. gamepad.gamepadMoveSensibility = value;
  64909. },
  64910. enumerable: true,
  64911. configurable: true
  64912. });
  64913. UniversalCamera.prototype.getClassName = function () {
  64914. return "UniversalCamera";
  64915. };
  64916. return UniversalCamera;
  64917. }(BABYLON.TouchCamera));
  64918. BABYLON.UniversalCamera = UniversalCamera;
  64919. })(BABYLON || (BABYLON = {}));
  64920. //# sourceMappingURL=babylon.universalCamera.js.map
  64921. var BABYLON;
  64922. (function (BABYLON) {
  64923. // We're mainly based on the logic defined into the FreeCamera code
  64924. var GamepadCamera = /** @class */ (function (_super) {
  64925. __extends(GamepadCamera, _super);
  64926. //-- end properties for backward compatibility for inputs
  64927. function GamepadCamera(name, position, scene) {
  64928. return _super.call(this, name, position, scene) || this;
  64929. }
  64930. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  64931. //-- Begin properties for backward compatibility for inputs
  64932. get: function () {
  64933. var gamepad = this.inputs.attached["gamepad"];
  64934. if (gamepad)
  64935. return gamepad.gamepadAngularSensibility;
  64936. return 0;
  64937. },
  64938. set: function (value) {
  64939. var gamepad = this.inputs.attached["gamepad"];
  64940. if (gamepad)
  64941. gamepad.gamepadAngularSensibility = value;
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  64947. get: function () {
  64948. var gamepad = this.inputs.attached["gamepad"];
  64949. if (gamepad)
  64950. return gamepad.gamepadMoveSensibility;
  64951. return 0;
  64952. },
  64953. set: function (value) {
  64954. var gamepad = this.inputs.attached["gamepad"];
  64955. if (gamepad)
  64956. gamepad.gamepadMoveSensibility = value;
  64957. },
  64958. enumerable: true,
  64959. configurable: true
  64960. });
  64961. GamepadCamera.prototype.getClassName = function () {
  64962. return "GamepadCamera";
  64963. };
  64964. return GamepadCamera;
  64965. }(BABYLON.UniversalCamera));
  64966. BABYLON.GamepadCamera = GamepadCamera;
  64967. })(BABYLON || (BABYLON = {}));
  64968. //# sourceMappingURL=babylon.gamepadCamera.js.map
  64969. var BABYLON;
  64970. (function (BABYLON) {
  64971. var PostProcessRenderPipelineManager = /** @class */ (function () {
  64972. function PostProcessRenderPipelineManager() {
  64973. this._renderPipelines = {};
  64974. }
  64975. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  64976. this._renderPipelines[renderPipeline._name] = renderPipeline;
  64977. };
  64978. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  64979. if (unique === void 0) { unique = false; }
  64980. var renderPipeline = this._renderPipelines[renderPipelineName];
  64981. if (!renderPipeline) {
  64982. return;
  64983. }
  64984. renderPipeline._attachCameras(cameras, unique);
  64985. };
  64986. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  64987. var renderPipeline = this._renderPipelines[renderPipelineName];
  64988. if (!renderPipeline) {
  64989. return;
  64990. }
  64991. renderPipeline._detachCameras(cameras);
  64992. };
  64993. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  64994. var renderPipeline = this._renderPipelines[renderPipelineName];
  64995. if (!renderPipeline) {
  64996. return;
  64997. }
  64998. renderPipeline._enableEffect(renderEffectName, cameras);
  64999. };
  65000. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65001. var renderPipeline = this._renderPipelines[renderPipelineName];
  65002. if (!renderPipeline) {
  65003. return;
  65004. }
  65005. renderPipeline._disableEffect(renderEffectName, cameras);
  65006. };
  65007. PostProcessRenderPipelineManager.prototype.update = function () {
  65008. for (var renderPipelineName in this._renderPipelines) {
  65009. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65010. var pipeline = this._renderPipelines[renderPipelineName];
  65011. if (!pipeline.isSupported) {
  65012. pipeline.dispose();
  65013. delete this._renderPipelines[renderPipelineName];
  65014. }
  65015. else {
  65016. pipeline._update();
  65017. }
  65018. }
  65019. }
  65020. };
  65021. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65022. for (var renderPipelineName in this._renderPipelines) {
  65023. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65024. var pipeline = this._renderPipelines[renderPipelineName];
  65025. pipeline._rebuild();
  65026. }
  65027. }
  65028. };
  65029. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65030. for (var renderPipelineName in this._renderPipelines) {
  65031. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65032. var pipeline = this._renderPipelines[renderPipelineName];
  65033. pipeline.dispose();
  65034. }
  65035. }
  65036. };
  65037. return PostProcessRenderPipelineManager;
  65038. }());
  65039. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65040. })(BABYLON || (BABYLON = {}));
  65041. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65042. var BABYLON;
  65043. (function (BABYLON) {
  65044. /**
  65045. * This represents a set of one or more post processes in Babylon.
  65046. * A post process can be used to apply a shader to a texture after it is rendered.
  65047. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65048. */
  65049. var PostProcessRenderEffect = /** @class */ (function () {
  65050. /**
  65051. * Instantiates a post process render effect.
  65052. * A post process can be used to apply a shader to a texture after it is rendered.
  65053. * @param engine The engine the effect is tied to
  65054. * @param name The name of the effect
  65055. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65056. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65057. */
  65058. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65059. this._name = name;
  65060. this._singleInstance = singleInstance || true;
  65061. this._getPostProcesses = getPostProcesses;
  65062. this._cameras = {};
  65063. this._indicesForCamera = {};
  65064. this._postProcesses = {};
  65065. }
  65066. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65067. /**
  65068. * Checks if all the post processes in the effect are supported.
  65069. */
  65070. get: function () {
  65071. for (var index in this._postProcesses) {
  65072. for (var ppIndex in this._postProcesses[index]) {
  65073. if (!this._postProcesses[index][ppIndex].isSupported) {
  65074. return false;
  65075. }
  65076. }
  65077. }
  65078. return true;
  65079. },
  65080. enumerable: true,
  65081. configurable: true
  65082. });
  65083. /**
  65084. * Updates the current state of the effect
  65085. */
  65086. PostProcessRenderEffect.prototype._update = function () {
  65087. };
  65088. /**
  65089. * Attaches the effect on cameras
  65090. * @param cameras The camera to attach to.
  65091. */
  65092. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65093. var _this = this;
  65094. var cameraKey;
  65095. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65096. if (!cams) {
  65097. return;
  65098. }
  65099. for (var i = 0; i < cams.length; i++) {
  65100. var camera = cams[i];
  65101. var cameraName = camera.name;
  65102. if (this._singleInstance) {
  65103. cameraKey = 0;
  65104. }
  65105. else {
  65106. cameraKey = cameraName;
  65107. }
  65108. if (!this._postProcesses[cameraKey]) {
  65109. var postProcess = this._getPostProcesses();
  65110. if (postProcess) {
  65111. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65112. }
  65113. }
  65114. if (!this._indicesForCamera[cameraName]) {
  65115. this._indicesForCamera[cameraName] = [];
  65116. }
  65117. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65118. var index = camera.attachPostProcess(postProcess);
  65119. _this._indicesForCamera[cameraName].push(index);
  65120. });
  65121. if (!this._cameras[cameraName]) {
  65122. this._cameras[cameraName] = camera;
  65123. }
  65124. }
  65125. };
  65126. /**
  65127. * Detatches the effect on cameras
  65128. * @param cameras The camera to detatch from.
  65129. */
  65130. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65131. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65132. if (!cams) {
  65133. return;
  65134. }
  65135. for (var i = 0; i < cams.length; i++) {
  65136. var camera = cams[i];
  65137. var cameraName = camera.name;
  65138. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65139. camera.detachPostProcess(postProcess);
  65140. });
  65141. if (this._cameras[cameraName]) {
  65142. //this._indicesForCamera.splice(index, 1);
  65143. this._cameras[cameraName] = null;
  65144. }
  65145. }
  65146. };
  65147. /**
  65148. * Enables the effect on given cameras
  65149. * @param cameras The camera to enable.
  65150. */
  65151. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65152. var _this = this;
  65153. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65154. if (!cams) {
  65155. return;
  65156. }
  65157. for (var i = 0; i < cams.length; i++) {
  65158. var camera = cams[i];
  65159. var cameraName = camera.name;
  65160. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65161. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65162. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65163. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65164. });
  65165. }
  65166. }
  65167. }
  65168. };
  65169. /**
  65170. * Disables the effect on the given cameras
  65171. * @param cameras The camera to disable.
  65172. */
  65173. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65174. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65175. if (!cams) {
  65176. return;
  65177. }
  65178. for (var i = 0; i < cams.length; i++) {
  65179. var camera = cams[i];
  65180. var cameraName = camera.name;
  65181. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65182. camera.detachPostProcess(postProcess);
  65183. });
  65184. }
  65185. };
  65186. /**
  65187. * Gets a list of the post processes contained in the effect.
  65188. * @param camera The camera to get the post processes on.
  65189. * @returns The list of the post processes in the effect.
  65190. */
  65191. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65192. if (this._singleInstance) {
  65193. return this._postProcesses[0];
  65194. }
  65195. else {
  65196. if (!camera) {
  65197. return null;
  65198. }
  65199. return this._postProcesses[camera.name];
  65200. }
  65201. };
  65202. return PostProcessRenderEffect;
  65203. }());
  65204. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65205. })(BABYLON || (BABYLON = {}));
  65206. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65207. var BABYLON;
  65208. (function (BABYLON) {
  65209. var PostProcessRenderPipeline = /** @class */ (function () {
  65210. function PostProcessRenderPipeline(engine, name) {
  65211. this._name = name;
  65212. this._renderEffects = {};
  65213. this._renderEffectsForIsolatedPass = new Array();
  65214. this._cameras = [];
  65215. }
  65216. PostProcessRenderPipeline.prototype.getClassName = function () {
  65217. return "PostProcessRenderPipeline";
  65218. };
  65219. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65220. get: function () {
  65221. for (var renderEffectName in this._renderEffects) {
  65222. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65223. if (!this._renderEffects[renderEffectName].isSupported) {
  65224. return false;
  65225. }
  65226. }
  65227. }
  65228. return true;
  65229. },
  65230. enumerable: true,
  65231. configurable: true
  65232. });
  65233. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65234. this._renderEffects[renderEffect._name] = renderEffect;
  65235. };
  65236. // private
  65237. PostProcessRenderPipeline.prototype._rebuild = function () {
  65238. };
  65239. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65240. var renderEffects = this._renderEffects[renderEffectName];
  65241. if (!renderEffects) {
  65242. return;
  65243. }
  65244. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65245. };
  65246. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65247. var renderEffects = this._renderEffects[renderEffectName];
  65248. if (!renderEffects) {
  65249. return;
  65250. }
  65251. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65252. };
  65253. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65254. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65255. if (!cams) {
  65256. return;
  65257. }
  65258. var indicesToDelete = [];
  65259. var i;
  65260. for (i = 0; i < cams.length; i++) {
  65261. var camera = cams[i];
  65262. var cameraName = camera.name;
  65263. if (this._cameras.indexOf(camera) === -1) {
  65264. this._cameras[cameraName] = camera;
  65265. }
  65266. else if (unique) {
  65267. indicesToDelete.push(i);
  65268. }
  65269. }
  65270. for (i = 0; i < indicesToDelete.length; i++) {
  65271. cameras.splice(indicesToDelete[i], 1);
  65272. }
  65273. for (var renderEffectName in this._renderEffects) {
  65274. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65275. this._renderEffects[renderEffectName]._attachCameras(cams);
  65276. }
  65277. }
  65278. };
  65279. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65280. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65281. if (!cams) {
  65282. return;
  65283. }
  65284. for (var renderEffectName in this._renderEffects) {
  65285. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65286. this._renderEffects[renderEffectName]._detachCameras(cams);
  65287. }
  65288. }
  65289. for (var i = 0; i < cams.length; i++) {
  65290. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65291. }
  65292. };
  65293. PostProcessRenderPipeline.prototype._update = function () {
  65294. for (var renderEffectName in this._renderEffects) {
  65295. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65296. this._renderEffects[renderEffectName]._update();
  65297. }
  65298. }
  65299. for (var i = 0; i < this._cameras.length; i++) {
  65300. var cameraName = this._cameras[i].name;
  65301. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65302. this._renderEffectsForIsolatedPass[cameraName]._update();
  65303. }
  65304. }
  65305. };
  65306. PostProcessRenderPipeline.prototype._reset = function () {
  65307. this._renderEffects = {};
  65308. this._renderEffectsForIsolatedPass = new Array();
  65309. };
  65310. PostProcessRenderPipeline.prototype.dispose = function () {
  65311. // Must be implemented by children
  65312. };
  65313. __decorate([
  65314. BABYLON.serialize()
  65315. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65316. return PostProcessRenderPipeline;
  65317. }());
  65318. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65319. })(BABYLON || (BABYLON = {}));
  65320. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65321. var BABYLON;
  65322. (function (BABYLON) {
  65323. var DepthRenderer = /** @class */ (function () {
  65324. function DepthRenderer(scene, type) {
  65325. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65326. var _this = this;
  65327. this._scene = scene;
  65328. var engine = scene.getEngine();
  65329. // Render target
  65330. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65331. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65332. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65333. this._depthMap.refreshRate = 1;
  65334. this._depthMap.renderParticles = false;
  65335. this._depthMap.renderList = null;
  65336. // set default depth value to 1.0 (far away)
  65337. this._depthMap.onClearObservable.add(function (engine) {
  65338. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65339. });
  65340. // Custom render function
  65341. var renderSubMesh = function (subMesh) {
  65342. var mesh = subMesh.getRenderingMesh();
  65343. var scene = _this._scene;
  65344. var engine = scene.getEngine();
  65345. var material = subMesh.getMaterial();
  65346. if (!material) {
  65347. return;
  65348. }
  65349. // Culling and reverse (right handed system)
  65350. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65351. // Managing instances
  65352. var batch = mesh._getInstancesRenderList(subMesh._id);
  65353. if (batch.mustReturn) {
  65354. return;
  65355. }
  65356. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65357. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  65358. engine.enableEffect(_this._effect);
  65359. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65360. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65361. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  65362. // Alpha test
  65363. if (material && material.needAlphaTesting()) {
  65364. var alphaTexture = material.getAlphaTestTexture();
  65365. if (alphaTexture) {
  65366. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65367. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65368. }
  65369. }
  65370. // Bones
  65371. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65372. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65373. }
  65374. // Draw
  65375. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65376. }
  65377. };
  65378. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65379. var index;
  65380. if (depthOnlySubMeshes.length) {
  65381. engine.setColorWrite(false);
  65382. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65383. renderSubMesh(depthOnlySubMeshes.data[index]);
  65384. }
  65385. engine.setColorWrite(true);
  65386. }
  65387. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65388. renderSubMesh(opaqueSubMeshes.data[index]);
  65389. }
  65390. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65391. renderSubMesh(alphaTestSubMeshes.data[index]);
  65392. }
  65393. };
  65394. }
  65395. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65396. var material = subMesh.getMaterial();
  65397. if (material.disableDepthWrite) {
  65398. return false;
  65399. }
  65400. var defines = [];
  65401. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65402. var mesh = subMesh.getMesh();
  65403. // Alpha test
  65404. if (material && material.needAlphaTesting()) {
  65405. defines.push("#define ALPHATEST");
  65406. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65407. attribs.push(BABYLON.VertexBuffer.UVKind);
  65408. defines.push("#define UV1");
  65409. }
  65410. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65411. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65412. defines.push("#define UV2");
  65413. }
  65414. }
  65415. // Bones
  65416. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65417. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65418. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65419. if (mesh.numBoneInfluencers > 4) {
  65420. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65421. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65422. }
  65423. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65424. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65425. }
  65426. else {
  65427. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65428. }
  65429. // Instances
  65430. if (useInstances) {
  65431. defines.push("#define INSTANCES");
  65432. attribs.push("world0");
  65433. attribs.push("world1");
  65434. attribs.push("world2");
  65435. attribs.push("world3");
  65436. }
  65437. // Get correct effect
  65438. var join = defines.join("\n");
  65439. if (this._cachedDefines !== join) {
  65440. this._cachedDefines = join;
  65441. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65442. }
  65443. return this._effect.isReady();
  65444. };
  65445. DepthRenderer.prototype.getDepthMap = function () {
  65446. return this._depthMap;
  65447. };
  65448. // Methods
  65449. DepthRenderer.prototype.dispose = function () {
  65450. this._depthMap.dispose();
  65451. };
  65452. return DepthRenderer;
  65453. }());
  65454. BABYLON.DepthRenderer = DepthRenderer;
  65455. })(BABYLON || (BABYLON = {}));
  65456. //# sourceMappingURL=babylon.depthRenderer.js.map
  65457. var BABYLON;
  65458. (function (BABYLON) {
  65459. var SSAORenderingPipeline = /** @class */ (function (_super) {
  65460. __extends(SSAORenderingPipeline, _super);
  65461. /**
  65462. * @constructor
  65463. * @param {string} name - The rendering pipeline name
  65464. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65465. * @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 }
  65466. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65467. */
  65468. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  65469. var _this = _super.call(this, scene.getEngine(), name) || this;
  65470. // Members
  65471. /**
  65472. * The PassPostProcess id in the pipeline that contains the original scene color
  65473. * @type {string}
  65474. */
  65475. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65476. /**
  65477. * The SSAO PostProcess id in the pipeline
  65478. * @type {string}
  65479. */
  65480. _this.SSAORenderEffect = "SSAORenderEffect";
  65481. /**
  65482. * The horizontal blur PostProcess id in the pipeline
  65483. * @type {string}
  65484. */
  65485. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65486. /**
  65487. * The vertical blur PostProcess id in the pipeline
  65488. * @type {string}
  65489. */
  65490. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65491. /**
  65492. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65493. * @type {string}
  65494. */
  65495. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65496. /**
  65497. * The output strength of the SSAO post-process. Default value is 1.0.
  65498. * @type {number}
  65499. */
  65500. _this.totalStrength = 1.0;
  65501. /**
  65502. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  65503. * @type {number}
  65504. */
  65505. _this.radius = 0.0001;
  65506. /**
  65507. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  65508. * Must not be equal to fallOff and superior to fallOff.
  65509. * Default value is 0.975
  65510. * @type {number}
  65511. */
  65512. _this.area = 0.0075;
  65513. /**
  65514. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  65515. * Must not be equal to area and inferior to area.
  65516. * Default value is 0.0
  65517. * @type {number}
  65518. */
  65519. _this.fallOff = 0.000001;
  65520. /**
  65521. * The base color of the SSAO post-process
  65522. * The final result is "base + ssao" between [0, 1]
  65523. * @type {number}
  65524. */
  65525. _this.base = 0.5;
  65526. _this._firstUpdate = true;
  65527. _this._scene = scene;
  65528. // Set up assets
  65529. _this._createRandomTexture();
  65530. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  65531. var ssaoRatio = ratio.ssaoRatio || ratio;
  65532. var combineRatio = ratio.combineRatio || ratio;
  65533. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65534. _this._createSSAOPostProcess(ssaoRatio);
  65535. _this._createBlurPostProcess(ssaoRatio);
  65536. _this._createSSAOCombinePostProcess(combineRatio);
  65537. // Set up pipeline
  65538. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65539. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65540. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65541. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65542. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65543. // Finish
  65544. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65545. if (cameras)
  65546. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65547. return _this;
  65548. }
  65549. // Public Methods
  65550. /**
  65551. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65552. */
  65553. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  65554. if (disableDepthRender === void 0) { disableDepthRender = false; }
  65555. for (var i = 0; i < this._scene.cameras.length; i++) {
  65556. var camera = this._scene.cameras[i];
  65557. this._originalColorPostProcess.dispose(camera);
  65558. this._ssaoPostProcess.dispose(camera);
  65559. this._blurHPostProcess.dispose(camera);
  65560. this._blurVPostProcess.dispose(camera);
  65561. this._ssaoCombinePostProcess.dispose(camera);
  65562. }
  65563. this._randomTexture.dispose();
  65564. if (disableDepthRender)
  65565. this._scene.disableDepthRenderer();
  65566. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65567. _super.prototype.dispose.call(this);
  65568. };
  65569. // Private Methods
  65570. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  65571. var _this = this;
  65572. var size = 16;
  65573. 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);
  65574. 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);
  65575. this._blurHPostProcess.onActivateObservable.add(function () {
  65576. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  65577. _this._blurHPostProcess.kernel = size * dw;
  65578. });
  65579. this._blurVPostProcess.onActivateObservable.add(function () {
  65580. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  65581. _this._blurVPostProcess.kernel = size * dw;
  65582. });
  65583. };
  65584. SSAORenderingPipeline.prototype._rebuild = function () {
  65585. this._firstUpdate = true;
  65586. _super.prototype._rebuild.call(this);
  65587. };
  65588. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65589. var _this = this;
  65590. var numSamples = 16;
  65591. var sampleSphere = [
  65592. 0.5381, 0.1856, -0.4319,
  65593. 0.1379, 0.2486, 0.4430,
  65594. 0.3371, 0.5679, -0.0057,
  65595. -0.6999, -0.0451, -0.0019,
  65596. 0.0689, -0.1598, -0.8547,
  65597. 0.0560, 0.0069, -0.1843,
  65598. -0.0146, 0.1402, 0.0762,
  65599. 0.0100, -0.1924, -0.0344,
  65600. -0.3577, -0.5301, -0.4358,
  65601. -0.3169, 0.1063, 0.0158,
  65602. 0.0103, -0.5869, 0.0046,
  65603. -0.0897, -0.4940, 0.3287,
  65604. 0.7119, -0.0154, -0.0918,
  65605. -0.0533, 0.0596, -0.5411,
  65606. 0.0352, -0.0631, 0.5460,
  65607. -0.4776, 0.2847, -0.0271
  65608. ];
  65609. var samplesFactor = 1.0 / numSamples;
  65610. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  65611. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65612. "area", "fallOff", "base", "range", "viewport"
  65613. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65614. this._ssaoPostProcess.onApply = function (effect) {
  65615. if (_this._firstUpdate) {
  65616. effect.setArray3("sampleSphere", sampleSphere);
  65617. effect.setFloat("samplesFactor", samplesFactor);
  65618. effect.setFloat("randTextureTiles", 4.0);
  65619. }
  65620. effect.setFloat("totalStrength", _this.totalStrength);
  65621. effect.setFloat("radius", _this.radius);
  65622. effect.setFloat("area", _this.area);
  65623. effect.setFloat("fallOff", _this.fallOff);
  65624. effect.setFloat("base", _this.base);
  65625. effect.setTexture("textureSampler", _this._depthTexture);
  65626. effect.setTexture("randomSampler", _this._randomTexture);
  65627. };
  65628. };
  65629. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65630. var _this = this;
  65631. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65632. this._ssaoCombinePostProcess.onApply = function (effect) {
  65633. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65634. };
  65635. };
  65636. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  65637. var size = 512;
  65638. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65639. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65640. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65641. var context = this._randomTexture.getContext();
  65642. var rand = function (min, max) {
  65643. return Math.random() * (max - min) + min;
  65644. };
  65645. var randVector = BABYLON.Vector3.Zero();
  65646. for (var x = 0; x < size; x++) {
  65647. for (var y = 0; y < size; y++) {
  65648. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  65649. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  65650. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  65651. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65652. context.fillRect(x, y, 1, 1);
  65653. }
  65654. }
  65655. this._randomTexture.update(false);
  65656. };
  65657. __decorate([
  65658. BABYLON.serialize()
  65659. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  65660. __decorate([
  65661. BABYLON.serialize()
  65662. ], SSAORenderingPipeline.prototype, "radius", void 0);
  65663. __decorate([
  65664. BABYLON.serialize()
  65665. ], SSAORenderingPipeline.prototype, "area", void 0);
  65666. __decorate([
  65667. BABYLON.serialize()
  65668. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  65669. __decorate([
  65670. BABYLON.serialize()
  65671. ], SSAORenderingPipeline.prototype, "base", void 0);
  65672. return SSAORenderingPipeline;
  65673. }(BABYLON.PostProcessRenderPipeline));
  65674. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  65675. })(BABYLON || (BABYLON = {}));
  65676. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  65677. var BABYLON;
  65678. (function (BABYLON) {
  65679. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  65680. __extends(SSAO2RenderingPipeline, _super);
  65681. /**
  65682. * @constructor
  65683. * @param {string} name - The rendering pipeline name
  65684. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  65685. * @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 }
  65686. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  65687. */
  65688. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  65689. var _this = _super.call(this, scene.getEngine(), name) || this;
  65690. // Members
  65691. /**
  65692. * The PassPostProcess id in the pipeline that contains the original scene color
  65693. * @type {string}
  65694. */
  65695. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  65696. /**
  65697. * The SSAO PostProcess id in the pipeline
  65698. * @type {string}
  65699. */
  65700. _this.SSAORenderEffect = "SSAORenderEffect";
  65701. /**
  65702. * The horizontal blur PostProcess id in the pipeline
  65703. * @type {string}
  65704. */
  65705. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  65706. /**
  65707. * The vertical blur PostProcess id in the pipeline
  65708. * @type {string}
  65709. */
  65710. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  65711. /**
  65712. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  65713. * @type {string}
  65714. */
  65715. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  65716. /**
  65717. * The output strength of the SSAO post-process. Default value is 1.0.
  65718. * @type {number}
  65719. */
  65720. _this.totalStrength = 1.0;
  65721. /**
  65722. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  65723. * @type {number}
  65724. */
  65725. _this.maxZ = 100.0;
  65726. /**
  65727. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  65728. * @type {number}
  65729. */
  65730. _this.minZAspect = 0.2;
  65731. /**
  65732. * Number of samples used for the SSAO calculations. Default value is 8
  65733. * @type {number}
  65734. */
  65735. _this._samples = 8;
  65736. /**
  65737. * Are we using bilateral blur ?
  65738. * @type {boolean}
  65739. */
  65740. _this._expensiveBlur = true;
  65741. /**
  65742. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  65743. * @type {number}
  65744. */
  65745. _this.radius = 2.0;
  65746. /**
  65747. * The base color of the SSAO post-process
  65748. * The final result is "base + ssao" between [0, 1]
  65749. * @type {number}
  65750. */
  65751. _this.base = 0.1;
  65752. _this._firstUpdate = true;
  65753. _this._scene = scene;
  65754. if (!_this.isSupported) {
  65755. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  65756. return _this;
  65757. }
  65758. var ssaoRatio = ratio.ssaoRatio || ratio;
  65759. var blurRatio = ratio.blurRatio || ratio;
  65760. // Set up assets
  65761. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  65762. _this._createRandomTexture();
  65763. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  65764. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  65765. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  65766. _this._createSSAOPostProcess(1.0);
  65767. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  65768. _this._createSSAOCombinePostProcess(blurRatio);
  65769. // Set up pipeline
  65770. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  65771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  65772. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  65773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  65774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  65775. // Finish
  65776. scene.postProcessRenderPipelineManager.addPipeline(_this);
  65777. if (cameras)
  65778. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  65779. return _this;
  65780. }
  65781. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  65782. get: function () {
  65783. return this._samples;
  65784. },
  65785. set: function (n) {
  65786. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  65787. this._samples = n;
  65788. this._sampleSphere = this._generateHemisphere();
  65789. this._firstUpdate = true;
  65790. },
  65791. enumerable: true,
  65792. configurable: true
  65793. });
  65794. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  65795. get: function () {
  65796. return this._expensiveBlur;
  65797. },
  65798. set: function (b) {
  65799. 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"]);
  65800. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  65801. this._expensiveBlur = b;
  65802. this._firstUpdate = true;
  65803. },
  65804. enumerable: true,
  65805. configurable: true
  65806. });
  65807. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  65808. /**
  65809. * Support test.
  65810. * @type {boolean}
  65811. */
  65812. get: function () {
  65813. var engine = BABYLON.Engine.LastCreatedEngine;
  65814. if (!engine) {
  65815. return false;
  65816. }
  65817. return engine.getCaps().drawBuffersExtension;
  65818. },
  65819. enumerable: true,
  65820. configurable: true
  65821. });
  65822. // Public Methods
  65823. /**
  65824. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  65825. */
  65826. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  65827. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  65828. for (var i = 0; i < this._scene.cameras.length; i++) {
  65829. var camera = this._scene.cameras[i];
  65830. this._originalColorPostProcess.dispose(camera);
  65831. this._ssaoPostProcess.dispose(camera);
  65832. this._blurHPostProcess.dispose(camera);
  65833. this._blurVPostProcess.dispose(camera);
  65834. this._ssaoCombinePostProcess.dispose(camera);
  65835. }
  65836. this._randomTexture.dispose();
  65837. if (disableGeometryBufferRenderer)
  65838. this._scene.disableGeometryBufferRenderer();
  65839. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  65840. _super.prototype.dispose.call(this);
  65841. };
  65842. // Private Methods
  65843. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  65844. var _this = this;
  65845. this._samplerOffsets = [];
  65846. var expensive = this.expensiveBlur;
  65847. for (var i = -8; i < 8; i++) {
  65848. this._samplerOffsets.push(i * 2 + 0.5);
  65849. }
  65850. 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");
  65851. this._blurHPostProcess.onApply = function (effect) {
  65852. if (!_this._scene.activeCamera) {
  65853. return;
  65854. }
  65855. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  65856. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65857. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65858. effect.setFloat("radius", _this.radius);
  65859. effect.setTexture("depthSampler", _this._depthTexture);
  65860. if (_this._firstUpdate) {
  65861. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65862. }
  65863. };
  65864. 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");
  65865. this._blurVPostProcess.onApply = function (effect) {
  65866. if (!_this._scene.activeCamera) {
  65867. return;
  65868. }
  65869. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  65870. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65871. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65872. effect.setFloat("radius", _this.radius);
  65873. effect.setTexture("depthSampler", _this._depthTexture);
  65874. if (_this._firstUpdate) {
  65875. effect.setArray("samplerOffsets", _this._samplerOffsets);
  65876. _this._firstUpdate = false;
  65877. }
  65878. };
  65879. };
  65880. SSAO2RenderingPipeline.prototype._rebuild = function () {
  65881. this._firstUpdate = true;
  65882. _super.prototype._rebuild.call(this);
  65883. };
  65884. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  65885. var numSamples = this.samples;
  65886. var result = [];
  65887. var vector, scale;
  65888. var rand = function (min, max) {
  65889. return Math.random() * (max - min) + min;
  65890. };
  65891. var i = 0;
  65892. while (i < numSamples) {
  65893. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  65894. vector.normalize();
  65895. scale = i / numSamples;
  65896. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  65897. vector.scaleInPlace(scale);
  65898. result.push(vector.x, vector.y, vector.z);
  65899. i++;
  65900. }
  65901. return result;
  65902. };
  65903. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  65904. var _this = this;
  65905. var numSamples = this.samples;
  65906. this._sampleSphere = this._generateHemisphere();
  65907. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  65908. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  65909. "base", "range", "projection", "near", "far", "texelSize",
  65910. "xViewport", "yViewport", "maxZ", "minZAspect"
  65911. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  65912. this._ssaoPostProcess.onApply = function (effect) {
  65913. if (_this._firstUpdate) {
  65914. effect.setArray3("sampleSphere", _this._sampleSphere);
  65915. effect.setFloat("randTextureTiles", 4.0);
  65916. }
  65917. if (!_this._scene.activeCamera) {
  65918. return;
  65919. }
  65920. effect.setFloat("samplesFactor", 1 / _this.samples);
  65921. effect.setFloat("totalStrength", _this.totalStrength);
  65922. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  65923. effect.setFloat("radius", _this.radius);
  65924. effect.setFloat("maxZ", _this.maxZ);
  65925. effect.setFloat("minZAspect", _this.minZAspect);
  65926. effect.setFloat("base", _this.base);
  65927. effect.setFloat("near", _this._scene.activeCamera.minZ);
  65928. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  65929. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  65930. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  65931. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  65932. effect.setTexture("textureSampler", _this._depthTexture);
  65933. effect.setTexture("normalSampler", _this._normalTexture);
  65934. effect.setTexture("randomSampler", _this._randomTexture);
  65935. };
  65936. };
  65937. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  65938. var _this = this;
  65939. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  65940. this._ssaoCombinePostProcess.onApply = function (effect) {
  65941. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  65942. };
  65943. };
  65944. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  65945. var size = 512;
  65946. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  65947. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65948. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65949. var context = this._randomTexture.getContext();
  65950. var rand = function (min, max) {
  65951. return Math.random() * (max - min) + min;
  65952. };
  65953. var randVector = BABYLON.Vector3.Zero();
  65954. for (var x = 0; x < size; x++) {
  65955. for (var y = 0; y < size; y++) {
  65956. randVector.x = rand(0.0, 1.0);
  65957. randVector.y = rand(0.0, 1.0);
  65958. randVector.z = 0.0;
  65959. randVector.normalize();
  65960. randVector.scaleInPlace(255);
  65961. randVector.x = Math.floor(randVector.x);
  65962. randVector.y = Math.floor(randVector.y);
  65963. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  65964. context.fillRect(x, y, 1, 1);
  65965. }
  65966. }
  65967. this._randomTexture.update(false);
  65968. };
  65969. __decorate([
  65970. BABYLON.serialize()
  65971. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  65972. __decorate([
  65973. BABYLON.serialize()
  65974. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  65975. __decorate([
  65976. BABYLON.serialize()
  65977. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  65978. __decorate([
  65979. BABYLON.serialize("samples")
  65980. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  65981. __decorate([
  65982. BABYLON.serialize("expensiveBlur")
  65983. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  65984. __decorate([
  65985. BABYLON.serialize()
  65986. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  65987. __decorate([
  65988. BABYLON.serialize()
  65989. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  65990. return SSAO2RenderingPipeline;
  65991. }(BABYLON.PostProcessRenderPipeline));
  65992. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  65993. })(BABYLON || (BABYLON = {}));
  65994. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  65995. // BABYLON.JS Chromatic Aberration GLSL Shader
  65996. // Author: Olivier Guyot
  65997. // Separates very slightly R, G and B colors on the edges of the screen
  65998. // Inspired by Francois Tarlier & Martins Upitis
  65999. var BABYLON;
  66000. (function (BABYLON) {
  66001. var LensRenderingPipeline = /** @class */ (function (_super) {
  66002. __extends(LensRenderingPipeline, _super);
  66003. /**
  66004. * @constructor
  66005. *
  66006. * Effect parameters are as follow:
  66007. * {
  66008. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66009. * edge_blur: number; // from 0 to x (1 for realism)
  66010. * distortion: number; // from 0 to x (1 for realism)
  66011. * grain_amount: number; // from 0 to 1
  66012. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66013. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66014. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66015. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66016. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66017. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66018. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66019. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66020. * }
  66021. * Note: if an effect parameter is unset, effect is disabled
  66022. *
  66023. * @param {string} name - The rendering pipeline name
  66024. * @param {object} parameters - An object containing all parameters (see above)
  66025. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66026. * @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)
  66027. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66028. */
  66029. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66030. if (ratio === void 0) { ratio = 1.0; }
  66031. var _this = _super.call(this, scene.getEngine(), name) || this;
  66032. // Lens effects can be of the following:
  66033. // - chromatic aberration (slight shift of RGB colors)
  66034. // - blur on the edge of the lens
  66035. // - lens distortion
  66036. // - depth-of-field blur & highlights enhancing
  66037. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66038. // - grain effect (noise or custom texture)
  66039. // Two additional texture samplers are needed:
  66040. // - depth map (for depth-of-field)
  66041. // - grain texture
  66042. /**
  66043. * The chromatic aberration PostProcess id in the pipeline
  66044. * @type {string}
  66045. */
  66046. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66047. /**
  66048. * The highlights enhancing PostProcess id in the pipeline
  66049. * @type {string}
  66050. */
  66051. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66052. /**
  66053. * The depth-of-field PostProcess id in the pipeline
  66054. * @type {string}
  66055. */
  66056. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66057. _this._scene = scene;
  66058. // Fetch texture samplers
  66059. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66060. if (parameters.grain_texture) {
  66061. _this._grainTexture = parameters.grain_texture;
  66062. }
  66063. else {
  66064. _this._createGrainTexture();
  66065. }
  66066. // save parameters
  66067. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66068. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66069. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66070. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66071. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66072. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66073. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66074. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66075. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66076. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66077. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66078. // Create effects
  66079. _this._createChromaticAberrationPostProcess(ratio);
  66080. _this._createHighlightsPostProcess(ratio);
  66081. _this._createDepthOfFieldPostProcess(ratio / 4);
  66082. // Set up pipeline
  66083. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66084. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66085. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66086. if (_this._highlightsGain === -1) {
  66087. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66088. }
  66089. // Finish
  66090. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66091. if (cameras) {
  66092. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66093. }
  66094. return _this;
  66095. }
  66096. // public methods (self explanatory)
  66097. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66098. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66099. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66100. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66101. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66102. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66103. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66104. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66105. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66106. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66107. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66108. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66109. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66110. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66111. };
  66112. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66113. this._highlightsPostProcess.updateEffect();
  66114. };
  66115. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66116. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66117. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66118. this._highlightsGain = amount;
  66119. };
  66120. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66121. if (this._highlightsGain === -1) {
  66122. this._highlightsGain = 1.0;
  66123. }
  66124. this._highlightsThreshold = amount;
  66125. };
  66126. LensRenderingPipeline.prototype.disableHighlights = function () {
  66127. this._highlightsGain = -1;
  66128. };
  66129. /**
  66130. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66131. */
  66132. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66133. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66134. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66135. this._chromaticAberrationPostProcess = null;
  66136. this._highlightsPostProcess = null;
  66137. this._depthOfFieldPostProcess = null;
  66138. this._grainTexture.dispose();
  66139. if (disableDepthRender)
  66140. this._scene.disableDepthRenderer();
  66141. };
  66142. // colors shifting and distortion
  66143. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66144. var _this = this;
  66145. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66146. [], // samplers
  66147. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66148. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66149. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66150. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66151. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66152. };
  66153. };
  66154. // highlights enhancing
  66155. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66156. var _this = this;
  66157. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66158. [], // samplers
  66159. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66160. this._highlightsPostProcess.onApply = function (effect) {
  66161. effect.setFloat('gain', _this._highlightsGain);
  66162. effect.setFloat('threshold', _this._highlightsThreshold);
  66163. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66164. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66165. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66166. };
  66167. };
  66168. // colors shifting and distortion
  66169. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66170. var _this = this;
  66171. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66172. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66173. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66174. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66175. this._depthOfFieldPostProcess.onApply = function (effect) {
  66176. effect.setTexture("depthSampler", _this._depthTexture);
  66177. effect.setTexture("grainSampler", _this._grainTexture);
  66178. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66179. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66180. effect.setFloat('grain_amount', _this._grainAmount);
  66181. effect.setBool('blur_noise', _this._blurNoise);
  66182. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66183. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66184. effect.setFloat('distortion', _this._distortion);
  66185. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66186. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66187. effect.setFloat('aperture', _this._dofAperture);
  66188. effect.setFloat('darken', _this._dofDarken);
  66189. effect.setFloat('edge_blur', _this._edgeBlur);
  66190. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66191. if (_this._scene.activeCamera) {
  66192. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66193. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66194. }
  66195. };
  66196. };
  66197. // creates a black and white random noise texture, 512x512
  66198. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66199. var size = 512;
  66200. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66201. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66202. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66203. var context = this._grainTexture.getContext();
  66204. var rand = function (min, max) {
  66205. return Math.random() * (max - min) + min;
  66206. };
  66207. var value;
  66208. for (var x = 0; x < size; x++) {
  66209. for (var y = 0; y < size; y++) {
  66210. value = Math.floor(rand(0.42, 0.58) * 255);
  66211. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66212. context.fillRect(x, y, 1, 1);
  66213. }
  66214. }
  66215. this._grainTexture.update(false);
  66216. };
  66217. return LensRenderingPipeline;
  66218. }(BABYLON.PostProcessRenderPipeline));
  66219. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66220. })(BABYLON || (BABYLON = {}));
  66221. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66222. var BABYLON;
  66223. (function (BABYLON) {
  66224. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66225. __extends(StandardRenderingPipeline, _super);
  66226. /**
  66227. * @constructor
  66228. * @param {string} name - The rendering pipeline name
  66229. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66230. * @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)
  66231. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66232. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66233. */
  66234. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66235. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66236. var _this = _super.call(this, scene.getEngine(), name) || this;
  66237. _this.downSampleX4PostProcess = null;
  66238. _this.brightPassPostProcess = null;
  66239. _this.blurHPostProcesses = [];
  66240. _this.blurVPostProcesses = [];
  66241. _this.textureAdderPostProcess = null;
  66242. _this.volumetricLightPostProcess = null;
  66243. _this.volumetricLightSmoothXPostProcess = null;
  66244. _this.volumetricLightSmoothYPostProcess = null;
  66245. _this.volumetricLightMergePostProces = null;
  66246. _this.volumetricLightFinalPostProcess = null;
  66247. _this.luminancePostProcess = null;
  66248. _this.luminanceDownSamplePostProcesses = [];
  66249. _this.hdrPostProcess = null;
  66250. _this.textureAdderFinalPostProcess = null;
  66251. _this.lensFlareFinalPostProcess = null;
  66252. _this.hdrFinalPostProcess = null;
  66253. _this.lensFlarePostProcess = null;
  66254. _this.lensFlareComposePostProcess = null;
  66255. _this.motionBlurPostProcess = null;
  66256. _this.depthOfFieldPostProcess = null;
  66257. // Values
  66258. _this.brightThreshold = 1.0;
  66259. _this.blurWidth = 512.0;
  66260. _this.horizontalBlur = false;
  66261. _this.exposure = 1.0;
  66262. _this.lensTexture = null;
  66263. _this.volumetricLightCoefficient = 0.2;
  66264. _this.volumetricLightPower = 4.0;
  66265. _this.volumetricLightBlurScale = 64.0;
  66266. _this.sourceLight = null;
  66267. _this.hdrMinimumLuminance = 1.0;
  66268. _this.hdrDecreaseRate = 0.5;
  66269. _this.hdrIncreaseRate = 0.5;
  66270. _this.lensColorTexture = null;
  66271. _this.lensFlareStrength = 20.0;
  66272. _this.lensFlareGhostDispersal = 1.4;
  66273. _this.lensFlareHaloWidth = 0.7;
  66274. _this.lensFlareDistortionStrength = 16.0;
  66275. _this.lensStarTexture = null;
  66276. _this.lensFlareDirtTexture = null;
  66277. _this.depthOfFieldDistance = 10.0;
  66278. _this.depthOfFieldBlurWidth = 64.0;
  66279. _this.motionStrength = 1.0;
  66280. // IAnimatable
  66281. _this.animations = [];
  66282. _this._currentDepthOfFieldSource = null;
  66283. _this._hdrCurrentLuminance = 1.0;
  66284. // Getters and setters
  66285. _this._bloomEnabled = true;
  66286. _this._depthOfFieldEnabled = false;
  66287. _this._vlsEnabled = false;
  66288. _this._lensFlareEnabled = false;
  66289. _this._hdrEnabled = false;
  66290. _this._motionBlurEnabled = false;
  66291. _this._motionBlurSamples = 64.0;
  66292. _this._volumetricLightStepsCount = 50.0;
  66293. _this._cameras = cameras || [];
  66294. // Initialize
  66295. _this._scene = scene;
  66296. _this._basePostProcess = originalPostProcess;
  66297. _this._ratio = ratio;
  66298. // Misc
  66299. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66300. // Finish
  66301. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66302. _this._buildPipeline();
  66303. return _this;
  66304. }
  66305. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66306. get: function () {
  66307. return this._bloomEnabled;
  66308. },
  66309. set: function (enabled) {
  66310. if (this._bloomEnabled === enabled) {
  66311. return;
  66312. }
  66313. this._bloomEnabled = enabled;
  66314. this._buildPipeline();
  66315. },
  66316. enumerable: true,
  66317. configurable: true
  66318. });
  66319. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66320. get: function () {
  66321. return this._depthOfFieldEnabled;
  66322. },
  66323. set: function (enabled) {
  66324. if (this._depthOfFieldEnabled === enabled) {
  66325. return;
  66326. }
  66327. this._depthOfFieldEnabled = enabled;
  66328. this._buildPipeline();
  66329. },
  66330. enumerable: true,
  66331. configurable: true
  66332. });
  66333. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66334. get: function () {
  66335. return this._lensFlareEnabled;
  66336. },
  66337. set: function (enabled) {
  66338. if (this._lensFlareEnabled === enabled) {
  66339. return;
  66340. }
  66341. this._lensFlareEnabled = enabled;
  66342. this._buildPipeline();
  66343. },
  66344. enumerable: true,
  66345. configurable: true
  66346. });
  66347. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66348. get: function () {
  66349. return this._hdrEnabled;
  66350. },
  66351. set: function (enabled) {
  66352. if (this._hdrEnabled === enabled) {
  66353. return;
  66354. }
  66355. this._hdrEnabled = enabled;
  66356. this._buildPipeline();
  66357. },
  66358. enumerable: true,
  66359. configurable: true
  66360. });
  66361. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66362. get: function () {
  66363. return this._vlsEnabled;
  66364. },
  66365. set: function (enabled) {
  66366. if (this._vlsEnabled === enabled) {
  66367. return;
  66368. }
  66369. if (enabled) {
  66370. var geometry = this._scene.enableGeometryBufferRenderer();
  66371. if (!geometry) {
  66372. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66373. return;
  66374. }
  66375. }
  66376. this._vlsEnabled = enabled;
  66377. this._buildPipeline();
  66378. },
  66379. enumerable: true,
  66380. configurable: true
  66381. });
  66382. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66383. get: function () {
  66384. return this._motionBlurEnabled;
  66385. },
  66386. set: function (enabled) {
  66387. if (this._motionBlurEnabled === enabled) {
  66388. return;
  66389. }
  66390. this._motionBlurEnabled = enabled;
  66391. this._buildPipeline();
  66392. },
  66393. enumerable: true,
  66394. configurable: true
  66395. });
  66396. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66397. get: function () {
  66398. return this._volumetricLightStepsCount;
  66399. },
  66400. set: function (count) {
  66401. if (this.volumetricLightPostProcess) {
  66402. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66403. }
  66404. this._volumetricLightStepsCount = count;
  66405. },
  66406. enumerable: true,
  66407. configurable: true
  66408. });
  66409. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66410. get: function () {
  66411. return this._motionBlurSamples;
  66412. },
  66413. set: function (samples) {
  66414. if (this.motionBlurPostProcess) {
  66415. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66416. }
  66417. this._motionBlurSamples = samples;
  66418. },
  66419. enumerable: true,
  66420. configurable: true
  66421. });
  66422. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66423. var _this = this;
  66424. var ratio = this._ratio;
  66425. var scene = this._scene;
  66426. this._disposePostProcesses();
  66427. this._reset();
  66428. // Create pass post-process
  66429. if (!this._basePostProcess) {
  66430. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66431. this.originalPostProcess.onApply = function (effect) {
  66432. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66433. };
  66434. }
  66435. else {
  66436. this.originalPostProcess = this._basePostProcess;
  66437. }
  66438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66439. this._currentDepthOfFieldSource = this.originalPostProcess;
  66440. if (this._vlsEnabled) {
  66441. // Create volumetric light
  66442. this._createVolumetricLightPostProcess(scene, ratio);
  66443. // Create volumetric light final post-process
  66444. 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);
  66445. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66446. }
  66447. if (this._bloomEnabled) {
  66448. // Create down sample X4 post-process
  66449. this._createDownSampleX4PostProcess(scene, ratio / 2);
  66450. // Create bright pass post-process
  66451. this._createBrightPassPostProcess(scene, ratio / 2);
  66452. // Create gaussian blur post-processes (down sampling blurs)
  66453. this._createBlurPostProcesses(scene, ratio / 4, 1);
  66454. // Create texture adder post-process
  66455. this._createTextureAdderPostProcess(scene, ratio);
  66456. // Create depth-of-field source post-process
  66457. 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);
  66458. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  66459. }
  66460. if (this._lensFlareEnabled) {
  66461. // Create lens flare post-process
  66462. this._createLensFlarePostProcess(scene, ratio);
  66463. // Create depth-of-field source post-process post lens-flare and disable it now
  66464. 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);
  66465. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  66466. }
  66467. if (this._hdrEnabled) {
  66468. // Create luminance
  66469. this._createLuminancePostProcesses(scene, this._floatTextureType);
  66470. // Create HDR
  66471. this._createHdrPostProcess(scene, ratio);
  66472. // Create depth-of-field source post-process post hdr and disable it now
  66473. 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);
  66474. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  66475. }
  66476. if (this._depthOfFieldEnabled) {
  66477. // Create gaussian blur used by depth-of-field
  66478. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  66479. // Create depth-of-field post-process
  66480. this._createDepthOfFieldPostProcess(scene, ratio);
  66481. }
  66482. if (this._motionBlurEnabled) {
  66483. // Create motion blur post-process
  66484. this._createMotionBlurPostProcess(scene, ratio);
  66485. }
  66486. if (this._cameras !== null) {
  66487. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  66488. }
  66489. };
  66490. // Down Sample X4 Post-Processs
  66491. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  66492. var _this = this;
  66493. var downSampleX4Offsets = new Array(32);
  66494. 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);
  66495. this.downSampleX4PostProcess.onApply = function (effect) {
  66496. var id = 0;
  66497. var width = _this.downSampleX4PostProcess.width;
  66498. var height = _this.downSampleX4PostProcess.height;
  66499. for (var i = -2; i < 2; i++) {
  66500. for (var j = -2; j < 2; j++) {
  66501. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  66502. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  66503. id += 2;
  66504. }
  66505. }
  66506. effect.setArray2("dsOffsets", downSampleX4Offsets);
  66507. };
  66508. // Add to pipeline
  66509. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  66510. };
  66511. // Brightpass Post-Process
  66512. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  66513. var _this = this;
  66514. var brightOffsets = new Array(8);
  66515. 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);
  66516. this.brightPassPostProcess.onApply = function (effect) {
  66517. var sU = (1.0 / _this.brightPassPostProcess.width);
  66518. var sV = (1.0 / _this.brightPassPostProcess.height);
  66519. brightOffsets[0] = -0.5 * sU;
  66520. brightOffsets[1] = 0.5 * sV;
  66521. brightOffsets[2] = 0.5 * sU;
  66522. brightOffsets[3] = 0.5 * sV;
  66523. brightOffsets[4] = -0.5 * sU;
  66524. brightOffsets[5] = -0.5 * sV;
  66525. brightOffsets[6] = 0.5 * sU;
  66526. brightOffsets[7] = -0.5 * sV;
  66527. effect.setArray2("dsOffsets", brightOffsets);
  66528. effect.setFloat("brightThreshold", _this.brightThreshold);
  66529. };
  66530. // Add to pipeline
  66531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  66532. };
  66533. // Create blur H&V post-processes
  66534. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  66535. var _this = this;
  66536. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  66537. var engine = scene.getEngine();
  66538. 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);
  66539. 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);
  66540. blurX.onActivateObservable.add(function () {
  66541. var dw = blurX.width / engine.getRenderWidth();
  66542. blurX.kernel = _this[blurWidthKey] * dw;
  66543. });
  66544. blurY.onActivateObservable.add(function () {
  66545. var dw = blurY.height / engine.getRenderHeight();
  66546. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  66547. });
  66548. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  66549. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  66550. this.blurHPostProcesses.push(blurX);
  66551. this.blurVPostProcesses.push(blurY);
  66552. };
  66553. // Create texture adder post-process
  66554. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  66555. var _this = this;
  66556. 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);
  66557. this.textureAdderPostProcess.onApply = function (effect) {
  66558. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  66559. effect.setTexture("lensSampler", _this.lensTexture);
  66560. effect.setFloat("exposure", _this.exposure);
  66561. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  66562. };
  66563. // Add to pipeline
  66564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  66565. };
  66566. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  66567. var _this = this;
  66568. var geometryRenderer = scene.enableGeometryBufferRenderer();
  66569. geometryRenderer.enablePosition = true;
  66570. var geometry = geometryRenderer.getGBuffer();
  66571. // Base post-process
  66572. 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));
  66573. var depthValues = BABYLON.Vector2.Zero();
  66574. this.volumetricLightPostProcess.onApply = function (effect) {
  66575. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  66576. var generator = _this.sourceLight.getShadowGenerator();
  66577. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  66578. effect.setTexture("positionSampler", geometry.textures[2]);
  66579. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  66580. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  66581. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  66582. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  66583. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  66584. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  66585. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  66586. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  66587. effect.setVector2("depthValues", depthValues);
  66588. }
  66589. };
  66590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  66591. // Smooth
  66592. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  66593. // Merge
  66594. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  66595. this.volumetricLightMergePostProces.onApply = function (effect) {
  66596. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  66597. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  66598. };
  66599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  66600. };
  66601. // Create luminance
  66602. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  66603. var _this = this;
  66604. // Create luminance
  66605. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  66606. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  66607. var offsets = [];
  66608. this.luminancePostProcess.onApply = function (effect) {
  66609. var sU = (1.0 / _this.luminancePostProcess.width);
  66610. var sV = (1.0 / _this.luminancePostProcess.height);
  66611. offsets[0] = -0.5 * sU;
  66612. offsets[1] = 0.5 * sV;
  66613. offsets[2] = 0.5 * sU;
  66614. offsets[3] = 0.5 * sV;
  66615. offsets[4] = -0.5 * sU;
  66616. offsets[5] = -0.5 * sV;
  66617. offsets[6] = 0.5 * sU;
  66618. offsets[7] = -0.5 * sV;
  66619. effect.setArray2("lumOffsets", offsets);
  66620. };
  66621. // Add to pipeline
  66622. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  66623. // Create down sample luminance
  66624. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  66625. var size = Math.pow(3, i);
  66626. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  66627. if (i === 0) {
  66628. defines += "#define FINAL_DOWN_SAMPLER";
  66629. }
  66630. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  66631. this.luminanceDownSamplePostProcesses.push(postProcess);
  66632. }
  66633. // Create callbacks and add effects
  66634. var lastLuminance = this.luminancePostProcess;
  66635. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  66636. var downSampleOffsets = new Array(18);
  66637. pp.onApply = function (effect) {
  66638. if (!lastLuminance) {
  66639. return;
  66640. }
  66641. var id = 0;
  66642. for (var x = -1; x < 2; x++) {
  66643. for (var y = -1; y < 2; y++) {
  66644. downSampleOffsets[id] = x / lastLuminance.width;
  66645. downSampleOffsets[id + 1] = y / lastLuminance.height;
  66646. id += 2;
  66647. }
  66648. }
  66649. effect.setArray2("dsOffsets", downSampleOffsets);
  66650. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  66651. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66652. lastLuminance = _this.luminancePostProcess;
  66653. }
  66654. else {
  66655. lastLuminance = pp;
  66656. }
  66657. };
  66658. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  66659. pp.onAfterRender = function (effect) {
  66660. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  66661. 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);
  66662. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  66663. };
  66664. }
  66665. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  66666. });
  66667. };
  66668. // Create HDR post-process
  66669. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  66670. var _this = this;
  66671. 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);
  66672. var outputLiminance = 1;
  66673. var time = 0;
  66674. var lastTime = 0;
  66675. this.hdrPostProcess.onApply = function (effect) {
  66676. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  66677. time += scene.getEngine().getDeltaTime();
  66678. if (outputLiminance < 0) {
  66679. outputLiminance = _this._hdrCurrentLuminance;
  66680. }
  66681. else {
  66682. var dt = (lastTime - time) / 1000.0;
  66683. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  66684. outputLiminance += _this.hdrDecreaseRate * dt;
  66685. }
  66686. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  66687. outputLiminance -= _this.hdrIncreaseRate * dt;
  66688. }
  66689. else {
  66690. outputLiminance = _this._hdrCurrentLuminance;
  66691. }
  66692. }
  66693. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  66694. effect.setFloat("averageLuminance", outputLiminance);
  66695. lastTime = time;
  66696. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  66697. };
  66698. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  66699. };
  66700. // Create lens flare post-process
  66701. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  66702. var _this = this;
  66703. 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);
  66704. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  66705. this._createBlurPostProcesses(scene, ratio / 4, 2);
  66706. 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);
  66707. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  66708. var resolution = new BABYLON.Vector2(0, 0);
  66709. // Lens flare
  66710. this.lensFlarePostProcess.onApply = function (effect) {
  66711. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  66712. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  66713. effect.setFloat("strength", _this.lensFlareStrength);
  66714. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  66715. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  66716. // Shift
  66717. resolution.x = _this.lensFlarePostProcess.width;
  66718. resolution.y = _this.lensFlarePostProcess.height;
  66719. effect.setVector2("resolution", resolution);
  66720. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  66721. };
  66722. // Compose
  66723. 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);
  66724. 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);
  66725. this.lensFlareComposePostProcess.onApply = function (effect) {
  66726. if (!_this._scene.activeCamera) {
  66727. return;
  66728. }
  66729. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66730. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  66731. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  66732. // Lens start rotation matrix
  66733. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  66734. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  66735. 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));
  66736. camRot *= 4.0;
  66737. 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);
  66738. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  66739. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  66740. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  66741. };
  66742. };
  66743. // Create depth-of-field post-process
  66744. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  66745. var _this = this;
  66746. 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);
  66747. this.depthOfFieldPostProcess.onApply = function (effect) {
  66748. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  66749. effect.setTexture("depthSampler", _this._getDepthTexture());
  66750. effect.setFloat("distance", _this.depthOfFieldDistance);
  66751. };
  66752. // Add to pipeline
  66753. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  66754. };
  66755. // Create motion blur post-process
  66756. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  66757. var _this = this;
  66758. 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);
  66759. var motionScale = 0;
  66760. var prevViewProjection = BABYLON.Matrix.Identity();
  66761. var invViewProjection = BABYLON.Matrix.Identity();
  66762. var viewProjection = BABYLON.Matrix.Identity();
  66763. var screenSize = BABYLON.Vector2.Zero();
  66764. this.motionBlurPostProcess.onApply = function (effect) {
  66765. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  66766. viewProjection.invertToRef(invViewProjection);
  66767. effect.setMatrix("inverseViewProjection", invViewProjection);
  66768. effect.setMatrix("prevViewProjection", prevViewProjection);
  66769. prevViewProjection = viewProjection;
  66770. screenSize.x = _this.motionBlurPostProcess.width;
  66771. screenSize.y = _this.motionBlurPostProcess.height;
  66772. effect.setVector2("screenSize", screenSize);
  66773. motionScale = scene.getEngine().getFps() / 60.0;
  66774. effect.setFloat("motionScale", motionScale);
  66775. effect.setFloat("motionStrength", _this.motionStrength);
  66776. effect.setTexture("depthSampler", _this._getDepthTexture());
  66777. };
  66778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  66779. };
  66780. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  66781. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  66782. var renderer = this._scene.enableGeometryBufferRenderer();
  66783. return renderer.getGBuffer().textures[0];
  66784. }
  66785. return this._scene.enableDepthRenderer().getDepthMap();
  66786. };
  66787. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  66788. for (var i = 0; i < this._cameras.length; i++) {
  66789. var camera = this._cameras[i];
  66790. if (this.originalPostProcess) {
  66791. this.originalPostProcess.dispose(camera);
  66792. }
  66793. if (this.downSampleX4PostProcess) {
  66794. this.downSampleX4PostProcess.dispose(camera);
  66795. }
  66796. if (this.brightPassPostProcess) {
  66797. this.brightPassPostProcess.dispose(camera);
  66798. }
  66799. if (this.textureAdderPostProcess) {
  66800. this.textureAdderPostProcess.dispose(camera);
  66801. }
  66802. if (this.textureAdderFinalPostProcess) {
  66803. this.textureAdderFinalPostProcess.dispose(camera);
  66804. }
  66805. if (this.volumetricLightPostProcess) {
  66806. this.volumetricLightPostProcess.dispose(camera);
  66807. }
  66808. if (this.volumetricLightSmoothXPostProcess) {
  66809. this.volumetricLightSmoothXPostProcess.dispose(camera);
  66810. }
  66811. if (this.volumetricLightSmoothYPostProcess) {
  66812. this.volumetricLightSmoothYPostProcess.dispose(camera);
  66813. }
  66814. if (this.volumetricLightMergePostProces) {
  66815. this.volumetricLightMergePostProces.dispose(camera);
  66816. }
  66817. if (this.volumetricLightFinalPostProcess) {
  66818. this.volumetricLightFinalPostProcess.dispose(camera);
  66819. }
  66820. if (this.lensFlarePostProcess) {
  66821. this.lensFlarePostProcess.dispose(camera);
  66822. }
  66823. if (this.lensFlareComposePostProcess) {
  66824. this.lensFlareComposePostProcess.dispose(camera);
  66825. }
  66826. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  66827. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  66828. }
  66829. if (this.luminancePostProcess) {
  66830. this.luminancePostProcess.dispose(camera);
  66831. }
  66832. if (this.hdrPostProcess) {
  66833. this.hdrPostProcess.dispose(camera);
  66834. }
  66835. if (this.hdrFinalPostProcess) {
  66836. this.hdrFinalPostProcess.dispose(camera);
  66837. }
  66838. if (this.depthOfFieldPostProcess) {
  66839. this.depthOfFieldPostProcess.dispose(camera);
  66840. }
  66841. if (this.motionBlurPostProcess) {
  66842. this.motionBlurPostProcess.dispose(camera);
  66843. }
  66844. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  66845. this.blurHPostProcesses[j].dispose(camera);
  66846. }
  66847. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  66848. this.blurVPostProcesses[j].dispose(camera);
  66849. }
  66850. }
  66851. this.originalPostProcess = null;
  66852. this.downSampleX4PostProcess = null;
  66853. this.brightPassPostProcess = null;
  66854. this.textureAdderPostProcess = null;
  66855. this.textureAdderFinalPostProcess = null;
  66856. this.volumetricLightPostProcess = null;
  66857. this.volumetricLightSmoothXPostProcess = null;
  66858. this.volumetricLightSmoothYPostProcess = null;
  66859. this.volumetricLightMergePostProces = null;
  66860. this.volumetricLightFinalPostProcess = null;
  66861. this.lensFlarePostProcess = null;
  66862. this.lensFlareComposePostProcess = null;
  66863. this.luminancePostProcess = null;
  66864. this.hdrPostProcess = null;
  66865. this.hdrFinalPostProcess = null;
  66866. this.depthOfFieldPostProcess = null;
  66867. this.motionBlurPostProcess = null;
  66868. this.luminanceDownSamplePostProcesses = [];
  66869. this.blurHPostProcesses = [];
  66870. this.blurVPostProcesses = [];
  66871. };
  66872. // Dispose
  66873. StandardRenderingPipeline.prototype.dispose = function () {
  66874. this._disposePostProcesses();
  66875. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  66876. _super.prototype.dispose.call(this);
  66877. };
  66878. // Serialize rendering pipeline
  66879. StandardRenderingPipeline.prototype.serialize = function () {
  66880. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  66881. serializationObject.customType = "StandardRenderingPipeline";
  66882. return serializationObject;
  66883. };
  66884. /**
  66885. * Static members
  66886. */
  66887. // Parse serialized pipeline
  66888. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  66889. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  66890. };
  66891. // Luminance steps
  66892. StandardRenderingPipeline.LuminanceSteps = 6;
  66893. __decorate([
  66894. BABYLON.serialize()
  66895. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  66896. __decorate([
  66897. BABYLON.serialize()
  66898. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  66899. __decorate([
  66900. BABYLON.serialize()
  66901. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  66902. __decorate([
  66903. BABYLON.serialize()
  66904. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  66905. __decorate([
  66906. BABYLON.serializeAsTexture("lensTexture")
  66907. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  66908. __decorate([
  66909. BABYLON.serialize()
  66910. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  66911. __decorate([
  66912. BABYLON.serialize()
  66913. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  66914. __decorate([
  66915. BABYLON.serialize()
  66916. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  66917. __decorate([
  66918. BABYLON.serialize()
  66919. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  66920. __decorate([
  66921. BABYLON.serialize()
  66922. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  66923. __decorate([
  66924. BABYLON.serialize()
  66925. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  66926. __decorate([
  66927. BABYLON.serializeAsTexture("lensColorTexture")
  66928. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  66929. __decorate([
  66930. BABYLON.serialize()
  66931. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  66932. __decorate([
  66933. BABYLON.serialize()
  66934. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  66935. __decorate([
  66936. BABYLON.serialize()
  66937. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  66938. __decorate([
  66939. BABYLON.serialize()
  66940. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  66941. __decorate([
  66942. BABYLON.serializeAsTexture("lensStarTexture")
  66943. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  66944. __decorate([
  66945. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  66946. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  66947. __decorate([
  66948. BABYLON.serialize()
  66949. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  66950. __decorate([
  66951. BABYLON.serialize()
  66952. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  66953. __decorate([
  66954. BABYLON.serialize()
  66955. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  66956. __decorate([
  66957. BABYLON.serialize()
  66958. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  66959. __decorate([
  66960. BABYLON.serialize()
  66961. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  66962. __decorate([
  66963. BABYLON.serialize()
  66964. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  66965. __decorate([
  66966. BABYLON.serialize()
  66967. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  66968. __decorate([
  66969. BABYLON.serialize()
  66970. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  66971. __decorate([
  66972. BABYLON.serialize()
  66973. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  66974. __decorate([
  66975. BABYLON.serialize()
  66976. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  66977. __decorate([
  66978. BABYLON.serialize()
  66979. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  66980. __decorate([
  66981. BABYLON.serialize()
  66982. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  66983. return StandardRenderingPipeline;
  66984. }(BABYLON.PostProcessRenderPipeline));
  66985. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  66986. })(BABYLON || (BABYLON = {}));
  66987. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  66988. var BABYLON;
  66989. (function (BABYLON) {
  66990. var FxaaPostProcess = /** @class */ (function (_super) {
  66991. __extends(FxaaPostProcess, _super);
  66992. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  66993. if (camera === void 0) { camera = null; }
  66994. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  66995. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  66996. _this.onApplyObservable.add(function (effect) {
  66997. var texelSize = _this.texelSize;
  66998. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  66999. });
  67000. return _this;
  67001. }
  67002. return FxaaPostProcess;
  67003. }(BABYLON.PostProcess));
  67004. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67005. })(BABYLON || (BABYLON = {}));
  67006. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67007. var BABYLON;
  67008. (function (BABYLON) {
  67009. /**
  67010. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67011. */
  67012. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67013. __extends(CircleOfConfusionPostProcess, _super);
  67014. /**
  67015. * Creates a new instance of @see CircleOfConfusionPostProcess
  67016. * @param name The name of the effect.
  67017. * @param scene The scene the effect belongs to.
  67018. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67019. * @param options The required width/height ratio to downsize to before computing the render pass.
  67020. * @param camera The camera to apply the render pass to.
  67021. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67022. * @param engine The engine which the post process will be applied. (default: current engine)
  67023. * @param reusable If the post process can be reused on the same frame. (default: false)
  67024. * @param textureType Type of textures used when performing the post process. (default: 0)
  67025. */
  67026. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67027. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67028. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67029. /**
  67030. * 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.
  67031. */
  67032. _this.lensSize = 50;
  67033. /**
  67034. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67035. */
  67036. _this.fStop = 1.4;
  67037. /**
  67038. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67039. */
  67040. _this.focusDistance = 2000;
  67041. /**
  67042. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67043. */
  67044. _this.focalLength = 50;
  67045. _this.onApplyObservable.add(function (effect) {
  67046. effect.setTexture("depthSampler", depthTexture);
  67047. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67048. var aperture = _this.lensSize / _this.fStop;
  67049. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67050. effect.setFloat('focusDistance', _this.focusDistance);
  67051. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67052. if (scene.activeCamera) {
  67053. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67054. }
  67055. });
  67056. return _this;
  67057. }
  67058. return CircleOfConfusionPostProcess;
  67059. }(BABYLON.PostProcess));
  67060. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67061. })(BABYLON || (BABYLON = {}));
  67062. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67063. var BABYLON;
  67064. (function (BABYLON) {
  67065. /**
  67066. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67067. */
  67068. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67069. __extends(DepthOfFieldMergePostProcess, _super);
  67070. /**
  67071. * Creates a new instance of @see CircleOfConfusionPostProcess
  67072. * @param name The name of the effect.
  67073. * @param original The non-blurred image to be modified
  67074. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67075. * @param blurSteps Incrimental bluring post processes.
  67076. * @param options The required width/height ratio to downsize to before computing the render pass.
  67077. * @param camera The camera to apply the render pass to.
  67078. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67079. * @param engine The engine which the post process will be applied. (default: current engine)
  67080. * @param reusable If the post process can be reused on the same frame. (default: false)
  67081. * @param textureType Type of textures used when performing the post process. (default: 0)
  67082. */
  67083. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67084. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67085. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67086. _this.onApplyObservable.add(function (effect) {
  67087. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67088. effect.setTextureFromPostProcess("originalSampler", original);
  67089. blurSteps.forEach(function (step, index) {
  67090. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67091. });
  67092. });
  67093. return _this;
  67094. }
  67095. return DepthOfFieldMergePostProcess;
  67096. }(BABYLON.PostProcess));
  67097. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67098. })(BABYLON || (BABYLON = {}));
  67099. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67100. var BABYLON;
  67101. (function (BABYLON) {
  67102. /**
  67103. * Specifies the level of max blur that should be applied when using the depth of field effect
  67104. */
  67105. var DepthOfFieldEffectBlurLevel;
  67106. (function (DepthOfFieldEffectBlurLevel) {
  67107. /**
  67108. * Subtle blur
  67109. */
  67110. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67111. /**
  67112. * Medium blur
  67113. */
  67114. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67115. /**
  67116. * Large blur
  67117. */
  67118. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67119. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67120. ;
  67121. /**
  67122. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67123. */
  67124. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67125. __extends(DepthOfFieldEffect, _super);
  67126. /**
  67127. * Creates a new instance of @see DepthOfFieldEffect
  67128. * @param scene The scene the effect belongs to.
  67129. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67130. */
  67131. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  67132. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67133. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67134. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67135. // Enable and get current depth map
  67136. var depthMap = scene.enableDepthRenderer().getDepthMap();
  67137. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67138. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67139. // Capture circle of confusion texture
  67140. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67141. _this._depthOfFieldPass.autoClear = false;
  67142. // 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)
  67143. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67144. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67145. _this._depthOfFieldBlurY = [];
  67146. _this._depthOfFieldBlurX = [];
  67147. var blurCount = 1;
  67148. var kernelSize = 15;
  67149. switch (blurLevel) {
  67150. case DepthOfFieldEffectBlurLevel.High: {
  67151. blurCount = 3;
  67152. kernelSize = 51;
  67153. break;
  67154. }
  67155. case DepthOfFieldEffectBlurLevel.Medium: {
  67156. blurCount = 2;
  67157. kernelSize = 31;
  67158. break;
  67159. }
  67160. default: {
  67161. kernelSize = 15;
  67162. blurCount = 1;
  67163. break;
  67164. }
  67165. }
  67166. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67167. for (var i = 0; i < blurCount; i++) {
  67168. 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);
  67169. blurY.autoClear = false;
  67170. 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);
  67171. blurX.autoClear = false;
  67172. _this._depthOfFieldBlurY.push(blurY);
  67173. _this._depthOfFieldBlurX.push(blurX);
  67174. }
  67175. // Merge blurred images with original image based on circleOfConfusion
  67176. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67177. _this._depthOfFieldMerge.autoClear = false;
  67178. // Set all post processes on the effect.
  67179. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67180. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67181. effects.push(_this._depthOfFieldBlurY[i]);
  67182. effects.push(_this._depthOfFieldBlurX[i]);
  67183. }
  67184. effects.push(_this._depthOfFieldMerge);
  67185. return effects;
  67186. }, true) || this;
  67187. return _this;
  67188. }
  67189. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67190. get: function () {
  67191. return this._circleOfConfusion.focalLength;
  67192. },
  67193. /**
  67194. * The focal the length of the camera used in the effect
  67195. */
  67196. set: function (value) {
  67197. this._circleOfConfusion.focalLength = value;
  67198. },
  67199. enumerable: true,
  67200. configurable: true
  67201. });
  67202. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67203. get: function () {
  67204. return this._circleOfConfusion.fStop;
  67205. },
  67206. /**
  67207. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67208. */
  67209. set: function (value) {
  67210. this._circleOfConfusion.fStop = value;
  67211. },
  67212. enumerable: true,
  67213. configurable: true
  67214. });
  67215. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67216. get: function () {
  67217. return this._circleOfConfusion.focusDistance;
  67218. },
  67219. /**
  67220. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67221. */
  67222. set: function (value) {
  67223. this._circleOfConfusion.focusDistance = value;
  67224. },
  67225. enumerable: true,
  67226. configurable: true
  67227. });
  67228. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67229. get: function () {
  67230. return this._circleOfConfusion.lensSize;
  67231. },
  67232. /**
  67233. * 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.
  67234. */
  67235. set: function (value) {
  67236. this._circleOfConfusion.lensSize = value;
  67237. },
  67238. enumerable: true,
  67239. configurable: true
  67240. });
  67241. /**
  67242. * Disposes each of the internal effects for a given camera.
  67243. * @param camera The camera to dispose the effect on.
  67244. */
  67245. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67246. this._depthOfFieldPass.dispose(camera);
  67247. this._circleOfConfusion.dispose(camera);
  67248. this._depthOfFieldBlurX.forEach(function (element) {
  67249. element.dispose(camera);
  67250. });
  67251. this._depthOfFieldBlurY.forEach(function (element) {
  67252. element.dispose(camera);
  67253. });
  67254. this._depthOfFieldMerge.dispose(camera);
  67255. };
  67256. return DepthOfFieldEffect;
  67257. }(BABYLON.PostProcessRenderEffect));
  67258. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67259. })(BABYLON || (BABYLON = {}));
  67260. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67261. var BABYLON;
  67262. (function (BABYLON) {
  67263. /**
  67264. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67265. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67266. */
  67267. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67268. __extends(DefaultRenderingPipeline, _super);
  67269. /**
  67270. * @constructor
  67271. * @param {string} name - The rendering pipeline name
  67272. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67273. * @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)
  67274. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67275. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67276. */
  67277. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67278. if (automaticBuild === void 0) { automaticBuild = true; }
  67279. var _this = _super.call(this, scene.getEngine(), name) || this;
  67280. /**
  67281. * ID of the pass post process used for bloom,
  67282. */
  67283. _this.PassPostProcessId = "PassPostProcessEffect";
  67284. /**
  67285. * ID of the highlight post process used for bloom,
  67286. */
  67287. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67288. /**
  67289. * ID of the blurX post process used for bloom,
  67290. */
  67291. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67292. /**
  67293. * ID of the blurY post process used for bloom,
  67294. */
  67295. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67296. /**
  67297. * ID of the copy back post process used for bloom,
  67298. */
  67299. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67300. /**
  67301. * ID of the image processing post process;
  67302. */
  67303. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67304. /**
  67305. * ID of the Fast Approximate Anti-Aliasing post process;
  67306. */
  67307. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67308. /**
  67309. * ID of the final merge post process;
  67310. */
  67311. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67312. /**
  67313. * Animations which can be used to tweak settings over a period of time
  67314. */
  67315. _this.animations = [];
  67316. // Values
  67317. _this._bloomEnabled = false;
  67318. _this._depthOfFieldEnabled = false;
  67319. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67320. _this._fxaaEnabled = false;
  67321. _this._imageProcessingEnabled = true;
  67322. _this._bloomScale = 0.6;
  67323. _this._buildAllowed = true;
  67324. /**
  67325. * Specifies the size of the bloom blur kernel, relative to the final output size
  67326. */
  67327. _this.bloomKernel = 64;
  67328. /**
  67329. * Specifies the weight of the bloom in the final rendering
  67330. */
  67331. _this._bloomWeight = 0.15;
  67332. _this._cameras = cameras || [];
  67333. _this._buildAllowed = automaticBuild;
  67334. // Initialize
  67335. _this._scene = scene;
  67336. var caps = _this._scene.getEngine().getCaps();
  67337. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67338. // Misc
  67339. if (_this._hdr) {
  67340. if (caps.textureHalfFloatRender) {
  67341. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67342. }
  67343. else if (caps.textureFloatRender) {
  67344. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67345. }
  67346. }
  67347. else {
  67348. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67349. }
  67350. // Attach
  67351. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67352. _this._buildPipeline();
  67353. return _this;
  67354. }
  67355. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67356. get: function () {
  67357. return this._bloomWeight;
  67358. },
  67359. /**
  67360. * The strength of the bloom.
  67361. */
  67362. set: function (value) {
  67363. if (this._bloomWeight === value) {
  67364. return;
  67365. }
  67366. this._bloomWeight = value;
  67367. if (this._hdr && this.copyBack) {
  67368. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67369. }
  67370. },
  67371. enumerable: true,
  67372. configurable: true
  67373. });
  67374. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67375. get: function () {
  67376. return this._bloomScale;
  67377. },
  67378. /**
  67379. * The scale of the bloom, lower value will provide better performance.
  67380. */
  67381. set: function (value) {
  67382. if (this._bloomScale === value) {
  67383. return;
  67384. }
  67385. this._bloomScale = value;
  67386. this._buildPipeline();
  67387. },
  67388. enumerable: true,
  67389. configurable: true
  67390. });
  67391. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67392. get: function () {
  67393. return this._bloomEnabled;
  67394. },
  67395. /**
  67396. * Enable or disable the bloom from the pipeline
  67397. */
  67398. set: function (enabled) {
  67399. if (this._bloomEnabled === enabled) {
  67400. return;
  67401. }
  67402. this._bloomEnabled = enabled;
  67403. this._buildPipeline();
  67404. },
  67405. enumerable: true,
  67406. configurable: true
  67407. });
  67408. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67409. /**
  67410. * If the depth of field is enabled.
  67411. */
  67412. get: function () {
  67413. return this._depthOfFieldEnabled;
  67414. },
  67415. set: function (enabled) {
  67416. if (this._depthOfFieldEnabled === enabled) {
  67417. return;
  67418. }
  67419. this._depthOfFieldEnabled = enabled;
  67420. this._buildPipeline();
  67421. },
  67422. enumerable: true,
  67423. configurable: true
  67424. });
  67425. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67426. /**
  67427. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67428. */
  67429. get: function () {
  67430. return this._depthOfFieldBlurLevel;
  67431. },
  67432. set: function (value) {
  67433. if (this._depthOfFieldBlurLevel === value) {
  67434. return;
  67435. }
  67436. this._depthOfFieldBlurLevel = value;
  67437. this._buildPipeline();
  67438. },
  67439. enumerable: true,
  67440. configurable: true
  67441. });
  67442. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67443. get: function () {
  67444. return this._fxaaEnabled;
  67445. },
  67446. /**
  67447. * If the anti aliasing is enabled.
  67448. */
  67449. set: function (enabled) {
  67450. if (this._fxaaEnabled === enabled) {
  67451. return;
  67452. }
  67453. this._fxaaEnabled = enabled;
  67454. this._buildPipeline();
  67455. },
  67456. enumerable: true,
  67457. configurable: true
  67458. });
  67459. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  67460. get: function () {
  67461. return this._imageProcessingEnabled;
  67462. },
  67463. /**
  67464. * If image processing is enabled.
  67465. */
  67466. set: function (enabled) {
  67467. if (this._imageProcessingEnabled === enabled) {
  67468. return;
  67469. }
  67470. this._imageProcessingEnabled = enabled;
  67471. this._buildPipeline();
  67472. },
  67473. enumerable: true,
  67474. configurable: true
  67475. });
  67476. /**
  67477. * Force the compilation of the entire pipeline.
  67478. */
  67479. DefaultRenderingPipeline.prototype.prepare = function () {
  67480. var previousState = this._buildAllowed;
  67481. this._buildAllowed = true;
  67482. this._buildPipeline();
  67483. this._buildAllowed = previousState;
  67484. };
  67485. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  67486. var _this = this;
  67487. if (!this._buildAllowed) {
  67488. return;
  67489. }
  67490. var engine = this._scene.getEngine();
  67491. this._disposePostProcesses();
  67492. this._reset();
  67493. if (this.depthOfFieldEnabled) {
  67494. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  67495. this.addEffect(this.depthOfField);
  67496. }
  67497. if (this.bloomEnabled) {
  67498. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67499. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  67500. if (!this._hdr) {
  67501. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67502. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  67503. this.highlights.autoClear = false;
  67504. this.highlights.alwaysForcePOT = true;
  67505. }
  67506. 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);
  67507. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  67508. this.blurX.alwaysForcePOT = true;
  67509. this.blurX.autoClear = false;
  67510. this.blurX.onActivateObservable.add(function () {
  67511. var dw = _this.blurX.width / engine.getRenderWidth(true);
  67512. _this.blurX.kernel = _this.bloomKernel * dw;
  67513. });
  67514. 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);
  67515. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  67516. this.blurY.alwaysForcePOT = true;
  67517. this.blurY.autoClear = false;
  67518. this.blurY.onActivateObservable.add(function () {
  67519. var dh = _this.blurY.height / engine.getRenderHeight(true);
  67520. _this.blurY.kernel = _this.bloomKernel * dh;
  67521. });
  67522. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67523. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  67524. this.copyBack.alwaysForcePOT = true;
  67525. if (this._hdr) {
  67526. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  67527. var w = this.bloomWeight;
  67528. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  67529. }
  67530. else {
  67531. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  67532. }
  67533. this.copyBack.autoClear = false;
  67534. }
  67535. if (this._imageProcessingEnabled) {
  67536. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67537. if (this._hdr) {
  67538. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  67539. }
  67540. else {
  67541. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  67542. }
  67543. }
  67544. if (this.fxaaEnabled) {
  67545. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67546. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  67547. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67548. }
  67549. else if (this._hdr && this.imageProcessing) {
  67550. this.finalMerge = this.imageProcessing;
  67551. }
  67552. else {
  67553. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  67554. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  67555. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  67556. }
  67557. if (this.bloomEnabled) {
  67558. if (this._hdr) {
  67559. this.copyBack.shareOutputWith(this.blurX);
  67560. if (this.imageProcessing) {
  67561. this.imageProcessing.shareOutputWith(this.pass);
  67562. this.imageProcessing.autoClear = false;
  67563. }
  67564. else if (this.fxaa) {
  67565. this.fxaa.shareOutputWith(this.pass);
  67566. }
  67567. else {
  67568. this.finalMerge.shareOutputWith(this.pass);
  67569. }
  67570. }
  67571. else {
  67572. if (this.fxaa) {
  67573. this.fxaa.shareOutputWith(this.pass);
  67574. }
  67575. else {
  67576. this.finalMerge.shareOutputWith(this.pass);
  67577. }
  67578. }
  67579. }
  67580. if (this._cameras !== null) {
  67581. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67582. }
  67583. };
  67584. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  67585. for (var i = 0; i < this._cameras.length; i++) {
  67586. var camera = this._cameras[i];
  67587. if (this.pass) {
  67588. this.pass.dispose(camera);
  67589. }
  67590. if (this.highlights) {
  67591. this.highlights.dispose(camera);
  67592. }
  67593. if (this.blurX) {
  67594. this.blurX.dispose(camera);
  67595. }
  67596. if (this.blurY) {
  67597. this.blurY.dispose(camera);
  67598. }
  67599. if (this.copyBack) {
  67600. this.copyBack.dispose(camera);
  67601. }
  67602. if (this.imageProcessing) {
  67603. this.imageProcessing.dispose(camera);
  67604. }
  67605. if (this.fxaa) {
  67606. this.fxaa.dispose(camera);
  67607. }
  67608. if (this.finalMerge) {
  67609. this.finalMerge.dispose(camera);
  67610. }
  67611. if (this.depthOfField) {
  67612. this.depthOfField.disposeEffects(camera);
  67613. }
  67614. }
  67615. this.pass = null;
  67616. this.highlights = null;
  67617. this.blurX = null;
  67618. this.blurY = null;
  67619. this.copyBack = null;
  67620. this.imageProcessing = null;
  67621. this.fxaa = null;
  67622. this.finalMerge = null;
  67623. this.depthOfField = null;
  67624. };
  67625. /**
  67626. * Dispose of the pipeline and stop all post processes
  67627. */
  67628. DefaultRenderingPipeline.prototype.dispose = function () {
  67629. this._disposePostProcesses();
  67630. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67631. _super.prototype.dispose.call(this);
  67632. };
  67633. /**
  67634. * Serialize the rendering pipeline (Used when exporting)
  67635. * @returns the serialized object
  67636. */
  67637. DefaultRenderingPipeline.prototype.serialize = function () {
  67638. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67639. serializationObject.customType = "DefaultRenderingPipeline";
  67640. return serializationObject;
  67641. };
  67642. /**
  67643. * Parse the serialized pipeline
  67644. * @param source Source pipeline.
  67645. * @param scene The scene to load the pipeline to.
  67646. * @param rootUrl The URL of the serialized pipeline.
  67647. * @returns An instantiated pipeline from the serialized object.
  67648. */
  67649. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67650. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  67651. };
  67652. __decorate([
  67653. BABYLON.serialize()
  67654. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  67655. __decorate([
  67656. BABYLON.serialize()
  67657. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  67658. __decorate([
  67659. BABYLON.serialize()
  67660. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  67661. __decorate([
  67662. BABYLON.serialize()
  67663. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  67664. __decorate([
  67665. BABYLON.serialize()
  67666. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  67667. __decorate([
  67668. BABYLON.serialize()
  67669. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  67670. __decorate([
  67671. BABYLON.serialize()
  67672. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  67673. __decorate([
  67674. BABYLON.serialize()
  67675. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  67676. __decorate([
  67677. BABYLON.serialize()
  67678. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  67679. __decorate([
  67680. BABYLON.serialize()
  67681. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  67682. return DefaultRenderingPipeline;
  67683. }(BABYLON.PostProcessRenderPipeline));
  67684. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  67685. })(BABYLON || (BABYLON = {}));
  67686. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  67687. var BABYLON;
  67688. (function (BABYLON) {
  67689. /**
  67690. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  67691. */
  67692. var GeometryBufferRenderer = /** @class */ (function () {
  67693. /**
  67694. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  67695. * @param scene The scene the buffer belongs to
  67696. * @param ratio How big is the buffer related to the main canvas.
  67697. */
  67698. function GeometryBufferRenderer(scene, ratio) {
  67699. if (ratio === void 0) { ratio = 1; }
  67700. this._enablePosition = false;
  67701. this._scene = scene;
  67702. this._ratio = ratio;
  67703. // Render target
  67704. this._createRenderTargets();
  67705. }
  67706. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  67707. /**
  67708. * Set the render list (meshes to be rendered) used in the G buffer.
  67709. */
  67710. set: function (meshes) {
  67711. this._multiRenderTarget.renderList = meshes;
  67712. },
  67713. enumerable: true,
  67714. configurable: true
  67715. });
  67716. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  67717. /**
  67718. * Gets wether or not G buffer are supported by the running hardware.
  67719. * This requires draw buffer supports
  67720. */
  67721. get: function () {
  67722. return this._multiRenderTarget.isSupported;
  67723. },
  67724. enumerable: true,
  67725. configurable: true
  67726. });
  67727. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  67728. /**
  67729. * Gets wether or not position are enabled for the G buffer.
  67730. */
  67731. get: function () {
  67732. return this._enablePosition;
  67733. },
  67734. /**
  67735. * Sets wether or not position are enabled for the G buffer.
  67736. */
  67737. set: function (enable) {
  67738. this._enablePosition = enable;
  67739. this.dispose();
  67740. this._createRenderTargets();
  67741. },
  67742. enumerable: true,
  67743. configurable: true
  67744. });
  67745. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  67746. /**
  67747. * Gets the scene associated with the buffer.
  67748. */
  67749. get: function () {
  67750. return this._scene;
  67751. },
  67752. enumerable: true,
  67753. configurable: true
  67754. });
  67755. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  67756. /**
  67757. * Gets the ratio used by the buffer during its creation.
  67758. * How big is the buffer related to the main canvas.
  67759. */
  67760. get: function () {
  67761. return this._ratio;
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. /**
  67767. * Checks wether everything is ready to render a submesh to the G buffer.
  67768. * @param subMesh the submesh to check readiness for
  67769. * @param useInstances is the mesh drawn using instance or not
  67770. * @returns true if ready otherwise false
  67771. */
  67772. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  67773. var material = subMesh.getMaterial();
  67774. if (material && material.disableDepthWrite) {
  67775. return false;
  67776. }
  67777. var defines = [];
  67778. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67779. var mesh = subMesh.getMesh();
  67780. // Alpha test
  67781. if (material && material.needAlphaTesting()) {
  67782. defines.push("#define ALPHATEST");
  67783. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67784. attribs.push(BABYLON.VertexBuffer.UVKind);
  67785. defines.push("#define UV1");
  67786. }
  67787. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67788. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67789. defines.push("#define UV2");
  67790. }
  67791. }
  67792. // Buffers
  67793. if (this._enablePosition) {
  67794. defines.push("#define POSITION");
  67795. }
  67796. // Bones
  67797. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67798. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67799. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67800. if (mesh.numBoneInfluencers > 4) {
  67801. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67802. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67803. }
  67804. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67805. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67806. }
  67807. else {
  67808. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67809. }
  67810. // Instances
  67811. if (useInstances) {
  67812. defines.push("#define INSTANCES");
  67813. attribs.push("world0");
  67814. attribs.push("world1");
  67815. attribs.push("world2");
  67816. attribs.push("world3");
  67817. }
  67818. // Get correct effect
  67819. var join = defines.join("\n");
  67820. if (this._cachedDefines !== join) {
  67821. this._cachedDefines = join;
  67822. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  67823. }
  67824. return this._effect.isReady();
  67825. };
  67826. /**
  67827. * Gets the current underlying G Buffer.
  67828. * @returns the buffer
  67829. */
  67830. GeometryBufferRenderer.prototype.getGBuffer = function () {
  67831. return this._multiRenderTarget;
  67832. };
  67833. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  67834. /**
  67835. * Gets the number of samples used to render the buffer (anti aliasing).
  67836. */
  67837. get: function () {
  67838. return this._multiRenderTarget.samples;
  67839. },
  67840. /**
  67841. * Sets the number of samples used to render the buffer (anti aliasing).
  67842. */
  67843. set: function (value) {
  67844. this._multiRenderTarget.samples = value;
  67845. },
  67846. enumerable: true,
  67847. configurable: true
  67848. });
  67849. /**
  67850. * Disposes the renderer and frees up associated resources.
  67851. */
  67852. GeometryBufferRenderer.prototype.dispose = function () {
  67853. this.getGBuffer().dispose();
  67854. };
  67855. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  67856. var _this = this;
  67857. var engine = this._scene.getEngine();
  67858. var count = this._enablePosition ? 3 : 2;
  67859. 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 });
  67860. if (!this.isSupported) {
  67861. return;
  67862. }
  67863. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67864. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67865. this._multiRenderTarget.refreshRate = 1;
  67866. this._multiRenderTarget.renderParticles = false;
  67867. this._multiRenderTarget.renderList = null;
  67868. // set default depth value to 1.0 (far away)
  67869. this._multiRenderTarget.onClearObservable.add(function (engine) {
  67870. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  67871. });
  67872. // Custom render function
  67873. var renderSubMesh = function (subMesh) {
  67874. var mesh = subMesh.getRenderingMesh();
  67875. var scene = _this._scene;
  67876. var engine = scene.getEngine();
  67877. var material = subMesh.getMaterial();
  67878. if (!material) {
  67879. return;
  67880. }
  67881. // Culling
  67882. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67883. // Managing instances
  67884. var batch = mesh._getInstancesRenderList(subMesh._id);
  67885. if (batch.mustReturn) {
  67886. return;
  67887. }
  67888. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67889. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  67890. engine.enableEffect(_this._effect);
  67891. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67892. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67893. _this._effect.setMatrix("view", scene.getViewMatrix());
  67894. // Alpha test
  67895. if (material && material.needAlphaTesting()) {
  67896. var alphaTexture = material.getAlphaTestTexture();
  67897. if (alphaTexture) {
  67898. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67899. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67900. }
  67901. }
  67902. // Bones
  67903. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67904. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67905. }
  67906. // Draw
  67907. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67908. }
  67909. };
  67910. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67911. var index;
  67912. if (depthOnlySubMeshes.length) {
  67913. engine.setColorWrite(false);
  67914. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67915. renderSubMesh(depthOnlySubMeshes.data[index]);
  67916. }
  67917. engine.setColorWrite(true);
  67918. }
  67919. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67920. renderSubMesh(opaqueSubMeshes.data[index]);
  67921. }
  67922. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67923. renderSubMesh(alphaTestSubMeshes.data[index]);
  67924. }
  67925. };
  67926. };
  67927. return GeometryBufferRenderer;
  67928. }());
  67929. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  67930. })(BABYLON || (BABYLON = {}));
  67931. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  67932. var BABYLON;
  67933. (function (BABYLON) {
  67934. var RefractionPostProcess = /** @class */ (function (_super) {
  67935. __extends(RefractionPostProcess, _super);
  67936. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  67937. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  67938. _this.color = color;
  67939. _this.depth = depth;
  67940. _this.colorLevel = colorLevel;
  67941. _this._ownRefractionTexture = true;
  67942. _this.onActivateObservable.add(function (cam) {
  67943. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  67944. });
  67945. _this.onApplyObservable.add(function (effect) {
  67946. effect.setColor3("baseColor", _this.color);
  67947. effect.setFloat("depth", _this.depth);
  67948. effect.setFloat("colorLevel", _this.colorLevel);
  67949. effect.setTexture("refractionSampler", _this._refTexture);
  67950. });
  67951. return _this;
  67952. }
  67953. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  67954. /**
  67955. * Gets or sets the refraction texture
  67956. * Please note that you are responsible for disposing the texture if you set it manually
  67957. */
  67958. get: function () {
  67959. return this._refTexture;
  67960. },
  67961. set: function (value) {
  67962. if (this._refTexture && this._ownRefractionTexture) {
  67963. this._refTexture.dispose();
  67964. }
  67965. this._refTexture = value;
  67966. this._ownRefractionTexture = false;
  67967. },
  67968. enumerable: true,
  67969. configurable: true
  67970. });
  67971. // Methods
  67972. RefractionPostProcess.prototype.dispose = function (camera) {
  67973. if (this._refTexture && this._ownRefractionTexture) {
  67974. this._refTexture.dispose();
  67975. this._refTexture = null;
  67976. }
  67977. _super.prototype.dispose.call(this, camera);
  67978. };
  67979. return RefractionPostProcess;
  67980. }(BABYLON.PostProcess));
  67981. BABYLON.RefractionPostProcess = RefractionPostProcess;
  67982. })(BABYLON || (BABYLON = {}));
  67983. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  67984. var BABYLON;
  67985. (function (BABYLON) {
  67986. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  67987. __extends(BlackAndWhitePostProcess, _super);
  67988. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  67989. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  67990. _this.degree = 1;
  67991. _this.onApplyObservable.add(function (effect) {
  67992. effect.setFloat("degree", _this.degree);
  67993. });
  67994. return _this;
  67995. }
  67996. return BlackAndWhitePostProcess;
  67997. }(BABYLON.PostProcess));
  67998. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  67999. })(BABYLON || (BABYLON = {}));
  68000. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68001. var BABYLON;
  68002. (function (BABYLON) {
  68003. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68004. __extends(ConvolutionPostProcess, _super);
  68005. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  68006. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  68007. _this.kernel = kernel;
  68008. _this.onApply = function (effect) {
  68009. effect.setFloat2("screenSize", _this.width, _this.height);
  68010. effect.setArray("kernel", _this.kernel);
  68011. };
  68012. return _this;
  68013. }
  68014. // Statics
  68015. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68016. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68017. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68018. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68019. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68020. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68021. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68022. return ConvolutionPostProcess;
  68023. }(BABYLON.PostProcess));
  68024. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68025. })(BABYLON || (BABYLON = {}));
  68026. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68027. var BABYLON;
  68028. (function (BABYLON) {
  68029. var FilterPostProcess = /** @class */ (function (_super) {
  68030. __extends(FilterPostProcess, _super);
  68031. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68032. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68033. _this.kernelMatrix = kernelMatrix;
  68034. _this.onApply = function (effect) {
  68035. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68036. };
  68037. return _this;
  68038. }
  68039. return FilterPostProcess;
  68040. }(BABYLON.PostProcess));
  68041. BABYLON.FilterPostProcess = FilterPostProcess;
  68042. })(BABYLON || (BABYLON = {}));
  68043. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68044. var BABYLON;
  68045. (function (BABYLON) {
  68046. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68047. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68048. __extends(VolumetricLightScatteringPostProcess, _super);
  68049. /**
  68050. * @constructor
  68051. * @param {string} name - The post-process name
  68052. * @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)
  68053. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68054. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68055. * @param {number} samples - The post-process quality, default 100
  68056. * @param {number} samplingMode - The post-process filtering mode
  68057. * @param {BABYLON.Engine} engine - The babylon engine
  68058. * @param {boolean} reusable - If the post-process is reusable
  68059. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68060. */
  68061. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68062. if (samples === void 0) { samples = 100; }
  68063. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68064. 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;
  68065. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68066. /**
  68067. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68068. * @type {Vector3}
  68069. */
  68070. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68071. /**
  68072. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68073. * @type {boolean}
  68074. */
  68075. _this.useCustomMeshPosition = false;
  68076. /**
  68077. * If the post-process should inverse the light scattering direction
  68078. * @type {boolean}
  68079. */
  68080. _this.invert = true;
  68081. /**
  68082. * Array containing the excluded meshes not rendered in the internal pass
  68083. */
  68084. _this.excludedMeshes = new Array();
  68085. /**
  68086. * Controls the overall intensity of the post-process
  68087. * @type {number}
  68088. */
  68089. _this.exposure = 0.3;
  68090. /**
  68091. * Dissipates each sample's contribution in range [0, 1]
  68092. * @type {number}
  68093. */
  68094. _this.decay = 0.96815;
  68095. /**
  68096. * Controls the overall intensity of each sample
  68097. * @type {number}
  68098. */
  68099. _this.weight = 0.58767;
  68100. /**
  68101. * Controls the density of each sample
  68102. * @type {number}
  68103. */
  68104. _this.density = 0.926;
  68105. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68106. engine = scene.getEngine();
  68107. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68108. // Configure mesh
  68109. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68110. // Configure
  68111. _this._createPass(scene, ratio.passRatio || ratio);
  68112. _this.onActivate = function (camera) {
  68113. if (!_this.isSupported) {
  68114. _this.dispose(camera);
  68115. }
  68116. _this.onActivate = null;
  68117. };
  68118. _this.onApplyObservable.add(function (effect) {
  68119. _this._updateMeshScreenCoordinates(scene);
  68120. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68121. effect.setFloat("exposure", _this.exposure);
  68122. effect.setFloat("decay", _this.decay);
  68123. effect.setFloat("weight", _this.weight);
  68124. effect.setFloat("density", _this.density);
  68125. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68126. });
  68127. return _this;
  68128. }
  68129. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68130. get: function () {
  68131. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68132. return false;
  68133. },
  68134. set: function (useDiffuseColor) {
  68135. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68136. },
  68137. enumerable: true,
  68138. configurable: true
  68139. });
  68140. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68141. return "VolumetricLightScatteringPostProcess";
  68142. };
  68143. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68144. var mesh = subMesh.getMesh();
  68145. // Render this.mesh as default
  68146. if (mesh === this.mesh && mesh.material) {
  68147. return mesh.material.isReady(mesh);
  68148. }
  68149. var defines = [];
  68150. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68151. var material = subMesh.getMaterial();
  68152. // Alpha test
  68153. if (material) {
  68154. if (material.needAlphaTesting()) {
  68155. defines.push("#define ALPHATEST");
  68156. }
  68157. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68158. attribs.push(BABYLON.VertexBuffer.UVKind);
  68159. defines.push("#define UV1");
  68160. }
  68161. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68162. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68163. defines.push("#define UV2");
  68164. }
  68165. }
  68166. // Bones
  68167. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68168. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68169. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68170. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68171. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68172. }
  68173. else {
  68174. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68175. }
  68176. // Instances
  68177. if (useInstances) {
  68178. defines.push("#define INSTANCES");
  68179. attribs.push("world0");
  68180. attribs.push("world1");
  68181. attribs.push("world2");
  68182. attribs.push("world3");
  68183. }
  68184. // Get correct effect
  68185. var join = defines.join("\n");
  68186. if (this._cachedDefines !== join) {
  68187. this._cachedDefines = join;
  68188. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68189. }
  68190. return this._volumetricLightScatteringPass.isReady();
  68191. };
  68192. /**
  68193. * Sets the new light position for light scattering effect
  68194. * @param {BABYLON.Vector3} The new custom light position
  68195. */
  68196. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68197. this.customMeshPosition = position;
  68198. };
  68199. /**
  68200. * Returns the light position for light scattering effect
  68201. * @return {BABYLON.Vector3} The custom light position
  68202. */
  68203. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68204. return this.customMeshPosition;
  68205. };
  68206. /**
  68207. * Disposes the internal assets and detaches the post-process from the camera
  68208. */
  68209. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68210. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68211. if (rttIndex !== -1) {
  68212. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68213. }
  68214. this._volumetricLightScatteringRTT.dispose();
  68215. _super.prototype.dispose.call(this, camera);
  68216. };
  68217. /**
  68218. * Returns the render target texture used by the post-process
  68219. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68220. */
  68221. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68222. return this._volumetricLightScatteringRTT;
  68223. };
  68224. // Private methods
  68225. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68226. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68227. return true;
  68228. }
  68229. return false;
  68230. };
  68231. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68232. var _this = this;
  68233. var engine = scene.getEngine();
  68234. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68235. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68236. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68237. this._volumetricLightScatteringRTT.renderList = null;
  68238. this._volumetricLightScatteringRTT.renderParticles = false;
  68239. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68240. var camera = this.getCamera();
  68241. if (camera) {
  68242. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68243. }
  68244. else {
  68245. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68246. }
  68247. // Custom render function for submeshes
  68248. var renderSubMesh = function (subMesh) {
  68249. var mesh = subMesh.getRenderingMesh();
  68250. if (_this._meshExcluded(mesh)) {
  68251. return;
  68252. }
  68253. var material = subMesh.getMaterial();
  68254. if (!material) {
  68255. return;
  68256. }
  68257. var scene = mesh.getScene();
  68258. var engine = scene.getEngine();
  68259. // Culling
  68260. engine.setState(material.backFaceCulling);
  68261. // Managing instances
  68262. var batch = mesh._getInstancesRenderList(subMesh._id);
  68263. if (batch.mustReturn) {
  68264. return;
  68265. }
  68266. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68267. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68268. var effect = _this._volumetricLightScatteringPass;
  68269. if (mesh === _this.mesh) {
  68270. if (subMesh.effect) {
  68271. effect = subMesh.effect;
  68272. }
  68273. else {
  68274. effect = material.getEffect();
  68275. }
  68276. }
  68277. engine.enableEffect(effect);
  68278. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68279. if (mesh === _this.mesh) {
  68280. material.bind(mesh.getWorldMatrix(), mesh);
  68281. }
  68282. else {
  68283. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68284. // Alpha test
  68285. if (material && material.needAlphaTesting()) {
  68286. var alphaTexture = material.getAlphaTestTexture();
  68287. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68288. if (alphaTexture) {
  68289. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68290. }
  68291. }
  68292. // Bones
  68293. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68294. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68295. }
  68296. }
  68297. // Draw
  68298. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68299. }
  68300. };
  68301. // Render target texture callbacks
  68302. var savedSceneClearColor;
  68303. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68304. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68305. savedSceneClearColor = scene.clearColor;
  68306. scene.clearColor = sceneClearColor;
  68307. });
  68308. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68309. scene.clearColor = savedSceneClearColor;
  68310. });
  68311. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68312. var engine = scene.getEngine();
  68313. var index;
  68314. if (depthOnlySubMeshes.length) {
  68315. engine.setColorWrite(false);
  68316. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68317. renderSubMesh(depthOnlySubMeshes.data[index]);
  68318. }
  68319. engine.setColorWrite(true);
  68320. }
  68321. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68322. renderSubMesh(opaqueSubMeshes.data[index]);
  68323. }
  68324. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68325. renderSubMesh(alphaTestSubMeshes.data[index]);
  68326. }
  68327. if (transparentSubMeshes.length) {
  68328. // Sort sub meshes
  68329. for (index = 0; index < transparentSubMeshes.length; index++) {
  68330. var submesh = transparentSubMeshes.data[index];
  68331. var boundingInfo = submesh.getBoundingInfo();
  68332. if (boundingInfo && scene.activeCamera) {
  68333. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68334. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68335. }
  68336. }
  68337. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68338. sortedArray.sort(function (a, b) {
  68339. // Alpha index first
  68340. if (a._alphaIndex > b._alphaIndex) {
  68341. return 1;
  68342. }
  68343. if (a._alphaIndex < b._alphaIndex) {
  68344. return -1;
  68345. }
  68346. // Then distance to camera
  68347. if (a._distanceToCamera < b._distanceToCamera) {
  68348. return 1;
  68349. }
  68350. if (a._distanceToCamera > b._distanceToCamera) {
  68351. return -1;
  68352. }
  68353. return 0;
  68354. });
  68355. // Render sub meshes
  68356. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68357. for (index = 0; index < sortedArray.length; index++) {
  68358. renderSubMesh(sortedArray[index]);
  68359. }
  68360. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68361. }
  68362. };
  68363. };
  68364. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68365. var transform = scene.getTransformMatrix();
  68366. var meshPosition;
  68367. if (this.useCustomMeshPosition) {
  68368. meshPosition = this.customMeshPosition;
  68369. }
  68370. else if (this.attachedNode) {
  68371. meshPosition = this.attachedNode.position;
  68372. }
  68373. else {
  68374. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  68375. }
  68376. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  68377. this._screenCoordinates.x = pos.x / this._viewPort.width;
  68378. this._screenCoordinates.y = pos.y / this._viewPort.height;
  68379. if (this.invert)
  68380. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  68381. };
  68382. // Static methods
  68383. /**
  68384. * Creates a default mesh for the Volumeric Light Scattering post-process
  68385. * @param {string} The mesh name
  68386. * @param {BABYLON.Scene} The scene where to create the mesh
  68387. * @return {BABYLON.Mesh} the default mesh
  68388. */
  68389. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  68390. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  68391. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  68392. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  68393. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  68394. mesh.material = material;
  68395. return mesh;
  68396. };
  68397. __decorate([
  68398. BABYLON.serializeAsVector3()
  68399. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  68400. __decorate([
  68401. BABYLON.serialize()
  68402. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  68403. __decorate([
  68404. BABYLON.serialize()
  68405. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  68406. __decorate([
  68407. BABYLON.serializeAsMeshReference()
  68408. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  68409. __decorate([
  68410. BABYLON.serialize()
  68411. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  68412. __decorate([
  68413. BABYLON.serialize()
  68414. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  68415. __decorate([
  68416. BABYLON.serialize()
  68417. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  68418. __decorate([
  68419. BABYLON.serialize()
  68420. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  68421. __decorate([
  68422. BABYLON.serialize()
  68423. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68424. return VolumetricLightScatteringPostProcess;
  68425. }(BABYLON.PostProcess));
  68426. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68427. })(BABYLON || (BABYLON = {}));
  68428. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68429. //
  68430. // This post-process allows the modification of rendered colors by using
  68431. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68432. //
  68433. // The object needs to be provided an url to a texture containing the color
  68434. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  68435. // Use an image editing software to tweak the LUT to match your needs.
  68436. //
  68437. // For an example of a color LUT, see here:
  68438. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  68439. // For explanations on color grading, see here:
  68440. // http://udn.epicgames.com/Three/ColorGrading.html
  68441. //
  68442. var BABYLON;
  68443. (function (BABYLON) {
  68444. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  68445. __extends(ColorCorrectionPostProcess, _super);
  68446. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  68447. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  68448. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68449. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  68450. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68451. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68452. _this.onApply = function (effect) {
  68453. effect.setTexture("colorTable", _this._colorTableTexture);
  68454. };
  68455. return _this;
  68456. }
  68457. return ColorCorrectionPostProcess;
  68458. }(BABYLON.PostProcess));
  68459. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  68460. })(BABYLON || (BABYLON = {}));
  68461. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  68462. var BABYLON;
  68463. (function (BABYLON) {
  68464. var TonemappingOperator;
  68465. (function (TonemappingOperator) {
  68466. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  68467. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  68468. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  68469. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  68470. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  68471. ;
  68472. var TonemapPostProcess = /** @class */ (function (_super) {
  68473. __extends(TonemapPostProcess, _super);
  68474. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  68475. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68476. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68477. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  68478. _this._operator = _operator;
  68479. _this.exposureAdjustment = exposureAdjustment;
  68480. var defines = "#define ";
  68481. if (_this._operator === TonemappingOperator.Hable)
  68482. defines += "HABLE_TONEMAPPING";
  68483. else if (_this._operator === TonemappingOperator.Reinhard)
  68484. defines += "REINHARD_TONEMAPPING";
  68485. else if (_this._operator === TonemappingOperator.HejiDawson)
  68486. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  68487. else if (_this._operator === TonemappingOperator.Photographic)
  68488. defines += "PHOTOGRAPHIC_TONEMAPPING";
  68489. //sadly a second call to create the effect.
  68490. _this.updateEffect(defines);
  68491. _this.onApply = function (effect) {
  68492. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  68493. };
  68494. return _this;
  68495. }
  68496. return TonemapPostProcess;
  68497. }(BABYLON.PostProcess));
  68498. BABYLON.TonemapPostProcess = TonemapPostProcess;
  68499. })(BABYLON || (BABYLON = {}));
  68500. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  68501. var BABYLON;
  68502. (function (BABYLON) {
  68503. var DisplayPassPostProcess = /** @class */ (function (_super) {
  68504. __extends(DisplayPassPostProcess, _super);
  68505. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  68506. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  68507. }
  68508. return DisplayPassPostProcess;
  68509. }(BABYLON.PostProcess));
  68510. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  68511. })(BABYLON || (BABYLON = {}));
  68512. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  68513. var BABYLON;
  68514. (function (BABYLON) {
  68515. var HighlightsPostProcess = /** @class */ (function (_super) {
  68516. __extends(HighlightsPostProcess, _super);
  68517. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  68518. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68519. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  68520. }
  68521. return HighlightsPostProcess;
  68522. }(BABYLON.PostProcess));
  68523. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  68524. })(BABYLON || (BABYLON = {}));
  68525. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  68526. var BABYLON;
  68527. (function (BABYLON) {
  68528. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  68529. __extends(ImageProcessingPostProcess, _super);
  68530. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  68531. if (camera === void 0) { camera = null; }
  68532. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68533. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  68534. _this._fromLinearSpace = true;
  68535. /**
  68536. * Defines cache preventing GC.
  68537. */
  68538. _this._defines = {
  68539. IMAGEPROCESSING: false,
  68540. VIGNETTE: false,
  68541. VIGNETTEBLENDMODEMULTIPLY: false,
  68542. VIGNETTEBLENDMODEOPAQUE: false,
  68543. TONEMAPPING: false,
  68544. CONTRAST: false,
  68545. COLORCURVES: false,
  68546. COLORGRADING: false,
  68547. COLORGRADING3D: false,
  68548. FROMLINEARSPACE: false,
  68549. SAMPLER3DGREENDEPTH: false,
  68550. SAMPLER3DBGRMAP: false,
  68551. IMAGEPROCESSINGPOSTPROCESS: false,
  68552. EXPOSURE: false,
  68553. };
  68554. // Setup the configuration as forced by the constructor. This would then not force the
  68555. // scene materials output in linear space and let untouched the default forward pass.
  68556. if (imageProcessingConfiguration) {
  68557. imageProcessingConfiguration.applyByPostProcess = true;
  68558. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  68559. // This will cause the shader to be compiled
  68560. _this.fromLinearSpace = false;
  68561. }
  68562. else {
  68563. _this._attachImageProcessingConfiguration(null, true);
  68564. _this.imageProcessingConfiguration.applyByPostProcess = true;
  68565. }
  68566. _this.onApply = function (effect) {
  68567. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  68568. };
  68569. return _this;
  68570. }
  68571. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  68572. /**
  68573. * Gets the image processing configuration used either in this material.
  68574. */
  68575. get: function () {
  68576. return this._imageProcessingConfiguration;
  68577. },
  68578. /**
  68579. * Sets the Default image processing configuration used either in the this material.
  68580. *
  68581. * If sets to null, the scene one is in use.
  68582. */
  68583. set: function (value) {
  68584. this._attachImageProcessingConfiguration(value);
  68585. },
  68586. enumerable: true,
  68587. configurable: true
  68588. });
  68589. /**
  68590. * Attaches a new image processing configuration to the PBR Material.
  68591. * @param configuration
  68592. */
  68593. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  68594. var _this = this;
  68595. if (doNotBuild === void 0) { doNotBuild = false; }
  68596. if (configuration === this._imageProcessingConfiguration) {
  68597. return;
  68598. }
  68599. // Detaches observer.
  68600. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68601. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68602. }
  68603. // Pick the scene configuration if needed.
  68604. if (!configuration) {
  68605. var scene = null;
  68606. var engine = this.getEngine();
  68607. var camera = this.getCamera();
  68608. if (camera) {
  68609. scene = camera.getScene();
  68610. }
  68611. else if (engine && engine.scenes) {
  68612. var scenes = engine.scenes;
  68613. scene = scenes[scenes.length - 1];
  68614. }
  68615. else {
  68616. scene = BABYLON.Engine.LastCreatedScene;
  68617. }
  68618. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  68619. }
  68620. else {
  68621. this._imageProcessingConfiguration = configuration;
  68622. }
  68623. // Attaches observer.
  68624. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  68625. _this._updateParameters();
  68626. });
  68627. // Ensure the effect will be rebuilt.
  68628. if (!doNotBuild) {
  68629. this._updateParameters();
  68630. }
  68631. };
  68632. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  68633. /**
  68634. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68635. */
  68636. get: function () {
  68637. return this.imageProcessingConfiguration.colorCurves;
  68638. },
  68639. /**
  68640. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  68641. */
  68642. set: function (value) {
  68643. this.imageProcessingConfiguration.colorCurves = value;
  68644. },
  68645. enumerable: true,
  68646. configurable: true
  68647. });
  68648. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  68649. /**
  68650. * Gets wether the color curves effect is enabled.
  68651. */
  68652. get: function () {
  68653. return this.imageProcessingConfiguration.colorCurvesEnabled;
  68654. },
  68655. /**
  68656. * Sets wether the color curves effect is enabled.
  68657. */
  68658. set: function (value) {
  68659. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  68660. },
  68661. enumerable: true,
  68662. configurable: true
  68663. });
  68664. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  68665. /**
  68666. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68667. */
  68668. get: function () {
  68669. return this.imageProcessingConfiguration.colorGradingTexture;
  68670. },
  68671. /**
  68672. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  68673. */
  68674. set: function (value) {
  68675. this.imageProcessingConfiguration.colorGradingTexture = value;
  68676. },
  68677. enumerable: true,
  68678. configurable: true
  68679. });
  68680. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  68681. /**
  68682. * Gets wether the color grading effect is enabled.
  68683. */
  68684. get: function () {
  68685. return this.imageProcessingConfiguration.colorGradingEnabled;
  68686. },
  68687. /**
  68688. * Gets wether the color grading effect is enabled.
  68689. */
  68690. set: function (value) {
  68691. this.imageProcessingConfiguration.colorGradingEnabled = value;
  68692. },
  68693. enumerable: true,
  68694. configurable: true
  68695. });
  68696. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  68697. /**
  68698. * Gets exposure used in the effect.
  68699. */
  68700. get: function () {
  68701. return this.imageProcessingConfiguration.exposure;
  68702. },
  68703. /**
  68704. * Sets exposure used in the effect.
  68705. */
  68706. set: function (value) {
  68707. this.imageProcessingConfiguration.exposure = value;
  68708. },
  68709. enumerable: true,
  68710. configurable: true
  68711. });
  68712. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  68713. /**
  68714. * Gets wether tonemapping is enabled or not.
  68715. */
  68716. get: function () {
  68717. return this._imageProcessingConfiguration.toneMappingEnabled;
  68718. },
  68719. /**
  68720. * Sets wether tonemapping is enabled or not
  68721. */
  68722. set: function (value) {
  68723. this._imageProcessingConfiguration.toneMappingEnabled = value;
  68724. },
  68725. enumerable: true,
  68726. configurable: true
  68727. });
  68728. ;
  68729. ;
  68730. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  68731. /**
  68732. * Gets contrast used in the effect.
  68733. */
  68734. get: function () {
  68735. return this.imageProcessingConfiguration.contrast;
  68736. },
  68737. /**
  68738. * Sets contrast used in the effect.
  68739. */
  68740. set: function (value) {
  68741. this.imageProcessingConfiguration.contrast = value;
  68742. },
  68743. enumerable: true,
  68744. configurable: true
  68745. });
  68746. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  68747. /**
  68748. * Gets Vignette stretch size.
  68749. */
  68750. get: function () {
  68751. return this.imageProcessingConfiguration.vignetteStretch;
  68752. },
  68753. /**
  68754. * Sets Vignette stretch size.
  68755. */
  68756. set: function (value) {
  68757. this.imageProcessingConfiguration.vignetteStretch = value;
  68758. },
  68759. enumerable: true,
  68760. configurable: true
  68761. });
  68762. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  68763. /**
  68764. * Gets Vignette centre X Offset.
  68765. */
  68766. get: function () {
  68767. return this.imageProcessingConfiguration.vignetteCentreX;
  68768. },
  68769. /**
  68770. * Sets Vignette centre X Offset.
  68771. */
  68772. set: function (value) {
  68773. this.imageProcessingConfiguration.vignetteCentreX = value;
  68774. },
  68775. enumerable: true,
  68776. configurable: true
  68777. });
  68778. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  68779. /**
  68780. * Gets Vignette centre Y Offset.
  68781. */
  68782. get: function () {
  68783. return this.imageProcessingConfiguration.vignetteCentreY;
  68784. },
  68785. /**
  68786. * Sets Vignette centre Y Offset.
  68787. */
  68788. set: function (value) {
  68789. this.imageProcessingConfiguration.vignetteCentreY = value;
  68790. },
  68791. enumerable: true,
  68792. configurable: true
  68793. });
  68794. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  68795. /**
  68796. * Gets Vignette weight or intensity of the vignette effect.
  68797. */
  68798. get: function () {
  68799. return this.imageProcessingConfiguration.vignetteWeight;
  68800. },
  68801. /**
  68802. * Sets Vignette weight or intensity of the vignette effect.
  68803. */
  68804. set: function (value) {
  68805. this.imageProcessingConfiguration.vignetteWeight = value;
  68806. },
  68807. enumerable: true,
  68808. configurable: true
  68809. });
  68810. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  68811. /**
  68812. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68813. * if vignetteEnabled is set to true.
  68814. */
  68815. get: function () {
  68816. return this.imageProcessingConfiguration.vignetteColor;
  68817. },
  68818. /**
  68819. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68820. * if vignetteEnabled is set to true.
  68821. */
  68822. set: function (value) {
  68823. this.imageProcessingConfiguration.vignetteColor = value;
  68824. },
  68825. enumerable: true,
  68826. configurable: true
  68827. });
  68828. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  68829. /**
  68830. * Gets Camera field of view used by the Vignette effect.
  68831. */
  68832. get: function () {
  68833. return this.imageProcessingConfiguration.vignetteCameraFov;
  68834. },
  68835. /**
  68836. * Sets Camera field of view used by the Vignette effect.
  68837. */
  68838. set: function (value) {
  68839. this.imageProcessingConfiguration.vignetteCameraFov = value;
  68840. },
  68841. enumerable: true,
  68842. configurable: true
  68843. });
  68844. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  68845. /**
  68846. * Gets the vignette blend mode allowing different kind of effect.
  68847. */
  68848. get: function () {
  68849. return this.imageProcessingConfiguration.vignetteBlendMode;
  68850. },
  68851. /**
  68852. * Sets the vignette blend mode allowing different kind of effect.
  68853. */
  68854. set: function (value) {
  68855. this.imageProcessingConfiguration.vignetteBlendMode = value;
  68856. },
  68857. enumerable: true,
  68858. configurable: true
  68859. });
  68860. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  68861. /**
  68862. * Gets wether the vignette effect is enabled.
  68863. */
  68864. get: function () {
  68865. return this.imageProcessingConfiguration.vignetteEnabled;
  68866. },
  68867. /**
  68868. * Sets wether the vignette effect is enabled.
  68869. */
  68870. set: function (value) {
  68871. this.imageProcessingConfiguration.vignetteEnabled = value;
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  68877. /**
  68878. * Gets wether the input of the processing is in Gamma or Linear Space.
  68879. */
  68880. get: function () {
  68881. return this._fromLinearSpace;
  68882. },
  68883. /**
  68884. * Sets wether the input of the processing is in Gamma or Linear Space.
  68885. */
  68886. set: function (value) {
  68887. if (this._fromLinearSpace === value) {
  68888. return;
  68889. }
  68890. this._fromLinearSpace = value;
  68891. this._updateParameters();
  68892. },
  68893. enumerable: true,
  68894. configurable: true
  68895. });
  68896. ImageProcessingPostProcess.prototype.getClassName = function () {
  68897. return "ImageProcessingPostProcess";
  68898. };
  68899. ImageProcessingPostProcess.prototype._updateParameters = function () {
  68900. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  68901. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  68902. var defines = "";
  68903. for (var define in this._defines) {
  68904. if (this._defines[define]) {
  68905. defines += "#define " + define + ";\r\n";
  68906. }
  68907. }
  68908. var samplers = ["textureSampler"];
  68909. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  68910. var uniforms = ["scale"];
  68911. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  68912. this.updateEffect(defines, uniforms, samplers);
  68913. };
  68914. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  68915. _super.prototype.dispose.call(this, camera);
  68916. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  68917. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  68918. }
  68919. this.imageProcessingConfiguration.applyByPostProcess = false;
  68920. };
  68921. __decorate([
  68922. BABYLON.serialize()
  68923. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  68924. return ImageProcessingPostProcess;
  68925. }(BABYLON.PostProcess));
  68926. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  68927. })(BABYLON || (BABYLON = {}));
  68928. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  68929. var BABYLON;
  68930. (function (BABYLON) {
  68931. /**
  68932. * The Blur Post Process which blurs an image based on a kernel and direction.
  68933. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  68934. */
  68935. var BlurPostProcess = /** @class */ (function (_super) {
  68936. __extends(BlurPostProcess, _super);
  68937. /**
  68938. * Creates a new instance of @see BlurPostProcess
  68939. * @param name The name of the effect.
  68940. * @param direction The direction in which to blur the image.
  68941. * @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.
  68942. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  68943. * @param camera The camera to apply the render pass to.
  68944. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  68945. * @param engine The engine which the post process will be applied. (default: current engine)
  68946. * @param reusable If the post process can be reused on the same frame. (default: false)
  68947. * @param textureType Type of textures used when performing the post process. (default: 0)
  68948. */
  68949. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  68950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68951. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  68952. if (defines === void 0) { defines = ""; }
  68953. 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;
  68954. _this.direction = direction;
  68955. _this._packedFloat = false;
  68956. _this._staticDefines = "";
  68957. _this._staticDefines = defines;
  68958. _this.onApplyObservable.add(function (effect) {
  68959. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  68960. });
  68961. _this.kernel = kernel;
  68962. return _this;
  68963. }
  68964. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  68965. /**
  68966. * Gets the length in pixels of the blur sample region
  68967. */
  68968. get: function () {
  68969. return this._idealKernel;
  68970. },
  68971. /**
  68972. * Sets the length in pixels of the blur sample region
  68973. */
  68974. set: function (v) {
  68975. if (this._idealKernel === v) {
  68976. return;
  68977. }
  68978. v = Math.max(v, 1);
  68979. this._idealKernel = v;
  68980. this._kernel = this._nearestBestKernel(v);
  68981. this._updateParameters();
  68982. },
  68983. enumerable: true,
  68984. configurable: true
  68985. });
  68986. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  68987. /**
  68988. * Gets wether or not the blur is unpacking/repacking floats
  68989. */
  68990. get: function () {
  68991. return this._packedFloat;
  68992. },
  68993. /**
  68994. * Sets wether or not the blur needs to unpack/repack floats
  68995. */
  68996. set: function (v) {
  68997. if (this._packedFloat === v) {
  68998. return;
  68999. }
  69000. this._packedFloat = v;
  69001. this._updateParameters();
  69002. },
  69003. enumerable: true,
  69004. configurable: true
  69005. });
  69006. BlurPostProcess.prototype._updateParameters = function () {
  69007. // Generate sampling offsets and weights
  69008. var N = this._kernel;
  69009. var centerIndex = (N - 1) / 2;
  69010. // Generate Gaussian sampling weights over kernel
  69011. var offsets = [];
  69012. var weights = [];
  69013. var totalWeight = 0;
  69014. for (var i = 0; i < N; i++) {
  69015. var u = i / (N - 1);
  69016. var w = this._gaussianWeight(u * 2.0 - 1);
  69017. offsets[i] = (i - centerIndex);
  69018. weights[i] = w;
  69019. totalWeight += w;
  69020. }
  69021. // Normalize weights
  69022. for (var i = 0; i < weights.length; i++) {
  69023. weights[i] /= totalWeight;
  69024. }
  69025. // Optimize: combine samples to take advantage of hardware linear sampling
  69026. // Walk from left to center, combining pairs (symmetrically)
  69027. var linearSamplingWeights = [];
  69028. var linearSamplingOffsets = [];
  69029. var linearSamplingMap = [];
  69030. for (var i = 0; i <= centerIndex; i += 2) {
  69031. var j = Math.min(i + 1, Math.floor(centerIndex));
  69032. var singleCenterSample = i === j;
  69033. if (singleCenterSample) {
  69034. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69035. }
  69036. else {
  69037. var sharedCell = j === centerIndex;
  69038. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69039. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69040. if (offsetLinear === 0) {
  69041. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69042. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69043. }
  69044. else {
  69045. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69046. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69047. }
  69048. }
  69049. }
  69050. for (var i = 0; i < linearSamplingMap.length; i++) {
  69051. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69052. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69053. }
  69054. // Replace with optimized
  69055. offsets = linearSamplingOffsets;
  69056. weights = linearSamplingWeights;
  69057. // Generate shaders
  69058. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69059. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69060. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69061. var defines = "";
  69062. defines += this._staticDefines;
  69063. for (var i = 0; i < varyingCount; i++) {
  69064. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69065. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69066. }
  69067. var depCount = 0;
  69068. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69069. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69070. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69071. depCount++;
  69072. }
  69073. if (this.packedFloat) {
  69074. defines += "#define PACKEDFLOAT 1";
  69075. }
  69076. this.updateEffect(defines, null, null, {
  69077. varyingCount: varyingCount,
  69078. depCount: depCount
  69079. });
  69080. };
  69081. /**
  69082. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69083. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69084. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69085. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69086. * The gaps between physical kernels are compensated for in the weighting of the samples
  69087. * @param idealKernel Ideal blur kernel.
  69088. * @return Nearest best kernel.
  69089. */
  69090. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69091. var v = Math.round(idealKernel);
  69092. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69093. var k = _a[_i];
  69094. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69095. return Math.max(k, 3);
  69096. }
  69097. }
  69098. return Math.max(v, 3);
  69099. };
  69100. /**
  69101. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69102. * @param x The point on the Gaussian distribution to sample.
  69103. * @return the value of the Gaussian function at x.
  69104. */
  69105. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69106. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69107. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69108. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69109. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69110. // truncated at around 1.3% of peak strength.
  69111. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69112. var sigma = (1 / 3);
  69113. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69114. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69115. var weight = (1.0 / denominator) * Math.exp(exponent);
  69116. return weight;
  69117. };
  69118. /**
  69119. * Generates a string that can be used as a floating point number in GLSL.
  69120. * @param x Value to print.
  69121. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69122. * @return GLSL float string.
  69123. */
  69124. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69125. if (decimalFigures === void 0) { decimalFigures = 8; }
  69126. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69127. };
  69128. return BlurPostProcess;
  69129. }(BABYLON.PostProcess));
  69130. BABYLON.BlurPostProcess = BlurPostProcess;
  69131. })(BABYLON || (BABYLON = {}));
  69132. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69133. var BABYLON;
  69134. (function (BABYLON) {
  69135. /**
  69136. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69137. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69138. * based on samples that have a large difference in distance than the center pixel.
  69139. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69140. */
  69141. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69142. __extends(DepthOfFieldBlurPostProcess, _super);
  69143. /**
  69144. * Creates a new instance of @see CircleOfConfusionPostProcess
  69145. * @param name The name of the effect.
  69146. * @param scene The scene the effect belongs to.
  69147. * @param direction The direction the blur should be applied.
  69148. * @param kernel The size of the kernel used to blur.
  69149. * @param options The required width/height ratio to downsize to before computing the render pass.
  69150. * @param camera The camera to apply the render pass to.
  69151. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69152. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69153. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69154. * @param engine The engine which the post process will be applied. (default: current engine)
  69155. * @param reusable If the post process can be reused on the same frame. (default: false)
  69156. * @param textureType Type of textures used when performing the post process. (default: 0)
  69157. */
  69158. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  69159. if (imageToBlur === void 0) { imageToBlur = null; }
  69160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69161. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69162. 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") || this;
  69163. _this.direction = direction;
  69164. _this.onApplyObservable.add(function (effect) {
  69165. if (imageToBlur != null) {
  69166. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69167. }
  69168. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69169. if (scene.activeCamera) {
  69170. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69171. }
  69172. });
  69173. return _this;
  69174. }
  69175. return DepthOfFieldBlurPostProcess;
  69176. }(BABYLON.BlurPostProcess));
  69177. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69178. })(BABYLON || (BABYLON = {}));
  69179. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69180. var BABYLON;
  69181. (function (BABYLON) {
  69182. var Bone = /** @class */ (function (_super) {
  69183. __extends(Bone, _super);
  69184. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69185. if (parentBone === void 0) { parentBone = null; }
  69186. if (localMatrix === void 0) { localMatrix = null; }
  69187. if (restPose === void 0) { restPose = null; }
  69188. if (baseMatrix === void 0) { baseMatrix = null; }
  69189. if (index === void 0) { index = null; }
  69190. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69191. _this.name = name;
  69192. _this.children = new Array();
  69193. _this.animations = new Array();
  69194. // Set this value to map this bone to a different index in the transform matrices.
  69195. // Set this value to -1 to exclude the bone from the transform matrices.
  69196. _this._index = null;
  69197. _this._worldTransform = new BABYLON.Matrix();
  69198. _this._absoluteTransform = new BABYLON.Matrix();
  69199. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69200. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69201. _this._scaleVector = BABYLON.Vector3.One();
  69202. _this._negateScaleChildren = BABYLON.Vector3.One();
  69203. _this._scalingDeterminant = 1;
  69204. _this._skeleton = skeleton;
  69205. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69206. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69207. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69208. _this._index = index;
  69209. skeleton.bones.push(_this);
  69210. _this.setParent(parentBone, false);
  69211. _this._updateDifferenceMatrix();
  69212. return _this;
  69213. }
  69214. Object.defineProperty(Bone.prototype, "_matrix", {
  69215. get: function () {
  69216. return this._localMatrix;
  69217. },
  69218. set: function (val) {
  69219. if (this._localMatrix) {
  69220. this._localMatrix.copyFrom(val);
  69221. }
  69222. else {
  69223. this._localMatrix = val;
  69224. }
  69225. },
  69226. enumerable: true,
  69227. configurable: true
  69228. });
  69229. // Members
  69230. Bone.prototype.getSkeleton = function () {
  69231. return this._skeleton;
  69232. };
  69233. Bone.prototype.getParent = function () {
  69234. return this._parent;
  69235. };
  69236. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69237. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69238. if (this._parent === parent) {
  69239. return;
  69240. }
  69241. if (this._parent) {
  69242. var index = this._parent.children.indexOf(this);
  69243. if (index !== -1) {
  69244. this._parent.children.splice(index, 1);
  69245. }
  69246. }
  69247. this._parent = parent;
  69248. if (this._parent) {
  69249. this._parent.children.push(this);
  69250. }
  69251. if (updateDifferenceMatrix) {
  69252. this._updateDifferenceMatrix();
  69253. }
  69254. };
  69255. Bone.prototype.getLocalMatrix = function () {
  69256. return this._localMatrix;
  69257. };
  69258. Bone.prototype.getBaseMatrix = function () {
  69259. return this._baseMatrix;
  69260. };
  69261. Bone.prototype.getRestPose = function () {
  69262. return this._restPose;
  69263. };
  69264. Bone.prototype.returnToRest = function () {
  69265. this.updateMatrix(this._restPose.clone());
  69266. };
  69267. Bone.prototype.getWorldMatrix = function () {
  69268. return this._worldTransform;
  69269. };
  69270. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69271. return this._invertedAbsoluteTransform;
  69272. };
  69273. Bone.prototype.getAbsoluteTransform = function () {
  69274. return this._absoluteTransform;
  69275. };
  69276. Object.defineProperty(Bone.prototype, "position", {
  69277. // Properties (matches AbstractMesh properties)
  69278. get: function () {
  69279. return this.getPosition();
  69280. },
  69281. set: function (newPosition) {
  69282. this.setPosition(newPosition);
  69283. },
  69284. enumerable: true,
  69285. configurable: true
  69286. });
  69287. Object.defineProperty(Bone.prototype, "rotation", {
  69288. get: function () {
  69289. return this.getRotation();
  69290. },
  69291. set: function (newRotation) {
  69292. this.setRotation(newRotation);
  69293. },
  69294. enumerable: true,
  69295. configurable: true
  69296. });
  69297. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69298. get: function () {
  69299. return this.getRotationQuaternion();
  69300. },
  69301. set: function (newRotation) {
  69302. this.setRotationQuaternion(newRotation);
  69303. },
  69304. enumerable: true,
  69305. configurable: true
  69306. });
  69307. Object.defineProperty(Bone.prototype, "scaling", {
  69308. get: function () {
  69309. return this.getScale();
  69310. },
  69311. set: function (newScaling) {
  69312. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69313. },
  69314. enumerable: true,
  69315. configurable: true
  69316. });
  69317. // Methods
  69318. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69319. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69320. this._baseMatrix = matrix.clone();
  69321. this._localMatrix = matrix.clone();
  69322. this._skeleton._markAsDirty();
  69323. if (updateDifferenceMatrix) {
  69324. this._updateDifferenceMatrix();
  69325. }
  69326. };
  69327. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69328. if (!rootMatrix) {
  69329. rootMatrix = this._baseMatrix;
  69330. }
  69331. if (this._parent) {
  69332. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69333. }
  69334. else {
  69335. this._absoluteTransform.copyFrom(rootMatrix);
  69336. }
  69337. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69338. for (var index = 0; index < this.children.length; index++) {
  69339. this.children[index]._updateDifferenceMatrix();
  69340. }
  69341. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69342. };
  69343. Bone.prototype.markAsDirty = function () {
  69344. this._currentRenderId++;
  69345. this._skeleton._markAsDirty();
  69346. };
  69347. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69348. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69349. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69350. // all animation may be coming from a library skeleton, so may need to create animation
  69351. if (this.animations.length === 0) {
  69352. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69353. this.animations[0].setKeys([]);
  69354. }
  69355. // get animation info / verify there is such a range from the source bone
  69356. var sourceRange = source.animations[0].getRange(rangeName);
  69357. if (!sourceRange) {
  69358. return false;
  69359. }
  69360. var from = sourceRange.from;
  69361. var to = sourceRange.to;
  69362. var sourceKeys = source.animations[0].getKeys();
  69363. // rescaling prep
  69364. var sourceBoneLength = source.length;
  69365. var sourceParent = source.getParent();
  69366. var parent = this.getParent();
  69367. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69368. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69369. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69370. var destKeys = this.animations[0].getKeys();
  69371. // loop vars declaration
  69372. var orig;
  69373. var origTranslation;
  69374. var mat;
  69375. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69376. orig = sourceKeys[key];
  69377. if (orig.frame >= from && orig.frame <= to) {
  69378. if (rescaleAsRequired) {
  69379. mat = orig.value.clone();
  69380. // scale based on parent ratio, when bone has parent
  69381. if (parentScalingReqd) {
  69382. origTranslation = mat.getTranslation();
  69383. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69384. // scale based on skeleton dimension ratio when root bone, and value is passed
  69385. }
  69386. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69387. origTranslation = mat.getTranslation();
  69388. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69389. // use original when root bone, and no data for skelDimensionsRatio
  69390. }
  69391. else {
  69392. mat = orig.value;
  69393. }
  69394. }
  69395. else {
  69396. mat = orig.value;
  69397. }
  69398. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69399. }
  69400. }
  69401. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69402. return true;
  69403. };
  69404. /**
  69405. * Translate the bone in local or world space.
  69406. * @param vec The amount to translate the bone.
  69407. * @param space The space that the translation is in.
  69408. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69409. */
  69410. Bone.prototype.translate = function (vec, space, mesh) {
  69411. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69412. var lm = this.getLocalMatrix();
  69413. if (space == BABYLON.Space.LOCAL) {
  69414. lm.m[12] += vec.x;
  69415. lm.m[13] += vec.y;
  69416. lm.m[14] += vec.z;
  69417. }
  69418. else {
  69419. var wm = null;
  69420. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69421. if (mesh) {
  69422. wm = mesh.getWorldMatrix();
  69423. }
  69424. this._skeleton.computeAbsoluteTransforms();
  69425. var tmat = Bone._tmpMats[0];
  69426. var tvec = Bone._tmpVecs[0];
  69427. if (this._parent) {
  69428. if (mesh && wm) {
  69429. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69430. tmat.multiplyToRef(wm, tmat);
  69431. }
  69432. else {
  69433. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69434. }
  69435. }
  69436. tmat.m[12] = 0;
  69437. tmat.m[13] = 0;
  69438. tmat.m[14] = 0;
  69439. tmat.invert();
  69440. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  69441. lm.m[12] += tvec.x;
  69442. lm.m[13] += tvec.y;
  69443. lm.m[14] += tvec.z;
  69444. }
  69445. this.markAsDirty();
  69446. };
  69447. /**
  69448. * Set the postion of the bone in local or world space.
  69449. * @param position The position to set the bone.
  69450. * @param space The space that the position is in.
  69451. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69452. */
  69453. Bone.prototype.setPosition = function (position, space, mesh) {
  69454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69455. var lm = this.getLocalMatrix();
  69456. if (space == BABYLON.Space.LOCAL) {
  69457. lm.m[12] = position.x;
  69458. lm.m[13] = position.y;
  69459. lm.m[14] = position.z;
  69460. }
  69461. else {
  69462. var wm = null;
  69463. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69464. if (mesh) {
  69465. wm = mesh.getWorldMatrix();
  69466. }
  69467. this._skeleton.computeAbsoluteTransforms();
  69468. var tmat = Bone._tmpMats[0];
  69469. var vec = Bone._tmpVecs[0];
  69470. if (this._parent) {
  69471. if (mesh && wm) {
  69472. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69473. tmat.multiplyToRef(wm, tmat);
  69474. }
  69475. else {
  69476. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69477. }
  69478. }
  69479. tmat.invert();
  69480. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  69481. lm.m[12] = vec.x;
  69482. lm.m[13] = vec.y;
  69483. lm.m[14] = vec.z;
  69484. }
  69485. this.markAsDirty();
  69486. };
  69487. /**
  69488. * Set the absolute postion of the bone (world space).
  69489. * @param position The position to set the bone.
  69490. * @param mesh The mesh that this bone is attached to.
  69491. */
  69492. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  69493. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  69494. };
  69495. /**
  69496. * Set the scale of the bone on the x, y and z axes.
  69497. * @param x The scale of the bone on the x axis.
  69498. * @param x The scale of the bone on the y axis.
  69499. * @param z The scale of the bone on the z axis.
  69500. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69501. */
  69502. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  69503. if (scaleChildren === void 0) { scaleChildren = false; }
  69504. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  69505. if (!scaleChildren) {
  69506. this._negateScaleChildren.x = 1 / x;
  69507. this._negateScaleChildren.y = 1 / y;
  69508. this._negateScaleChildren.z = 1 / z;
  69509. }
  69510. this._syncScaleVector();
  69511. }
  69512. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  69513. };
  69514. /**
  69515. * Scale the bone on the x, y and z axes.
  69516. * @param x The amount to scale the bone on the x axis.
  69517. * @param x The amount to scale the bone on the y axis.
  69518. * @param z The amount to scale the bone on the z axis.
  69519. * @param scaleChildren Set this to true if children of the bone should be scaled.
  69520. */
  69521. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  69522. if (scaleChildren === void 0) { scaleChildren = false; }
  69523. var locMat = this.getLocalMatrix();
  69524. var origLocMat = Bone._tmpMats[0];
  69525. origLocMat.copyFrom(locMat);
  69526. var origLocMatInv = Bone._tmpMats[1];
  69527. origLocMatInv.copyFrom(origLocMat);
  69528. origLocMatInv.invert();
  69529. var scaleMat = Bone._tmpMats[2];
  69530. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  69531. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  69532. this._scaleVector.x *= x;
  69533. this._scaleVector.y *= y;
  69534. this._scaleVector.z *= z;
  69535. locMat.multiplyToRef(origLocMatInv, locMat);
  69536. locMat.multiplyToRef(scaleMat, locMat);
  69537. locMat.multiplyToRef(origLocMat, locMat);
  69538. var parent = this.getParent();
  69539. if (parent) {
  69540. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  69541. }
  69542. else {
  69543. this.getAbsoluteTransform().copyFrom(locMat);
  69544. }
  69545. var len = this.children.length;
  69546. scaleMat.invert();
  69547. for (var i = 0; i < len; i++) {
  69548. var child = this.children[i];
  69549. var cm = child.getLocalMatrix();
  69550. cm.multiplyToRef(scaleMat, cm);
  69551. var lm = child.getLocalMatrix();
  69552. lm.m[12] *= x;
  69553. lm.m[13] *= y;
  69554. lm.m[14] *= z;
  69555. }
  69556. this.computeAbsoluteTransforms();
  69557. if (scaleChildren) {
  69558. for (var i = 0; i < len; i++) {
  69559. this.children[i].scale(x, y, z, scaleChildren);
  69560. }
  69561. }
  69562. this.markAsDirty();
  69563. };
  69564. /**
  69565. * Set the yaw, pitch, and roll of the bone in local or world space.
  69566. * @param yaw The rotation of the bone on the y axis.
  69567. * @param pitch The rotation of the bone on the x axis.
  69568. * @param roll The rotation of the bone on the z axis.
  69569. * @param space The space that the axes of rotation are in.
  69570. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69571. */
  69572. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  69573. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69574. var rotMat = Bone._tmpMats[0];
  69575. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  69576. var rotMatInv = Bone._tmpMats[1];
  69577. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69578. rotMatInv.multiplyToRef(rotMat, rotMat);
  69579. this._rotateWithMatrix(rotMat, space, mesh);
  69580. };
  69581. /**
  69582. * Rotate the bone on an axis in local or world space.
  69583. * @param axis The axis to rotate the bone on.
  69584. * @param amount The amount to rotate the bone.
  69585. * @param space The space that the axis is in.
  69586. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69587. */
  69588. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  69589. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69590. var rmat = Bone._tmpMats[0];
  69591. rmat.m[12] = 0;
  69592. rmat.m[13] = 0;
  69593. rmat.m[14] = 0;
  69594. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  69595. this._rotateWithMatrix(rmat, space, mesh);
  69596. };
  69597. /**
  69598. * Set the rotation of the bone to a particular axis angle in local or world space.
  69599. * @param axis The axis to rotate the bone on.
  69600. * @param angle The angle that the bone should be rotated to.
  69601. * @param space The space that the axis is in.
  69602. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69603. */
  69604. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  69605. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69606. var rotMat = Bone._tmpMats[0];
  69607. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  69608. var rotMatInv = Bone._tmpMats[1];
  69609. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69610. rotMatInv.multiplyToRef(rotMat, rotMat);
  69611. this._rotateWithMatrix(rotMat, space, mesh);
  69612. };
  69613. /**
  69614. * Set the euler rotation of the bone in local of world space.
  69615. * @param rotation The euler rotation that the bone should be set to.
  69616. * @param space The space that the rotation is in.
  69617. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69618. */
  69619. Bone.prototype.setRotation = function (rotation, space, mesh) {
  69620. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69621. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  69622. };
  69623. /**
  69624. * Set the quaternion rotation of the bone in local of world space.
  69625. * @param quat The quaternion rotation that the bone should be set to.
  69626. * @param space The space that the rotation is in.
  69627. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69628. */
  69629. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  69630. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69631. var rotMatInv = Bone._tmpMats[0];
  69632. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69633. var rotMat = Bone._tmpMats[1];
  69634. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  69635. rotMatInv.multiplyToRef(rotMat, rotMat);
  69636. this._rotateWithMatrix(rotMat, space, mesh);
  69637. };
  69638. /**
  69639. * Set the rotation matrix of the bone in local of world space.
  69640. * @param rotMat The rotation matrix that the bone should be set to.
  69641. * @param space The space that the rotation is in.
  69642. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69643. */
  69644. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  69645. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69646. var rotMatInv = Bone._tmpMats[0];
  69647. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  69648. var rotMat2 = Bone._tmpMats[1];
  69649. rotMat2.copyFrom(rotMat);
  69650. rotMatInv.multiplyToRef(rotMat, rotMat2);
  69651. this._rotateWithMatrix(rotMat2, space, mesh);
  69652. };
  69653. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  69654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69655. var lmat = this.getLocalMatrix();
  69656. var lx = lmat.m[12];
  69657. var ly = lmat.m[13];
  69658. var lz = lmat.m[14];
  69659. var parent = this.getParent();
  69660. var parentScale = Bone._tmpMats[3];
  69661. var parentScaleInv = Bone._tmpMats[4];
  69662. if (parent) {
  69663. if (space == BABYLON.Space.WORLD) {
  69664. if (mesh) {
  69665. parentScale.copyFrom(mesh.getWorldMatrix());
  69666. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  69667. }
  69668. else {
  69669. parentScale.copyFrom(parent.getAbsoluteTransform());
  69670. }
  69671. }
  69672. else {
  69673. parentScale = parent._scaleMatrix;
  69674. }
  69675. parentScaleInv.copyFrom(parentScale);
  69676. parentScaleInv.invert();
  69677. lmat.multiplyToRef(parentScale, lmat);
  69678. lmat.multiplyToRef(rmat, lmat);
  69679. lmat.multiplyToRef(parentScaleInv, lmat);
  69680. }
  69681. else {
  69682. if (space == BABYLON.Space.WORLD && mesh) {
  69683. parentScale.copyFrom(mesh.getWorldMatrix());
  69684. parentScaleInv.copyFrom(parentScale);
  69685. parentScaleInv.invert();
  69686. lmat.multiplyToRef(parentScale, lmat);
  69687. lmat.multiplyToRef(rmat, lmat);
  69688. lmat.multiplyToRef(parentScaleInv, lmat);
  69689. }
  69690. else {
  69691. lmat.multiplyToRef(rmat, lmat);
  69692. }
  69693. }
  69694. lmat.m[12] = lx;
  69695. lmat.m[13] = ly;
  69696. lmat.m[14] = lz;
  69697. this.computeAbsoluteTransforms();
  69698. this.markAsDirty();
  69699. };
  69700. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  69701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69702. if (space == BABYLON.Space.WORLD) {
  69703. var scaleMatrix = Bone._tmpMats[2];
  69704. scaleMatrix.copyFrom(this._scaleMatrix);
  69705. rotMatInv.copyFrom(this.getAbsoluteTransform());
  69706. if (mesh) {
  69707. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  69708. var meshScale = Bone._tmpMats[3];
  69709. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  69710. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  69711. }
  69712. rotMatInv.invert();
  69713. scaleMatrix.m[0] *= this._scalingDeterminant;
  69714. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69715. }
  69716. else {
  69717. rotMatInv.copyFrom(this.getLocalMatrix());
  69718. rotMatInv.invert();
  69719. var scaleMatrix = Bone._tmpMats[2];
  69720. scaleMatrix.copyFrom(this._scaleMatrix);
  69721. if (this._parent) {
  69722. var pscaleMatrix = Bone._tmpMats[3];
  69723. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  69724. pscaleMatrix.invert();
  69725. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  69726. }
  69727. else {
  69728. scaleMatrix.m[0] *= this._scalingDeterminant;
  69729. }
  69730. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  69731. }
  69732. };
  69733. /**
  69734. * Get the scale of the bone
  69735. * @returns the scale of the bone
  69736. */
  69737. Bone.prototype.getScale = function () {
  69738. return this._scaleVector.clone();
  69739. };
  69740. /**
  69741. * Copy the scale of the bone to a vector3.
  69742. * @param result The vector3 to copy the scale to
  69743. */
  69744. Bone.prototype.getScaleToRef = function (result) {
  69745. result.copyFrom(this._scaleVector);
  69746. };
  69747. /**
  69748. * Get the position of the bone in local or world space.
  69749. * @param space The space that the returned position is in.
  69750. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69751. * @returns The position of the bone
  69752. */
  69753. Bone.prototype.getPosition = function (space, mesh) {
  69754. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69755. if (mesh === void 0) { mesh = null; }
  69756. var pos = BABYLON.Vector3.Zero();
  69757. this.getPositionToRef(space, mesh, pos);
  69758. return pos;
  69759. };
  69760. /**
  69761. * Copy the position of the bone to a vector3 in local or world space.
  69762. * @param space The space that the returned position is in.
  69763. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69764. * @param result The vector3 to copy the position to.
  69765. */
  69766. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  69767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69768. if (space == BABYLON.Space.LOCAL) {
  69769. var lm = this.getLocalMatrix();
  69770. result.x = lm.m[12];
  69771. result.y = lm.m[13];
  69772. result.z = lm.m[14];
  69773. }
  69774. else {
  69775. var wm = null;
  69776. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69777. if (mesh) {
  69778. wm = mesh.getWorldMatrix();
  69779. }
  69780. this._skeleton.computeAbsoluteTransforms();
  69781. var tmat = Bone._tmpMats[0];
  69782. if (mesh && wm) {
  69783. tmat.copyFrom(this.getAbsoluteTransform());
  69784. tmat.multiplyToRef(wm, tmat);
  69785. }
  69786. else {
  69787. tmat = this.getAbsoluteTransform();
  69788. }
  69789. result.x = tmat.m[12];
  69790. result.y = tmat.m[13];
  69791. result.z = tmat.m[14];
  69792. }
  69793. };
  69794. /**
  69795. * Get the absolute position of the bone (world space).
  69796. * @param mesh The mesh that this bone is attached to.
  69797. * @returns The absolute position of the bone
  69798. */
  69799. Bone.prototype.getAbsolutePosition = function (mesh) {
  69800. if (mesh === void 0) { mesh = null; }
  69801. var pos = BABYLON.Vector3.Zero();
  69802. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  69803. return pos;
  69804. };
  69805. /**
  69806. * Copy the absolute position of the bone (world space) to the result param.
  69807. * @param mesh The mesh that this bone is attached to.
  69808. * @param result The vector3 to copy the absolute position to.
  69809. */
  69810. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  69811. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  69812. };
  69813. /**
  69814. * Compute the absolute transforms of this bone and its children.
  69815. */
  69816. Bone.prototype.computeAbsoluteTransforms = function () {
  69817. if (this._parent) {
  69818. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69819. }
  69820. else {
  69821. this._absoluteTransform.copyFrom(this._localMatrix);
  69822. var poseMatrix = this._skeleton.getPoseMatrix();
  69823. if (poseMatrix) {
  69824. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  69825. }
  69826. }
  69827. var children = this.children;
  69828. var len = children.length;
  69829. for (var i = 0; i < len; i++) {
  69830. children[i].computeAbsoluteTransforms();
  69831. }
  69832. };
  69833. Bone.prototype._syncScaleVector = function () {
  69834. var lm = this.getLocalMatrix();
  69835. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  69836. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  69837. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  69838. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  69839. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  69840. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  69841. this._scaleVector.x = xs * Math.sqrt(xsq);
  69842. this._scaleVector.y = ys * Math.sqrt(ysq);
  69843. this._scaleVector.z = zs * Math.sqrt(zsq);
  69844. if (this._parent) {
  69845. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  69846. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  69847. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  69848. }
  69849. 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);
  69850. };
  69851. /**
  69852. * Get the world direction from an axis that is in the local space of the bone.
  69853. * @param localAxis The local direction that is used to compute the world direction.
  69854. * @param mesh The mesh that this bone is attached to.
  69855. * @returns The world direction
  69856. */
  69857. Bone.prototype.getDirection = function (localAxis, mesh) {
  69858. if (mesh === void 0) { mesh = null; }
  69859. var result = BABYLON.Vector3.Zero();
  69860. this.getDirectionToRef(localAxis, mesh, result);
  69861. return result;
  69862. };
  69863. /**
  69864. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  69865. * @param localAxis The local direction that is used to compute the world direction.
  69866. * @param mesh The mesh that this bone is attached to.
  69867. * @param result The vector3 that the world direction will be copied to.
  69868. */
  69869. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  69870. if (mesh === void 0) { mesh = null; }
  69871. var wm = null;
  69872. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69873. if (mesh) {
  69874. wm = mesh.getWorldMatrix();
  69875. }
  69876. this._skeleton.computeAbsoluteTransforms();
  69877. var mat = Bone._tmpMats[0];
  69878. mat.copyFrom(this.getAbsoluteTransform());
  69879. if (mesh && wm) {
  69880. mat.multiplyToRef(wm, mat);
  69881. }
  69882. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  69883. result.normalize();
  69884. };
  69885. /**
  69886. * Get the euler rotation of the bone in local or world space.
  69887. * @param space The space that the rotation should be in.
  69888. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69889. * @returns The euler rotation
  69890. */
  69891. Bone.prototype.getRotation = function (space, mesh) {
  69892. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69893. if (mesh === void 0) { mesh = null; }
  69894. var result = BABYLON.Vector3.Zero();
  69895. this.getRotationToRef(space, mesh, result);
  69896. return result;
  69897. };
  69898. /**
  69899. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  69900. * @param space The space that the rotation should be in.
  69901. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69902. * @param result The vector3 that the rotation should be copied to.
  69903. */
  69904. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  69905. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69906. if (mesh === void 0) { mesh = null; }
  69907. var quat = Bone._tmpQuat;
  69908. this.getRotationQuaternionToRef(space, mesh, quat);
  69909. quat.toEulerAnglesToRef(result);
  69910. };
  69911. /**
  69912. * Get the quaternion rotation of the bone in either local or world space.
  69913. * @param space The space that the rotation should be in.
  69914. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69915. * @returns The quaternion rotation
  69916. */
  69917. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  69918. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69919. if (mesh === void 0) { mesh = null; }
  69920. var result = BABYLON.Quaternion.Identity();
  69921. this.getRotationQuaternionToRef(space, mesh, result);
  69922. return result;
  69923. };
  69924. /**
  69925. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  69926. * @param space The space that the rotation should be in.
  69927. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69928. * @param result The quaternion that the rotation should be copied to.
  69929. */
  69930. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  69931. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69932. if (mesh === void 0) { mesh = null; }
  69933. if (space == BABYLON.Space.LOCAL) {
  69934. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69935. }
  69936. else {
  69937. var mat = Bone._tmpMats[0];
  69938. var amat = this.getAbsoluteTransform();
  69939. if (mesh) {
  69940. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69941. }
  69942. else {
  69943. mat.copyFrom(amat);
  69944. }
  69945. mat.m[0] *= this._scalingDeterminant;
  69946. mat.m[1] *= this._scalingDeterminant;
  69947. mat.m[2] *= this._scalingDeterminant;
  69948. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  69949. }
  69950. };
  69951. /**
  69952. * Get the rotation matrix of the bone in local or world space.
  69953. * @param space The space that the rotation should be in.
  69954. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69955. * @returns The rotation matrix
  69956. */
  69957. Bone.prototype.getRotationMatrix = function (space, mesh) {
  69958. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69959. var result = BABYLON.Matrix.Identity();
  69960. this.getRotationMatrixToRef(space, mesh, result);
  69961. return result;
  69962. };
  69963. /**
  69964. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  69965. * @param space The space that the rotation should be in.
  69966. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69967. * @param result The quaternion that the rotation should be copied to.
  69968. */
  69969. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  69970. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69971. if (space == BABYLON.Space.LOCAL) {
  69972. this.getLocalMatrix().getRotationMatrixToRef(result);
  69973. }
  69974. else {
  69975. var mat = Bone._tmpMats[0];
  69976. var amat = this.getAbsoluteTransform();
  69977. if (mesh) {
  69978. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  69979. }
  69980. else {
  69981. mat.copyFrom(amat);
  69982. }
  69983. mat.m[0] *= this._scalingDeterminant;
  69984. mat.m[1] *= this._scalingDeterminant;
  69985. mat.m[2] *= this._scalingDeterminant;
  69986. mat.getRotationMatrixToRef(result);
  69987. }
  69988. };
  69989. /**
  69990. * Get the world position of a point that is in the local space of the bone.
  69991. * @param position The local position
  69992. * @param mesh The mesh that this bone is attached to.
  69993. * @returns The world position
  69994. */
  69995. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  69996. if (mesh === void 0) { mesh = null; }
  69997. var result = BABYLON.Vector3.Zero();
  69998. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  69999. return result;
  70000. };
  70001. /**
  70002. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70003. * @param position The local position
  70004. * @param mesh The mesh that this bone is attached to.
  70005. * @param result The vector3 that the world position should be copied to.
  70006. */
  70007. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70008. if (mesh === void 0) { mesh = null; }
  70009. var wm = null;
  70010. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70011. if (mesh) {
  70012. wm = mesh.getWorldMatrix();
  70013. }
  70014. this._skeleton.computeAbsoluteTransforms();
  70015. var tmat = Bone._tmpMats[0];
  70016. if (mesh && wm) {
  70017. tmat.copyFrom(this.getAbsoluteTransform());
  70018. tmat.multiplyToRef(wm, tmat);
  70019. }
  70020. else {
  70021. tmat = this.getAbsoluteTransform();
  70022. }
  70023. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70024. };
  70025. /**
  70026. * Get the local position of a point that is in world space.
  70027. * @param position The world position
  70028. * @param mesh The mesh that this bone is attached to.
  70029. * @returns The local position
  70030. */
  70031. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70032. if (mesh === void 0) { mesh = null; }
  70033. var result = BABYLON.Vector3.Zero();
  70034. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70035. return result;
  70036. };
  70037. /**
  70038. * Get the local position of a point that is in world space and copy it to the result param.
  70039. * @param position The world position
  70040. * @param mesh The mesh that this bone is attached to.
  70041. * @param result The vector3 that the local position should be copied to.
  70042. */
  70043. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70044. if (mesh === void 0) { mesh = null; }
  70045. var wm = null;
  70046. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70047. if (mesh) {
  70048. wm = mesh.getWorldMatrix();
  70049. }
  70050. this._skeleton.computeAbsoluteTransforms();
  70051. var tmat = Bone._tmpMats[0];
  70052. tmat.copyFrom(this.getAbsoluteTransform());
  70053. if (mesh && wm) {
  70054. tmat.multiplyToRef(wm, tmat);
  70055. }
  70056. tmat.invert();
  70057. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70058. };
  70059. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70060. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70061. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70062. return Bone;
  70063. }(BABYLON.Node));
  70064. BABYLON.Bone = Bone;
  70065. })(BABYLON || (BABYLON = {}));
  70066. //# sourceMappingURL=babylon.bone.js.map
  70067. var BABYLON;
  70068. (function (BABYLON) {
  70069. var BoneIKController = /** @class */ (function () {
  70070. function BoneIKController(mesh, bone, options) {
  70071. this.targetPosition = BABYLON.Vector3.Zero();
  70072. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70073. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70074. this.poleAngle = 0;
  70075. this.slerpAmount = 1;
  70076. this._bone1Quat = BABYLON.Quaternion.Identity();
  70077. this._bone1Mat = BABYLON.Matrix.Identity();
  70078. this._bone2Ang = Math.PI;
  70079. this._maxAngle = Math.PI;
  70080. this._rightHandedSystem = false;
  70081. this._bendAxis = BABYLON.Vector3.Right();
  70082. this._slerping = false;
  70083. this._adjustRoll = 0;
  70084. this._bone2 = bone;
  70085. this._bone1 = bone.getParent();
  70086. if (!this._bone1) {
  70087. return;
  70088. }
  70089. this.mesh = mesh;
  70090. var bonePos = bone.getPosition();
  70091. if (bone.getAbsoluteTransform().determinant() > 0) {
  70092. this._rightHandedSystem = true;
  70093. this._bendAxis.x = 0;
  70094. this._bendAxis.y = 0;
  70095. this._bendAxis.z = -1;
  70096. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70097. this._adjustRoll = Math.PI * .5;
  70098. this._bendAxis.z = 1;
  70099. }
  70100. }
  70101. if (this._bone1.length) {
  70102. var boneScale1 = this._bone1.getScale();
  70103. var boneScale2 = this._bone2.getScale();
  70104. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70105. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70106. }
  70107. else if (this._bone1.children[0]) {
  70108. mesh.computeWorldMatrix(true);
  70109. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70110. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70111. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70112. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70113. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70114. }
  70115. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70116. this.maxAngle = Math.PI;
  70117. if (options) {
  70118. if (options.targetMesh) {
  70119. this.targetMesh = options.targetMesh;
  70120. this.targetMesh.computeWorldMatrix(true);
  70121. }
  70122. if (options.poleTargetMesh) {
  70123. this.poleTargetMesh = options.poleTargetMesh;
  70124. this.poleTargetMesh.computeWorldMatrix(true);
  70125. }
  70126. else if (options.poleTargetBone) {
  70127. this.poleTargetBone = options.poleTargetBone;
  70128. }
  70129. else if (this._bone1.getParent()) {
  70130. this.poleTargetBone = this._bone1.getParent();
  70131. }
  70132. if (options.poleTargetLocalOffset) {
  70133. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70134. }
  70135. if (options.poleAngle) {
  70136. this.poleAngle = options.poleAngle;
  70137. }
  70138. if (options.bendAxis) {
  70139. this._bendAxis.copyFrom(options.bendAxis);
  70140. }
  70141. if (options.maxAngle) {
  70142. this.maxAngle = options.maxAngle;
  70143. }
  70144. if (options.slerpAmount) {
  70145. this.slerpAmount = options.slerpAmount;
  70146. }
  70147. }
  70148. }
  70149. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70150. get: function () {
  70151. return this._maxAngle;
  70152. },
  70153. set: function (value) {
  70154. this._setMaxAngle(value);
  70155. },
  70156. enumerable: true,
  70157. configurable: true
  70158. });
  70159. BoneIKController.prototype._setMaxAngle = function (ang) {
  70160. if (ang < 0) {
  70161. ang = 0;
  70162. }
  70163. if (ang > Math.PI || ang == undefined) {
  70164. ang = Math.PI;
  70165. }
  70166. this._maxAngle = ang;
  70167. var a = this._bone1Length;
  70168. var b = this._bone2Length;
  70169. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70170. };
  70171. BoneIKController.prototype.update = function () {
  70172. var bone1 = this._bone1;
  70173. if (!bone1) {
  70174. return;
  70175. }
  70176. var target = this.targetPosition;
  70177. var poleTarget = this.poleTargetPosition;
  70178. var mat1 = BoneIKController._tmpMats[0];
  70179. var mat2 = BoneIKController._tmpMats[1];
  70180. if (this.targetMesh) {
  70181. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70182. }
  70183. if (this.poleTargetBone) {
  70184. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70185. }
  70186. else if (this.poleTargetMesh) {
  70187. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70188. }
  70189. var bonePos = BoneIKController._tmpVecs[0];
  70190. var zaxis = BoneIKController._tmpVecs[1];
  70191. var xaxis = BoneIKController._tmpVecs[2];
  70192. var yaxis = BoneIKController._tmpVecs[3];
  70193. var upAxis = BoneIKController._tmpVecs[4];
  70194. var _tmpQuat = BoneIKController._tmpQuat;
  70195. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70196. poleTarget.subtractToRef(bonePos, upAxis);
  70197. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70198. upAxis.y = 1;
  70199. }
  70200. else {
  70201. upAxis.normalize();
  70202. }
  70203. target.subtractToRef(bonePos, yaxis);
  70204. yaxis.normalize();
  70205. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70206. zaxis.normalize();
  70207. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70208. xaxis.normalize();
  70209. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70210. var a = this._bone1Length;
  70211. var b = this._bone2Length;
  70212. var c = BABYLON.Vector3.Distance(bonePos, target);
  70213. if (this._maxReach > 0) {
  70214. c = Math.min(this._maxReach, c);
  70215. }
  70216. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70217. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70218. if (acosa > 1) {
  70219. acosa = 1;
  70220. }
  70221. if (acosb > 1) {
  70222. acosb = 1;
  70223. }
  70224. if (acosa < -1) {
  70225. acosa = -1;
  70226. }
  70227. if (acosb < -1) {
  70228. acosb = -1;
  70229. }
  70230. var angA = Math.acos(acosa);
  70231. var angB = Math.acos(acosb);
  70232. var angC = -angA - angB;
  70233. if (this._rightHandedSystem) {
  70234. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70235. mat2.multiplyToRef(mat1, mat1);
  70236. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70237. mat2.multiplyToRef(mat1, mat1);
  70238. }
  70239. else {
  70240. var _tmpVec = BoneIKController._tmpVecs[5];
  70241. _tmpVec.copyFrom(this._bendAxis);
  70242. _tmpVec.x *= -1;
  70243. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70244. mat2.multiplyToRef(mat1, mat1);
  70245. }
  70246. if (this.poleAngle) {
  70247. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70248. mat1.multiplyToRef(mat2, mat1);
  70249. }
  70250. if (this._bone1) {
  70251. if (this.slerpAmount < 1) {
  70252. if (!this._slerping) {
  70253. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70254. }
  70255. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70256. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70257. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70258. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70259. this._slerping = true;
  70260. }
  70261. else {
  70262. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70263. this._bone1Mat.copyFrom(mat1);
  70264. this._slerping = false;
  70265. }
  70266. }
  70267. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70268. this._bone2Ang = angC;
  70269. };
  70270. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70271. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70272. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70273. return BoneIKController;
  70274. }());
  70275. BABYLON.BoneIKController = BoneIKController;
  70276. })(BABYLON || (BABYLON = {}));
  70277. //# sourceMappingURL=babylon.boneIKController.js.map
  70278. var BABYLON;
  70279. (function (BABYLON) {
  70280. var BoneLookController = /** @class */ (function () {
  70281. /**
  70282. * Create a BoneLookController
  70283. * @param mesh the mesh that the bone belongs to
  70284. * @param bone the bone that will be looking to the target
  70285. * @param target the target Vector3 to look at
  70286. * @param settings optional settings:
  70287. * - maxYaw: the maximum angle the bone will yaw to
  70288. * - minYaw: the minimum angle the bone will yaw to
  70289. * - maxPitch: the maximum angle the bone will pitch to
  70290. * - minPitch: the minimum angle the bone will yaw to
  70291. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70292. * - upAxis: the up axis of the coordinate system
  70293. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70294. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70295. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70296. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70297. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70298. * - adjustRoll: used to make an adjustment to the roll of the bone
  70299. **/
  70300. function BoneLookController(mesh, bone, target, options) {
  70301. /**
  70302. * The up axis of the coordinate system that is used when the bone is rotated.
  70303. */
  70304. this.upAxis = BABYLON.Vector3.Up();
  70305. /**
  70306. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70307. */
  70308. this.upAxisSpace = BABYLON.Space.LOCAL;
  70309. /**
  70310. * Used to make an adjustment to the yaw of the bone.
  70311. */
  70312. this.adjustYaw = 0;
  70313. /**
  70314. * Used to make an adjustment to the pitch of the bone.
  70315. */
  70316. this.adjustPitch = 0;
  70317. /**
  70318. * Used to make an adjustment to the roll of the bone.
  70319. */
  70320. this.adjustRoll = 0;
  70321. /**
  70322. * 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).
  70323. */
  70324. this.slerpAmount = 1;
  70325. this._boneQuat = BABYLON.Quaternion.Identity();
  70326. this._slerping = false;
  70327. this._firstFrameSkipped = false;
  70328. this._fowardAxis = BABYLON.Vector3.Forward();
  70329. this.mesh = mesh;
  70330. this.bone = bone;
  70331. this.target = target;
  70332. if (options) {
  70333. if (options.adjustYaw) {
  70334. this.adjustYaw = options.adjustYaw;
  70335. }
  70336. if (options.adjustPitch) {
  70337. this.adjustPitch = options.adjustPitch;
  70338. }
  70339. if (options.adjustRoll) {
  70340. this.adjustRoll = options.adjustRoll;
  70341. }
  70342. if (options.maxYaw != null) {
  70343. this.maxYaw = options.maxYaw;
  70344. }
  70345. else {
  70346. this.maxYaw = Math.PI;
  70347. }
  70348. if (options.minYaw != null) {
  70349. this.minYaw = options.minYaw;
  70350. }
  70351. else {
  70352. this.minYaw = -Math.PI;
  70353. }
  70354. if (options.maxPitch != null) {
  70355. this.maxPitch = options.maxPitch;
  70356. }
  70357. else {
  70358. this.maxPitch = Math.PI;
  70359. }
  70360. if (options.minPitch != null) {
  70361. this.minPitch = options.minPitch;
  70362. }
  70363. else {
  70364. this.minPitch = -Math.PI;
  70365. }
  70366. if (options.slerpAmount != null) {
  70367. this.slerpAmount = options.slerpAmount;
  70368. }
  70369. if (options.upAxis != null) {
  70370. this.upAxis = options.upAxis;
  70371. }
  70372. if (options.upAxisSpace != null) {
  70373. this.upAxisSpace = options.upAxisSpace;
  70374. }
  70375. if (options.yawAxis != null || options.pitchAxis != null) {
  70376. var newYawAxis = BABYLON.Axis.Y;
  70377. var newPitchAxis = BABYLON.Axis.X;
  70378. if (options.yawAxis != null) {
  70379. newYawAxis = options.yawAxis.clone();
  70380. newYawAxis.normalize();
  70381. }
  70382. if (options.pitchAxis != null) {
  70383. newPitchAxis = options.pitchAxis.clone();
  70384. newPitchAxis.normalize();
  70385. }
  70386. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70387. this._transformYawPitch = BABYLON.Matrix.Identity();
  70388. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70389. this._transformYawPitchInv = this._transformYawPitch.clone();
  70390. this._transformYawPitch.invert();
  70391. }
  70392. }
  70393. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70394. this.upAxisSpace = BABYLON.Space.LOCAL;
  70395. }
  70396. }
  70397. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70398. /**
  70399. * Get/set the minimum yaw angle that the bone can look to.
  70400. */
  70401. get: function () {
  70402. return this._minYaw;
  70403. },
  70404. set: function (value) {
  70405. this._minYaw = value;
  70406. this._minYawSin = Math.sin(value);
  70407. this._minYawCos = Math.cos(value);
  70408. if (this._maxYaw != null) {
  70409. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70410. this._yawRange = this._maxYaw - this._minYaw;
  70411. }
  70412. },
  70413. enumerable: true,
  70414. configurable: true
  70415. });
  70416. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  70417. /**
  70418. * Get/set the maximum yaw angle that the bone can look to.
  70419. */
  70420. get: function () {
  70421. return this._maxYaw;
  70422. },
  70423. set: function (value) {
  70424. this._maxYaw = value;
  70425. this._maxYawSin = Math.sin(value);
  70426. this._maxYawCos = Math.cos(value);
  70427. if (this._minYaw != null) {
  70428. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70429. this._yawRange = this._maxYaw - this._minYaw;
  70430. }
  70431. },
  70432. enumerable: true,
  70433. configurable: true
  70434. });
  70435. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  70436. /**
  70437. * Get/set the minimum pitch angle that the bone can look to.
  70438. */
  70439. get: function () {
  70440. return this._minPitch;
  70441. },
  70442. set: function (value) {
  70443. this._minPitch = value;
  70444. this._minPitchTan = Math.tan(value);
  70445. },
  70446. enumerable: true,
  70447. configurable: true
  70448. });
  70449. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  70450. /**
  70451. * Get/set the maximum pitch angle that the bone can look to.
  70452. */
  70453. get: function () {
  70454. return this._maxPitch;
  70455. },
  70456. set: function (value) {
  70457. this._maxPitch = value;
  70458. this._maxPitchTan = Math.tan(value);
  70459. },
  70460. enumerable: true,
  70461. configurable: true
  70462. });
  70463. /**
  70464. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  70465. */
  70466. BoneLookController.prototype.update = function () {
  70467. //skip the first frame when slerping so that the mesh rotation is correct
  70468. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  70469. this._firstFrameSkipped = true;
  70470. return;
  70471. }
  70472. var bone = this.bone;
  70473. var bonePos = BoneLookController._tmpVecs[0];
  70474. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  70475. var target = this.target;
  70476. var _tmpMat1 = BoneLookController._tmpMats[0];
  70477. var _tmpMat2 = BoneLookController._tmpMats[1];
  70478. var mesh = this.mesh;
  70479. var parentBone = bone.getParent();
  70480. var upAxis = BoneLookController._tmpVecs[1];
  70481. upAxis.copyFrom(this.upAxis);
  70482. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  70483. if (this._transformYawPitch) {
  70484. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  70485. }
  70486. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  70487. }
  70488. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  70489. mesh.getDirectionToRef(upAxis, upAxis);
  70490. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  70491. upAxis.normalize();
  70492. }
  70493. }
  70494. var checkYaw = false;
  70495. var checkPitch = false;
  70496. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  70497. checkYaw = true;
  70498. }
  70499. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  70500. checkPitch = true;
  70501. }
  70502. if (checkYaw || checkPitch) {
  70503. var spaceMat = BoneLookController._tmpMats[2];
  70504. var spaceMatInv = BoneLookController._tmpMats[3];
  70505. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  70506. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  70507. }
  70508. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  70509. spaceMat.copyFrom(mesh.getWorldMatrix());
  70510. }
  70511. else {
  70512. var forwardAxis = BoneLookController._tmpVecs[2];
  70513. forwardAxis.copyFrom(this._fowardAxis);
  70514. if (this._transformYawPitch) {
  70515. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  70516. }
  70517. if (parentBone) {
  70518. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  70519. }
  70520. else {
  70521. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  70522. }
  70523. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  70524. rightAxis.normalize();
  70525. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  70526. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  70527. }
  70528. spaceMat.invertToRef(spaceMatInv);
  70529. var xzlen = null;
  70530. if (checkPitch) {
  70531. var localTarget = BoneLookController._tmpVecs[3];
  70532. target.subtractToRef(bonePos, localTarget);
  70533. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70534. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70535. var pitch = Math.atan2(localTarget.y, xzlen);
  70536. var newPitch = pitch;
  70537. if (pitch > this._maxPitch) {
  70538. localTarget.y = this._maxPitchTan * xzlen;
  70539. newPitch = this._maxPitch;
  70540. }
  70541. else if (pitch < this._minPitch) {
  70542. localTarget.y = this._minPitchTan * xzlen;
  70543. newPitch = this._minPitch;
  70544. }
  70545. if (pitch != newPitch) {
  70546. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70547. localTarget.addInPlace(bonePos);
  70548. target = localTarget;
  70549. }
  70550. }
  70551. if (checkYaw) {
  70552. var localTarget = BoneLookController._tmpVecs[4];
  70553. target.subtractToRef(bonePos, localTarget);
  70554. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  70555. var yaw = Math.atan2(localTarget.x, localTarget.z);
  70556. var newYaw = yaw;
  70557. if (yaw > this._maxYaw || yaw < this._minYaw) {
  70558. if (xzlen == null) {
  70559. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70560. }
  70561. if (this._yawRange > Math.PI) {
  70562. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  70563. localTarget.z = this._maxYawCos * xzlen;
  70564. localTarget.x = this._maxYawSin * xzlen;
  70565. newYaw = this._maxYaw;
  70566. }
  70567. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  70568. localTarget.z = this._minYawCos * xzlen;
  70569. localTarget.x = this._minYawSin * xzlen;
  70570. newYaw = this._minYaw;
  70571. }
  70572. }
  70573. else {
  70574. if (yaw > this._maxYaw) {
  70575. localTarget.z = this._maxYawCos * xzlen;
  70576. localTarget.x = this._maxYawSin * xzlen;
  70577. newYaw = this._maxYaw;
  70578. }
  70579. else if (yaw < this._minYaw) {
  70580. localTarget.z = this._minYawCos * xzlen;
  70581. localTarget.x = this._minYawSin * xzlen;
  70582. newYaw = this._minYaw;
  70583. }
  70584. }
  70585. }
  70586. if (this._slerping && this._yawRange > Math.PI) {
  70587. //are we going to be crossing into the min/max region?
  70588. var boneFwd = BoneLookController._tmpVecs[8];
  70589. boneFwd.copyFrom(BABYLON.Axis.Z);
  70590. if (this._transformYawPitch) {
  70591. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  70592. }
  70593. var boneRotMat = BoneLookController._tmpMats[4];
  70594. this._boneQuat.toRotationMatrix(boneRotMat);
  70595. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  70596. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  70597. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  70598. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  70599. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  70600. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  70601. if (angBtwTar > angBtwMidYaw) {
  70602. if (xzlen == null) {
  70603. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  70604. }
  70605. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  70606. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  70607. if (angBtwMin < angBtwMax) {
  70608. newYaw = boneYaw + Math.PI * .75;
  70609. localTarget.z = Math.cos(newYaw) * xzlen;
  70610. localTarget.x = Math.sin(newYaw) * xzlen;
  70611. }
  70612. else {
  70613. newYaw = boneYaw - Math.PI * .75;
  70614. localTarget.z = Math.cos(newYaw) * xzlen;
  70615. localTarget.x = Math.sin(newYaw) * xzlen;
  70616. }
  70617. }
  70618. }
  70619. if (yaw != newYaw) {
  70620. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  70621. localTarget.addInPlace(bonePos);
  70622. target = localTarget;
  70623. }
  70624. }
  70625. }
  70626. var zaxis = BoneLookController._tmpVecs[5];
  70627. var xaxis = BoneLookController._tmpVecs[6];
  70628. var yaxis = BoneLookController._tmpVecs[7];
  70629. var _tmpQuat = BoneLookController._tmpQuat;
  70630. target.subtractToRef(bonePos, zaxis);
  70631. zaxis.normalize();
  70632. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  70633. xaxis.normalize();
  70634. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  70635. yaxis.normalize();
  70636. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  70637. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  70638. return;
  70639. }
  70640. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  70641. return;
  70642. }
  70643. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  70644. return;
  70645. }
  70646. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  70647. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  70648. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  70649. }
  70650. if (this.slerpAmount < 1) {
  70651. if (!this._slerping) {
  70652. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  70653. }
  70654. if (this._transformYawPitch) {
  70655. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70656. }
  70657. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  70658. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  70659. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  70660. this._slerping = true;
  70661. }
  70662. else {
  70663. if (this._transformYawPitch) {
  70664. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  70665. }
  70666. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  70667. this._slerping = false;
  70668. }
  70669. };
  70670. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  70671. var angDiff = ang2 - ang1;
  70672. angDiff %= Math.PI * 2;
  70673. if (angDiff > Math.PI) {
  70674. angDiff -= Math.PI * 2;
  70675. }
  70676. else if (angDiff < -Math.PI) {
  70677. angDiff += Math.PI * 2;
  70678. }
  70679. return angDiff;
  70680. };
  70681. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  70682. ang1 %= (2 * Math.PI);
  70683. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70684. ang2 %= (2 * Math.PI);
  70685. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70686. var ab = 0;
  70687. if (ang1 < ang2) {
  70688. ab = ang2 - ang1;
  70689. }
  70690. else {
  70691. ab = ang1 - ang2;
  70692. }
  70693. if (ab > Math.PI) {
  70694. ab = Math.PI * 2 - ab;
  70695. }
  70696. return ab;
  70697. };
  70698. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  70699. ang %= (2 * Math.PI);
  70700. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  70701. ang1 %= (2 * Math.PI);
  70702. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  70703. ang2 %= (2 * Math.PI);
  70704. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  70705. if (ang1 < ang2) {
  70706. if (ang > ang1 && ang < ang2) {
  70707. return true;
  70708. }
  70709. }
  70710. else {
  70711. if (ang > ang2 && ang < ang1) {
  70712. return true;
  70713. }
  70714. }
  70715. return false;
  70716. };
  70717. 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()];
  70718. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  70719. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70720. return BoneLookController;
  70721. }());
  70722. BABYLON.BoneLookController = BoneLookController;
  70723. })(BABYLON || (BABYLON = {}));
  70724. //# sourceMappingURL=babylon.boneLookController.js.map
  70725. var BABYLON;
  70726. (function (BABYLON) {
  70727. var Skeleton = /** @class */ (function () {
  70728. function Skeleton(name, id, scene) {
  70729. this.name = name;
  70730. this.id = id;
  70731. this.bones = new Array();
  70732. this.needInitialSkinMatrix = false;
  70733. this._isDirty = true;
  70734. this._meshesWithPoseMatrix = new Array();
  70735. this._identity = BABYLON.Matrix.Identity();
  70736. this._ranges = {};
  70737. this._lastAbsoluteTransformsUpdateId = -1;
  70738. /**
  70739. * Specifies if the skeleton should be serialized.
  70740. */
  70741. this.doNotSerialize = false;
  70742. // Events
  70743. /**
  70744. * An event triggered before computing the skeleton's matrices
  70745. * @type {BABYLON.Observable}
  70746. */
  70747. this.onBeforeComputeObservable = new BABYLON.Observable();
  70748. this.bones = [];
  70749. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70750. scene.skeletons.push(this);
  70751. //make sure it will recalculate the matrix next time prepare is called.
  70752. this._isDirty = true;
  70753. }
  70754. // Members
  70755. Skeleton.prototype.getTransformMatrices = function (mesh) {
  70756. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  70757. return mesh._bonesTransformMatrices;
  70758. }
  70759. if (!this._transformMatrices) {
  70760. this.prepare();
  70761. }
  70762. return this._transformMatrices;
  70763. };
  70764. Skeleton.prototype.getScene = function () {
  70765. return this._scene;
  70766. };
  70767. // Methods
  70768. /**
  70769. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  70770. */
  70771. Skeleton.prototype.toString = function (fullDetails) {
  70772. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  70773. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  70774. if (fullDetails) {
  70775. ret += ", Ranges: {";
  70776. var first = true;
  70777. for (var name_1 in this._ranges) {
  70778. if (first) {
  70779. ret += ", ";
  70780. first = false;
  70781. }
  70782. ret += name_1;
  70783. }
  70784. ret += "}";
  70785. }
  70786. return ret;
  70787. };
  70788. /**
  70789. * Get bone's index searching by name
  70790. * @param {string} name is bone's name to search for
  70791. * @return {number} Indice of the bone. Returns -1 if not found
  70792. */
  70793. Skeleton.prototype.getBoneIndexByName = function (name) {
  70794. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  70795. if (this.bones[boneIndex].name === name) {
  70796. return boneIndex;
  70797. }
  70798. }
  70799. return -1;
  70800. };
  70801. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  70802. // check name not already in use
  70803. if (!this._ranges[name]) {
  70804. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  70805. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70806. if (this.bones[i].animations[0]) {
  70807. this.bones[i].animations[0].createRange(name, from, to);
  70808. }
  70809. }
  70810. }
  70811. };
  70812. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  70813. if (deleteFrames === void 0) { deleteFrames = true; }
  70814. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70815. if (this.bones[i].animations[0]) {
  70816. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  70817. }
  70818. }
  70819. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  70820. };
  70821. Skeleton.prototype.getAnimationRange = function (name) {
  70822. return this._ranges[name];
  70823. };
  70824. /**
  70825. * Returns as an Array, all AnimationRanges defined on this skeleton
  70826. */
  70827. Skeleton.prototype.getAnimationRanges = function () {
  70828. var animationRanges = [];
  70829. var name;
  70830. var i = 0;
  70831. for (name in this._ranges) {
  70832. animationRanges[i] = this._ranges[name];
  70833. i++;
  70834. }
  70835. return animationRanges;
  70836. };
  70837. /**
  70838. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  70839. */
  70840. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  70841. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  70842. if (this._ranges[name] || !source.getAnimationRange(name)) {
  70843. return false;
  70844. }
  70845. var ret = true;
  70846. var frameOffset = this._getHighestAnimationFrame() + 1;
  70847. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  70848. var boneDict = {};
  70849. var sourceBones = source.bones;
  70850. var nBones;
  70851. var i;
  70852. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  70853. boneDict[sourceBones[i].name] = sourceBones[i];
  70854. }
  70855. if (this.bones.length !== sourceBones.length) {
  70856. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  70857. ret = false;
  70858. }
  70859. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  70860. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  70861. var boneName = this.bones[i].name;
  70862. var sourceBone = boneDict[boneName];
  70863. if (sourceBone) {
  70864. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  70865. }
  70866. else {
  70867. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  70868. ret = false;
  70869. }
  70870. }
  70871. // do not call createAnimationRange(), since it also is done to bones, which was already done
  70872. var range = source.getAnimationRange(name);
  70873. if (range) {
  70874. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  70875. }
  70876. return ret;
  70877. };
  70878. Skeleton.prototype.returnToRest = function () {
  70879. for (var index = 0; index < this.bones.length; index++) {
  70880. this.bones[index].returnToRest();
  70881. }
  70882. };
  70883. Skeleton.prototype._getHighestAnimationFrame = function () {
  70884. var ret = 0;
  70885. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  70886. if (this.bones[i].animations[0]) {
  70887. var highest = this.bones[i].animations[0].getHighestFrame();
  70888. if (ret < highest) {
  70889. ret = highest;
  70890. }
  70891. }
  70892. }
  70893. return ret;
  70894. };
  70895. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  70896. var range = this.getAnimationRange(name);
  70897. if (!range) {
  70898. return null;
  70899. }
  70900. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  70901. };
  70902. Skeleton.prototype._markAsDirty = function () {
  70903. this._isDirty = true;
  70904. };
  70905. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  70906. this._meshesWithPoseMatrix.push(mesh);
  70907. };
  70908. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  70909. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  70910. if (index > -1) {
  70911. this._meshesWithPoseMatrix.splice(index, 1);
  70912. }
  70913. };
  70914. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  70915. this.onBeforeComputeObservable.notifyObservers(this);
  70916. for (var index = 0; index < this.bones.length; index++) {
  70917. var bone = this.bones[index];
  70918. var parentBone = bone.getParent();
  70919. if (parentBone) {
  70920. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  70921. }
  70922. else {
  70923. if (initialSkinMatrix) {
  70924. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  70925. }
  70926. else {
  70927. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  70928. }
  70929. }
  70930. if (bone._index !== -1) {
  70931. var mappedIndex = bone._index === null ? index : bone._index;
  70932. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  70933. }
  70934. }
  70935. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  70936. };
  70937. Skeleton.prototype.prepare = function () {
  70938. if (!this._isDirty) {
  70939. return;
  70940. }
  70941. if (this.needInitialSkinMatrix) {
  70942. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  70943. var mesh = this._meshesWithPoseMatrix[index];
  70944. var poseMatrix = mesh.getPoseMatrix();
  70945. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  70946. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70947. }
  70948. if (this._synchronizedWithMesh !== mesh) {
  70949. this._synchronizedWithMesh = mesh;
  70950. // Prepare bones
  70951. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  70952. var bone = this.bones[boneIndex];
  70953. if (!bone.getParent()) {
  70954. var matrix = bone.getBaseMatrix();
  70955. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  70956. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  70957. }
  70958. }
  70959. }
  70960. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  70961. }
  70962. }
  70963. else {
  70964. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  70965. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  70966. }
  70967. this._computeTransformMatrices(this._transformMatrices, null);
  70968. }
  70969. this._isDirty = false;
  70970. this._scene._activeBones.addCount(this.bones.length, false);
  70971. };
  70972. Skeleton.prototype.getAnimatables = function () {
  70973. if (!this._animatables || this._animatables.length !== this.bones.length) {
  70974. this._animatables = [];
  70975. for (var index = 0; index < this.bones.length; index++) {
  70976. this._animatables.push(this.bones[index]);
  70977. }
  70978. }
  70979. return this._animatables;
  70980. };
  70981. Skeleton.prototype.clone = function (name, id) {
  70982. var result = new Skeleton(name, id || name, this._scene);
  70983. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  70984. for (var index = 0; index < this.bones.length; index++) {
  70985. var source = this.bones[index];
  70986. var parentBone = null;
  70987. var parent_1 = source.getParent();
  70988. if (parent_1) {
  70989. var parentIndex = this.bones.indexOf(parent_1);
  70990. parentBone = result.bones[parentIndex];
  70991. }
  70992. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  70993. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  70994. }
  70995. if (this._ranges) {
  70996. result._ranges = {};
  70997. for (var rangeName in this._ranges) {
  70998. var range = this._ranges[rangeName];
  70999. if (range) {
  71000. result._ranges[rangeName] = range.clone();
  71001. }
  71002. }
  71003. }
  71004. this._isDirty = true;
  71005. return result;
  71006. };
  71007. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71008. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71009. this.bones.forEach(function (bone) {
  71010. bone.animations.forEach(function (animation) {
  71011. animation.enableBlending = true;
  71012. animation.blendingSpeed = blendingSpeed;
  71013. });
  71014. });
  71015. };
  71016. Skeleton.prototype.dispose = function () {
  71017. this._meshesWithPoseMatrix = [];
  71018. // Animations
  71019. this.getScene().stopAnimation(this);
  71020. // Remove from scene
  71021. this.getScene().removeSkeleton(this);
  71022. };
  71023. Skeleton.prototype.serialize = function () {
  71024. var serializationObject = {};
  71025. serializationObject.name = this.name;
  71026. serializationObject.id = this.id;
  71027. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71028. serializationObject.bones = [];
  71029. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71030. for (var index = 0; index < this.bones.length; index++) {
  71031. var bone = this.bones[index];
  71032. var parent_2 = bone.getParent();
  71033. var serializedBone = {
  71034. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71035. name: bone.name,
  71036. matrix: bone.getBaseMatrix().toArray(),
  71037. rest: bone.getRestPose().toArray()
  71038. };
  71039. serializationObject.bones.push(serializedBone);
  71040. if (bone.length) {
  71041. serializedBone.length = bone.length;
  71042. }
  71043. if (bone.animations && bone.animations.length > 0) {
  71044. serializedBone.animation = bone.animations[0].serialize();
  71045. }
  71046. serializationObject.ranges = [];
  71047. for (var name in this._ranges) {
  71048. var source = this._ranges[name];
  71049. if (!source) {
  71050. continue;
  71051. }
  71052. var range = {};
  71053. range.name = name;
  71054. range.from = source.from;
  71055. range.to = source.to;
  71056. serializationObject.ranges.push(range);
  71057. }
  71058. }
  71059. return serializationObject;
  71060. };
  71061. Skeleton.Parse = function (parsedSkeleton, scene) {
  71062. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71063. if (parsedSkeleton.dimensionsAtRest) {
  71064. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71065. }
  71066. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71067. var index;
  71068. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71069. var parsedBone = parsedSkeleton.bones[index];
  71070. var parentBone = null;
  71071. if (parsedBone.parentBoneIndex > -1) {
  71072. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71073. }
  71074. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71075. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71076. if (parsedBone.length) {
  71077. bone.length = parsedBone.length;
  71078. }
  71079. if (parsedBone.animation) {
  71080. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71081. }
  71082. }
  71083. // placed after bones, so createAnimationRange can cascade down
  71084. if (parsedSkeleton.ranges) {
  71085. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71086. var data = parsedSkeleton.ranges[index];
  71087. skeleton.createAnimationRange(data.name, data.from, data.to);
  71088. }
  71089. }
  71090. return skeleton;
  71091. };
  71092. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71093. if (forceUpdate === void 0) { forceUpdate = false; }
  71094. var renderId = this._scene.getRenderId();
  71095. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71096. this.bones[0].computeAbsoluteTransforms();
  71097. this._lastAbsoluteTransformsUpdateId = renderId;
  71098. }
  71099. };
  71100. Skeleton.prototype.getPoseMatrix = function () {
  71101. var poseMatrix = null;
  71102. if (this._meshesWithPoseMatrix.length > 0) {
  71103. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71104. }
  71105. return poseMatrix;
  71106. };
  71107. Skeleton.prototype.sortBones = function () {
  71108. var bones = new Array();
  71109. var visited = new Array(this.bones.length);
  71110. for (var index = 0; index < this.bones.length; index++) {
  71111. this._sortBones(index, bones, visited);
  71112. }
  71113. this.bones = bones;
  71114. };
  71115. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71116. if (visited[index]) {
  71117. return;
  71118. }
  71119. visited[index] = true;
  71120. var bone = this.bones[index];
  71121. if (bone._index === undefined) {
  71122. bone._index = index;
  71123. }
  71124. var parentBone = bone.getParent();
  71125. if (parentBone) {
  71126. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71127. }
  71128. bones.push(bone);
  71129. };
  71130. return Skeleton;
  71131. }());
  71132. BABYLON.Skeleton = Skeleton;
  71133. })(BABYLON || (BABYLON = {}));
  71134. //# sourceMappingURL=babylon.skeleton.js.map
  71135. var BABYLON;
  71136. (function (BABYLON) {
  71137. var SphericalPolynomial = /** @class */ (function () {
  71138. function SphericalPolynomial() {
  71139. this.x = BABYLON.Vector3.Zero();
  71140. this.y = BABYLON.Vector3.Zero();
  71141. this.z = BABYLON.Vector3.Zero();
  71142. this.xx = BABYLON.Vector3.Zero();
  71143. this.yy = BABYLON.Vector3.Zero();
  71144. this.zz = BABYLON.Vector3.Zero();
  71145. this.xy = BABYLON.Vector3.Zero();
  71146. this.yz = BABYLON.Vector3.Zero();
  71147. this.zx = BABYLON.Vector3.Zero();
  71148. }
  71149. SphericalPolynomial.prototype.addAmbient = function (color) {
  71150. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71151. this.xx = this.xx.add(colorVector);
  71152. this.yy = this.yy.add(colorVector);
  71153. this.zz = this.zz.add(colorVector);
  71154. };
  71155. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71156. var result = new SphericalPolynomial();
  71157. result.x = harmonics.L11.scale(1.02333);
  71158. result.y = harmonics.L1_1.scale(1.02333);
  71159. result.z = harmonics.L10.scale(1.02333);
  71160. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71161. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71162. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71163. result.yz = harmonics.L2_1.scale(0.858086);
  71164. result.zx = harmonics.L21.scale(0.858086);
  71165. result.xy = harmonics.L2_2.scale(0.858086);
  71166. result.scale(1.0 / Math.PI);
  71167. return result;
  71168. };
  71169. SphericalPolynomial.prototype.scale = function (scale) {
  71170. this.x = this.x.scale(scale);
  71171. this.y = this.y.scale(scale);
  71172. this.z = this.z.scale(scale);
  71173. this.xx = this.xx.scale(scale);
  71174. this.yy = this.yy.scale(scale);
  71175. this.zz = this.zz.scale(scale);
  71176. this.yz = this.yz.scale(scale);
  71177. this.zx = this.zx.scale(scale);
  71178. this.xy = this.xy.scale(scale);
  71179. };
  71180. return SphericalPolynomial;
  71181. }());
  71182. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71183. var SphericalHarmonics = /** @class */ (function () {
  71184. function SphericalHarmonics() {
  71185. this.L00 = BABYLON.Vector3.Zero();
  71186. this.L1_1 = BABYLON.Vector3.Zero();
  71187. this.L10 = BABYLON.Vector3.Zero();
  71188. this.L11 = BABYLON.Vector3.Zero();
  71189. this.L2_2 = BABYLON.Vector3.Zero();
  71190. this.L2_1 = BABYLON.Vector3.Zero();
  71191. this.L20 = BABYLON.Vector3.Zero();
  71192. this.L21 = BABYLON.Vector3.Zero();
  71193. this.L22 = BABYLON.Vector3.Zero();
  71194. }
  71195. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71196. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71197. var c = colorVector.scale(deltaSolidAngle);
  71198. this.L00 = this.L00.add(c.scale(0.282095));
  71199. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71200. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71201. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71202. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71203. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71204. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71205. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71206. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71207. };
  71208. SphericalHarmonics.prototype.scale = function (scale) {
  71209. this.L00 = this.L00.scale(scale);
  71210. this.L1_1 = this.L1_1.scale(scale);
  71211. this.L10 = this.L10.scale(scale);
  71212. this.L11 = this.L11.scale(scale);
  71213. this.L2_2 = this.L2_2.scale(scale);
  71214. this.L2_1 = this.L2_1.scale(scale);
  71215. this.L20 = this.L20.scale(scale);
  71216. this.L21 = this.L21.scale(scale);
  71217. this.L22 = this.L22.scale(scale);
  71218. };
  71219. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71220. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71221. //
  71222. // E_lm = A_l * L_lm
  71223. //
  71224. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71225. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71226. // the scaling factors are given in equation 9.
  71227. // Constant (Band 0)
  71228. this.L00 = this.L00.scale(3.141593);
  71229. // Linear (Band 1)
  71230. this.L1_1 = this.L1_1.scale(2.094395);
  71231. this.L10 = this.L10.scale(2.094395);
  71232. this.L11 = this.L11.scale(2.094395);
  71233. // Quadratic (Band 2)
  71234. this.L2_2 = this.L2_2.scale(0.785398);
  71235. this.L2_1 = this.L2_1.scale(0.785398);
  71236. this.L20 = this.L20.scale(0.785398);
  71237. this.L21 = this.L21.scale(0.785398);
  71238. this.L22 = this.L22.scale(0.785398);
  71239. };
  71240. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71241. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71242. // L = (1/pi) * E * rho
  71243. //
  71244. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71245. this.scale(1.0 / Math.PI);
  71246. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71247. // (The pixel shader must apply albedo after texture fetches, etc).
  71248. };
  71249. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71250. var result = new SphericalHarmonics();
  71251. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71252. result.L1_1 = polynomial.y.scale(0.977204);
  71253. result.L10 = polynomial.z.scale(0.977204);
  71254. result.L11 = polynomial.x.scale(0.977204);
  71255. result.L2_2 = polynomial.xy.scale(1.16538);
  71256. result.L2_1 = polynomial.yz.scale(1.16538);
  71257. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71258. result.L21 = polynomial.zx.scale(1.16538);
  71259. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71260. result.scale(Math.PI);
  71261. return result;
  71262. };
  71263. return SphericalHarmonics;
  71264. }());
  71265. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71266. })(BABYLON || (BABYLON = {}));
  71267. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71268. var BABYLON;
  71269. (function (BABYLON) {
  71270. var FileFaceOrientation = /** @class */ (function () {
  71271. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71272. this.name = name;
  71273. this.worldAxisForNormal = worldAxisForNormal;
  71274. this.worldAxisForFileX = worldAxisForFileX;
  71275. this.worldAxisForFileY = worldAxisForFileY;
  71276. }
  71277. return FileFaceOrientation;
  71278. }());
  71279. ;
  71280. /**
  71281. * Helper class dealing with the extraction of spherical polynomial dataArray
  71282. * from a cube map.
  71283. */
  71284. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71285. function CubeMapToSphericalPolynomialTools() {
  71286. }
  71287. /**
  71288. * Converts a texture to the according Spherical Polynomial data.
  71289. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71290. *
  71291. * @param texture The texture to extract the information from.
  71292. * @return The Spherical Polynomial data.
  71293. */
  71294. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71295. if (!texture.isCube) {
  71296. // Only supports cube Textures currently.
  71297. return null;
  71298. }
  71299. var size = texture.getSize().width;
  71300. var right = texture.readPixels(0);
  71301. var left = texture.readPixels(1);
  71302. var up;
  71303. var down;
  71304. if (texture.isRenderTarget) {
  71305. up = texture.readPixels(3);
  71306. down = texture.readPixels(2);
  71307. }
  71308. else {
  71309. up = texture.readPixels(2);
  71310. down = texture.readPixels(3);
  71311. }
  71312. var front = texture.readPixels(4);
  71313. var back = texture.readPixels(5);
  71314. var gammaSpace = texture.gammaSpace;
  71315. // Always read as RGBA.
  71316. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71317. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71318. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71319. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71320. }
  71321. var cubeInfo = {
  71322. size: size,
  71323. right: right,
  71324. left: left,
  71325. up: up,
  71326. down: down,
  71327. front: front,
  71328. back: back,
  71329. format: format,
  71330. type: type,
  71331. gammaSpace: gammaSpace,
  71332. };
  71333. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71334. };
  71335. /**
  71336. * Converts a cubemap to the according Spherical Polynomial data.
  71337. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71338. *
  71339. * @param cubeInfo The Cube map to extract the information from.
  71340. * @return The Spherical Polynomial data.
  71341. */
  71342. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71343. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71344. var totalSolidAngle = 0.0;
  71345. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71346. var du = 2.0 / cubeInfo.size;
  71347. var dv = du;
  71348. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71349. var minUV = du * 0.5 - 1.0;
  71350. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71351. var fileFace = this.FileFaces[faceIndex];
  71352. var dataArray = cubeInfo[fileFace.name];
  71353. var v = minUV;
  71354. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71355. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71356. // Because SP is still linear, so summation is fine in that basis.
  71357. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71358. for (var y = 0; y < cubeInfo.size; y++) {
  71359. var u = minUV;
  71360. for (var x = 0; x < cubeInfo.size; x++) {
  71361. // World direction (not normalised)
  71362. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71363. worldDirection.normalize();
  71364. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71365. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71366. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71367. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71368. // Handle Integer types.
  71369. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71370. r /= 255;
  71371. g /= 255;
  71372. b /= 255;
  71373. }
  71374. // Handle Gamma space textures.
  71375. if (cubeInfo.gammaSpace) {
  71376. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71377. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71378. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71379. }
  71380. var color = new BABYLON.Color3(r, g, b);
  71381. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71382. totalSolidAngle += deltaSolidAngle;
  71383. u += du;
  71384. }
  71385. v += dv;
  71386. }
  71387. }
  71388. // Solid angle for entire sphere is 4*pi
  71389. var sphereSolidAngle = 4.0 * Math.PI;
  71390. // Adjust the solid angle to allow for how many faces we processed.
  71391. var facesProcessed = 6.0;
  71392. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71393. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71394. // This is needed because the numerical integration over the cube uses a
  71395. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71396. // and also to compensate for accumulative error due to float precision in the summation.
  71397. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71398. sphericalHarmonics.scale(correctionFactor);
  71399. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71400. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71401. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71402. };
  71403. CubeMapToSphericalPolynomialTools.FileFaces = [
  71404. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71405. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  71406. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  71407. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  71408. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  71409. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  71410. ];
  71411. return CubeMapToSphericalPolynomialTools;
  71412. }());
  71413. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  71414. })(BABYLON || (BABYLON = {}));
  71415. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  71416. var BABYLON;
  71417. (function (BABYLON) {
  71418. /**
  71419. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  71420. */
  71421. var PanoramaToCubeMapTools = /** @class */ (function () {
  71422. function PanoramaToCubeMapTools() {
  71423. }
  71424. /**
  71425. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  71426. *
  71427. * @param float32Array The source data.
  71428. * @param inputWidth The width of the input panorama.
  71429. * @param inputhHeight The height of the input panorama.
  71430. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  71431. * @return The cubemap data
  71432. */
  71433. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  71434. if (!float32Array) {
  71435. throw "ConvertPanoramaToCubemap: input cannot be null";
  71436. }
  71437. if (float32Array.length != inputWidth * inputHeight * 3) {
  71438. throw "ConvertPanoramaToCubemap: input size is wrong";
  71439. }
  71440. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  71441. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  71442. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  71443. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  71444. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  71445. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  71446. return {
  71447. front: textureFront,
  71448. back: textureBack,
  71449. left: textureLeft,
  71450. right: textureRight,
  71451. up: textureUp,
  71452. down: textureDown,
  71453. size: size,
  71454. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  71455. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  71456. gammaSpace: false,
  71457. };
  71458. };
  71459. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  71460. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  71461. var textureArray = new Float32Array(buffer);
  71462. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  71463. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  71464. var dy = 1 / texSize;
  71465. var fy = 0;
  71466. for (var y = 0; y < texSize; y++) {
  71467. var xv1 = faceData[0];
  71468. var xv2 = faceData[2];
  71469. for (var x = 0; x < texSize; x++) {
  71470. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  71471. v.normalize();
  71472. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  71473. // 3 channels per pixels
  71474. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  71475. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  71476. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  71477. xv1 = xv1.add(rotDX1);
  71478. xv2 = xv2.add(rotDX2);
  71479. }
  71480. fy += dy;
  71481. }
  71482. return textureArray;
  71483. };
  71484. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  71485. var theta = Math.atan2(vDir.z, vDir.x);
  71486. var phi = Math.acos(vDir.y);
  71487. while (theta < -Math.PI)
  71488. theta += 2 * Math.PI;
  71489. while (theta > Math.PI)
  71490. theta -= 2 * Math.PI;
  71491. var dx = theta / Math.PI;
  71492. var dy = phi / Math.PI;
  71493. // recenter.
  71494. dx = dx * 0.5 + 0.5;
  71495. var px = Math.round(dx * inputWidth);
  71496. if (px < 0)
  71497. px = 0;
  71498. else if (px >= inputWidth)
  71499. px = inputWidth - 1;
  71500. var py = Math.round(dy * inputHeight);
  71501. if (py < 0)
  71502. py = 0;
  71503. else if (py >= inputHeight)
  71504. py = inputHeight - 1;
  71505. var inputY = (inputHeight - py - 1);
  71506. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  71507. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  71508. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  71509. return {
  71510. r: r,
  71511. g: g,
  71512. b: b
  71513. };
  71514. };
  71515. PanoramaToCubeMapTools.FACE_FRONT = [
  71516. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71517. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71518. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71519. new BABYLON.Vector3(1.0, 1.0, -1.0)
  71520. ];
  71521. PanoramaToCubeMapTools.FACE_BACK = [
  71522. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71523. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71524. new BABYLON.Vector3(1.0, 1.0, 1.0),
  71525. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  71526. ];
  71527. PanoramaToCubeMapTools.FACE_RIGHT = [
  71528. new BABYLON.Vector3(1.0, -1.0, -1.0),
  71529. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71530. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71531. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71532. ];
  71533. PanoramaToCubeMapTools.FACE_LEFT = [
  71534. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71535. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71536. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71537. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  71538. ];
  71539. PanoramaToCubeMapTools.FACE_DOWN = [
  71540. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  71541. new BABYLON.Vector3(1.0, 1.0, -1.0),
  71542. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  71543. new BABYLON.Vector3(1.0, 1.0, 1.0)
  71544. ];
  71545. PanoramaToCubeMapTools.FACE_UP = [
  71546. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  71547. new BABYLON.Vector3(1.0, -1.0, 1.0),
  71548. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  71549. new BABYLON.Vector3(1.0, -1.0, -1.0)
  71550. ];
  71551. return PanoramaToCubeMapTools;
  71552. }());
  71553. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  71554. })(BABYLON || (BABYLON = {}));
  71555. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  71556. var BABYLON;
  71557. (function (BABYLON) {
  71558. ;
  71559. /**
  71560. * This groups tools to convert HDR texture to native colors array.
  71561. */
  71562. var HDRTools = /** @class */ (function () {
  71563. function HDRTools() {
  71564. }
  71565. HDRTools.Ldexp = function (mantissa, exponent) {
  71566. if (exponent > 1023) {
  71567. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  71568. }
  71569. if (exponent < -1074) {
  71570. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  71571. }
  71572. return mantissa * Math.pow(2, exponent);
  71573. };
  71574. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  71575. if (exponent > 0) {
  71576. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  71577. float32array[index + 0] = red * exponent;
  71578. float32array[index + 1] = green * exponent;
  71579. float32array[index + 2] = blue * exponent;
  71580. }
  71581. else {
  71582. float32array[index + 0] = 0;
  71583. float32array[index + 1] = 0;
  71584. float32array[index + 2] = 0;
  71585. }
  71586. };
  71587. HDRTools.readStringLine = function (uint8array, startIndex) {
  71588. var line = "";
  71589. var character = "";
  71590. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  71591. character = String.fromCharCode(uint8array[i]);
  71592. if (character == "\n") {
  71593. break;
  71594. }
  71595. line += character;
  71596. }
  71597. return line;
  71598. };
  71599. /**
  71600. * Reads header information from an RGBE texture stored in a native array.
  71601. * More information on this format are available here:
  71602. * https://en.wikipedia.org/wiki/RGBE_image_format
  71603. *
  71604. * @param uint8array The binary file stored in native array.
  71605. * @return The header information.
  71606. */
  71607. HDRTools.RGBE_ReadHeader = function (uint8array) {
  71608. var height = 0;
  71609. var width = 0;
  71610. var line = this.readStringLine(uint8array, 0);
  71611. if (line[0] != '#' || line[1] != '?') {
  71612. throw "Bad HDR Format.";
  71613. }
  71614. var endOfHeader = false;
  71615. var findFormat = false;
  71616. var lineIndex = 0;
  71617. do {
  71618. lineIndex += (line.length + 1);
  71619. line = this.readStringLine(uint8array, lineIndex);
  71620. if (line == "FORMAT=32-bit_rle_rgbe") {
  71621. findFormat = true;
  71622. }
  71623. else if (line.length == 0) {
  71624. endOfHeader = true;
  71625. }
  71626. } while (!endOfHeader);
  71627. if (!findFormat) {
  71628. throw "HDR Bad header format, unsupported FORMAT";
  71629. }
  71630. lineIndex += (line.length + 1);
  71631. line = this.readStringLine(uint8array, lineIndex);
  71632. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  71633. var match = sizeRegexp.exec(line);
  71634. // TODO. Support +Y and -X if needed.
  71635. if (!match || match.length < 3) {
  71636. throw "HDR Bad header format, no size";
  71637. }
  71638. width = parseInt(match[2]);
  71639. height = parseInt(match[1]);
  71640. if (width < 8 || width > 0x7fff) {
  71641. throw "HDR Bad header format, unsupported size";
  71642. }
  71643. lineIndex += (line.length + 1);
  71644. return {
  71645. height: height,
  71646. width: width,
  71647. dataPosition: lineIndex
  71648. };
  71649. };
  71650. /**
  71651. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  71652. * This RGBE texture needs to store the information as a panorama.
  71653. *
  71654. * More information on this format are available here:
  71655. * https://en.wikipedia.org/wiki/RGBE_image_format
  71656. *
  71657. * @param buffer The binary file stored in an array buffer.
  71658. * @param size The expected size of the extracted cubemap.
  71659. * @return The Cube Map information.
  71660. */
  71661. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  71662. var uint8array = new Uint8Array(buffer);
  71663. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  71664. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71665. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  71666. return cubeMapData;
  71667. };
  71668. /**
  71669. * Returns the pixels data extracted from an RGBE texture.
  71670. * This pixels will be stored left to right up to down in the R G B order in one array.
  71671. *
  71672. * More information on this format are available here:
  71673. * https://en.wikipedia.org/wiki/RGBE_image_format
  71674. *
  71675. * @param uint8array The binary file stored in an array buffer.
  71676. * @param hdrInfo The header information of the file.
  71677. * @return The pixels data in RGB right to left up to down order.
  71678. */
  71679. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  71680. // Keep for multi format supports.
  71681. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  71682. };
  71683. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  71684. var num_scanlines = hdrInfo.height;
  71685. var scanline_width = hdrInfo.width;
  71686. var a, b, c, d, count;
  71687. var dataIndex = hdrInfo.dataPosition;
  71688. var index = 0, endIndex = 0, i = 0;
  71689. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  71690. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  71691. // 3 channels of 4 bytes per pixel in float.
  71692. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  71693. var resultArray = new Float32Array(resultBuffer);
  71694. // read in each successive scanline
  71695. while (num_scanlines > 0) {
  71696. a = uint8array[dataIndex++];
  71697. b = uint8array[dataIndex++];
  71698. c = uint8array[dataIndex++];
  71699. d = uint8array[dataIndex++];
  71700. if (a != 2 || b != 2 || (c & 0x80)) {
  71701. // this file is not run length encoded
  71702. throw "HDR Bad header format, not RLE";
  71703. }
  71704. if (((c << 8) | d) != scanline_width) {
  71705. throw "HDR Bad header format, wrong scan line width";
  71706. }
  71707. index = 0;
  71708. // read each of the four channels for the scanline into the buffer
  71709. for (i = 0; i < 4; i++) {
  71710. endIndex = (i + 1) * scanline_width;
  71711. while (index < endIndex) {
  71712. a = uint8array[dataIndex++];
  71713. b = uint8array[dataIndex++];
  71714. if (a > 128) {
  71715. // a run of the same value
  71716. count = a - 128;
  71717. if ((count == 0) || (count > endIndex - index)) {
  71718. throw "HDR Bad Format, bad scanline data (run)";
  71719. }
  71720. while (count-- > 0) {
  71721. scanLineArray[index++] = b;
  71722. }
  71723. }
  71724. else {
  71725. // a non-run
  71726. count = a;
  71727. if ((count == 0) || (count > endIndex - index)) {
  71728. throw "HDR Bad Format, bad scanline data (non-run)";
  71729. }
  71730. scanLineArray[index++] = b;
  71731. if (--count > 0) {
  71732. for (var j = 0; j < count; j++) {
  71733. scanLineArray[index++] = uint8array[dataIndex++];
  71734. }
  71735. }
  71736. }
  71737. }
  71738. }
  71739. // now convert data from buffer into floats
  71740. for (i = 0; i < scanline_width; i++) {
  71741. a = scanLineArray[i];
  71742. b = scanLineArray[i + scanline_width];
  71743. c = scanLineArray[i + 2 * scanline_width];
  71744. d = scanLineArray[i + 3 * scanline_width];
  71745. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  71746. }
  71747. num_scanlines--;
  71748. }
  71749. return resultArray;
  71750. };
  71751. return HDRTools;
  71752. }());
  71753. BABYLON.HDRTools = HDRTools;
  71754. })(BABYLON || (BABYLON = {}));
  71755. //# sourceMappingURL=babylon.hdr.js.map
  71756. var BABYLON;
  71757. (function (BABYLON) {
  71758. /**
  71759. * This represents a texture coming from an HDR input.
  71760. *
  71761. * The only supported format is currently panorama picture stored in RGBE format.
  71762. * Example of such files can be found on HDRLib: http://hdrlib.com/
  71763. */
  71764. var HDRCubeTexture = /** @class */ (function (_super) {
  71765. __extends(HDRCubeTexture, _super);
  71766. /**
  71767. * Instantiates an HDRTexture from the following parameters.
  71768. *
  71769. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  71770. * @param scene The scene the texture will be used in
  71771. * @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.
  71772. * @param noMipmap Forces to not generate the mipmap if true
  71773. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  71774. * @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)
  71775. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  71776. */
  71777. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  71778. if (noMipmap === void 0) { noMipmap = false; }
  71779. if (generateHarmonics === void 0) { generateHarmonics = true; }
  71780. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  71781. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  71782. if (onLoad === void 0) { onLoad = null; }
  71783. if (onError === void 0) { onError = null; }
  71784. var _this = _super.call(this, scene) || this;
  71785. _this._useInGammaSpace = false;
  71786. _this._generateHarmonics = true;
  71787. _this._isBABYLONPreprocessed = false;
  71788. _this._onLoad = null;
  71789. _this._onError = null;
  71790. /**
  71791. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  71792. */
  71793. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71794. /**
  71795. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  71796. * This is usefull at run time to apply the good shader.
  71797. */
  71798. _this.isPMREM = false;
  71799. _this._isBlocking = true;
  71800. if (!url) {
  71801. return _this;
  71802. }
  71803. _this.name = url;
  71804. _this.url = url;
  71805. _this.hasAlpha = false;
  71806. _this.isCube = true;
  71807. _this._textureMatrix = BABYLON.Matrix.Identity();
  71808. _this._onLoad = onLoad;
  71809. _this._onError = onError;
  71810. _this.gammaSpace = false;
  71811. var caps = scene.getEngine().getCaps();
  71812. if (size) {
  71813. _this._isBABYLONPreprocessed = false;
  71814. _this._noMipmap = noMipmap;
  71815. _this._size = size;
  71816. _this._useInGammaSpace = useInGammaSpace;
  71817. _this._usePMREMGenerator = usePMREMGenerator &&
  71818. caps.textureLOD &&
  71819. caps.textureFloat &&
  71820. !_this._useInGammaSpace;
  71821. }
  71822. else {
  71823. _this._isBABYLONPreprocessed = true;
  71824. _this._noMipmap = false;
  71825. _this._useInGammaSpace = false;
  71826. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  71827. !_this._useInGammaSpace;
  71828. }
  71829. _this.isPMREM = _this._usePMREMGenerator;
  71830. _this._texture = _this._getFromCache(url, _this._noMipmap);
  71831. if (!_this._texture) {
  71832. if (!scene.useDelayedTextureLoading) {
  71833. _this.loadTexture();
  71834. }
  71835. else {
  71836. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71837. }
  71838. }
  71839. return _this;
  71840. }
  71841. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  71842. /**
  71843. * Gets wether or not the texture is blocking during loading.
  71844. */
  71845. get: function () {
  71846. return this._isBlocking;
  71847. },
  71848. /**
  71849. * Sets wether or not the texture is blocking during loading.
  71850. */
  71851. set: function (value) {
  71852. this._isBlocking = value;
  71853. },
  71854. enumerable: true,
  71855. configurable: true
  71856. });
  71857. /**
  71858. * Occurs when the file is a preprocessed .babylon.hdr file.
  71859. */
  71860. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  71861. var _this = this;
  71862. var mipLevels = 0;
  71863. var floatArrayView = null;
  71864. var scene = this.getScene();
  71865. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  71866. var mips = new Array();
  71867. if (!floatArrayView) {
  71868. return mips;
  71869. }
  71870. var startIndex = 30;
  71871. for (var level = 0; level < mipLevels; level++) {
  71872. mips.push([]);
  71873. // Fill each pixel of the mip level.
  71874. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  71875. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71876. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  71877. mips[level].push(faceData);
  71878. startIndex += faceSize;
  71879. }
  71880. }
  71881. return mips;
  71882. } : null;
  71883. var callback = function (buffer) {
  71884. var scene = _this.getScene();
  71885. if (!scene) {
  71886. return null;
  71887. }
  71888. // Create Native Array Views
  71889. var intArrayView = new Int32Array(buffer);
  71890. floatArrayView = new Float32Array(buffer);
  71891. // Fill header.
  71892. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  71893. _this._size = intArrayView[1]; // CubeMap max mip face size.
  71894. // Update Texture Information.
  71895. if (!_this._texture) {
  71896. return null;
  71897. }
  71898. _this._texture.updateSize(_this._size, _this._size);
  71899. // Fill polynomial information.
  71900. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  71901. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  71902. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  71903. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  71904. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  71905. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  71906. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  71907. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  71908. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  71909. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  71910. _this.sphericalPolynomial = sphericalPolynomial;
  71911. // Fill pixel data.
  71912. mipLevels = intArrayView[29]; // Number of mip levels.
  71913. var startIndex = 30;
  71914. var data = [];
  71915. var faceSize = Math.pow(_this._size, 2) * 3;
  71916. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71917. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  71918. startIndex += faceSize;
  71919. }
  71920. var results = [];
  71921. var byteArray = null;
  71922. // Push each faces.
  71923. for (var k = 0; k < 6; k++) {
  71924. var dataFace = null;
  71925. // To be deprecated.
  71926. if (version === 1) {
  71927. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  71928. dataFace = data[j];
  71929. }
  71930. // If special cases.
  71931. if (!mipmapGenerator && dataFace) {
  71932. if (!scene.getEngine().getCaps().textureFloat) {
  71933. // 3 channels of 1 bytes per pixel in bytes.
  71934. var byteBuffer = new ArrayBuffer(faceSize);
  71935. byteArray = new Uint8Array(byteBuffer);
  71936. }
  71937. for (var i = 0; i < _this._size * _this._size; i++) {
  71938. // Put in gamma space if requested.
  71939. if (_this._useInGammaSpace) {
  71940. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  71941. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  71942. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  71943. }
  71944. // Convert to int texture for fallback.
  71945. if (byteArray) {
  71946. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  71947. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  71948. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  71949. // May use luminance instead if the result is not accurate.
  71950. var max = Math.max(Math.max(r, g), b);
  71951. if (max > 255) {
  71952. var scale = 255 / max;
  71953. r *= scale;
  71954. g *= scale;
  71955. b *= scale;
  71956. }
  71957. byteArray[(i * 3) + 0] = r;
  71958. byteArray[(i * 3) + 1] = g;
  71959. byteArray[(i * 3) + 2] = b;
  71960. }
  71961. }
  71962. }
  71963. // Fill the array accordingly.
  71964. if (byteArray) {
  71965. results.push(byteArray);
  71966. }
  71967. else {
  71968. results.push(dataFace);
  71969. }
  71970. }
  71971. return results;
  71972. };
  71973. if (scene) {
  71974. 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);
  71975. }
  71976. };
  71977. /**
  71978. * Occurs when the file is raw .hdr file.
  71979. */
  71980. HDRCubeTexture.prototype.loadHDRTexture = function () {
  71981. var _this = this;
  71982. var callback = function (buffer) {
  71983. var scene = _this.getScene();
  71984. if (!scene) {
  71985. return null;
  71986. }
  71987. // Extract the raw linear data.
  71988. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  71989. // Generate harmonics if needed.
  71990. if (_this._generateHarmonics) {
  71991. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  71992. _this.sphericalPolynomial = sphericalPolynomial;
  71993. }
  71994. var results = [];
  71995. var byteArray = null;
  71996. // Push each faces.
  71997. for (var j = 0; j < 6; j++) {
  71998. // Create uintarray fallback.
  71999. if (!scene.getEngine().getCaps().textureFloat) {
  72000. // 3 channels of 1 bytes per pixel in bytes.
  72001. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72002. byteArray = new Uint8Array(byteBuffer);
  72003. }
  72004. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72005. // If special cases.
  72006. if (_this._useInGammaSpace || byteArray) {
  72007. for (var i = 0; i < _this._size * _this._size; i++) {
  72008. // Put in gamma space if requested.
  72009. if (_this._useInGammaSpace) {
  72010. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72011. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72012. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72013. }
  72014. // Convert to int texture for fallback.
  72015. if (byteArray) {
  72016. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72017. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72018. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72019. // May use luminance instead if the result is not accurate.
  72020. var max = Math.max(Math.max(r, g), b);
  72021. if (max > 255) {
  72022. var scale = 255 / max;
  72023. r *= scale;
  72024. g *= scale;
  72025. b *= scale;
  72026. }
  72027. byteArray[(i * 3) + 0] = r;
  72028. byteArray[(i * 3) + 1] = g;
  72029. byteArray[(i * 3) + 2] = b;
  72030. }
  72031. }
  72032. }
  72033. if (byteArray) {
  72034. results.push(byteArray);
  72035. }
  72036. else {
  72037. results.push(dataFace);
  72038. }
  72039. }
  72040. return results;
  72041. };
  72042. var mipmapGenerator = null;
  72043. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72044. // if (!this._noMipmap &&
  72045. // this._usePMREMGenerator) {
  72046. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72047. // // Custom setup of the generator matching with the PBR shader values.
  72048. // var generator = new BABYLON.PMREMGenerator(data,
  72049. // this._size,
  72050. // this._size,
  72051. // 0,
  72052. // 3,
  72053. // this.getScene().getEngine().getCaps().textureFloat,
  72054. // 2048,
  72055. // 0.25,
  72056. // false,
  72057. // true);
  72058. // return generator.filterCubeMap();
  72059. // };
  72060. // }
  72061. var scene = this.getScene();
  72062. if (scene) {
  72063. 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);
  72064. }
  72065. };
  72066. /**
  72067. * Starts the loading process of the texture.
  72068. */
  72069. HDRCubeTexture.prototype.loadTexture = function () {
  72070. if (this._isBABYLONPreprocessed) {
  72071. this.loadBabylonTexture();
  72072. }
  72073. else {
  72074. this.loadHDRTexture();
  72075. }
  72076. };
  72077. HDRCubeTexture.prototype.clone = function () {
  72078. var scene = this.getScene();
  72079. if (!scene) {
  72080. return this;
  72081. }
  72082. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72083. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72084. // Base texture
  72085. newTexture.level = this.level;
  72086. newTexture.wrapU = this.wrapU;
  72087. newTexture.wrapV = this.wrapV;
  72088. newTexture.coordinatesIndex = this.coordinatesIndex;
  72089. newTexture.coordinatesMode = this.coordinatesMode;
  72090. return newTexture;
  72091. };
  72092. // Methods
  72093. HDRCubeTexture.prototype.delayLoad = function () {
  72094. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72095. return;
  72096. }
  72097. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72098. this._texture = this._getFromCache(this.url, this._noMipmap);
  72099. if (!this._texture) {
  72100. this.loadTexture();
  72101. }
  72102. };
  72103. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72104. return this._textureMatrix;
  72105. };
  72106. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72107. this._textureMatrix = value;
  72108. };
  72109. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72110. var texture = null;
  72111. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72112. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72113. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72114. texture.name = parsedTexture.name;
  72115. texture.hasAlpha = parsedTexture.hasAlpha;
  72116. texture.level = parsedTexture.level;
  72117. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72118. texture.isBlocking = parsedTexture.isBlocking;
  72119. }
  72120. return texture;
  72121. };
  72122. HDRCubeTexture.prototype.serialize = function () {
  72123. if (!this.name) {
  72124. return null;
  72125. }
  72126. var serializationObject = {};
  72127. serializationObject.name = this.name;
  72128. serializationObject.hasAlpha = this.hasAlpha;
  72129. serializationObject.isCube = true;
  72130. serializationObject.level = this.level;
  72131. serializationObject.size = this._size;
  72132. serializationObject.coordinatesMode = this.coordinatesMode;
  72133. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72134. serializationObject.generateHarmonics = this._generateHarmonics;
  72135. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72136. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72137. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72138. serializationObject.noMipmap = this._noMipmap;
  72139. serializationObject.isBlocking = this._isBlocking;
  72140. return serializationObject;
  72141. };
  72142. /**
  72143. * Saves as a file the data contained in the texture in a binary format.
  72144. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72145. * as the spherical used in the lighting.
  72146. * @param url The HDR file url.
  72147. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72148. * @param onError Method called if any error happens during download.
  72149. * @return The packed binary data.
  72150. */
  72151. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72152. if (onError === void 0) { onError = null; }
  72153. var callback = function (buffer) {
  72154. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72155. // Returns a URL you can use as a href.
  72156. var objUrl = window.URL.createObjectURL(data);
  72157. // Simulates a link to it and click to dowload.
  72158. var a = document.createElement("a");
  72159. document.body.appendChild(a);
  72160. a.style.display = "none";
  72161. a.href = objUrl;
  72162. a.download = "envmap.babylon.hdr";
  72163. a.click();
  72164. };
  72165. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72166. };
  72167. /**
  72168. * Serializes the data contained in the texture in a binary format.
  72169. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72170. * as the spherical used in the lighting.
  72171. * @param url The HDR file url.
  72172. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72173. * @param onError Method called if any error happens during download.
  72174. * @return The packed binary data.
  72175. */
  72176. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72177. if (onError === void 0) { onError = null; }
  72178. // Needs the url tho create the texture.
  72179. if (!url) {
  72180. return;
  72181. }
  72182. // Check Power of two size.
  72183. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72184. return;
  72185. }
  72186. // Coming Back in 3.x.
  72187. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72188. };
  72189. HDRCubeTexture._facesMapping = [
  72190. "right",
  72191. "left",
  72192. "up",
  72193. "down",
  72194. "front",
  72195. "back"
  72196. ];
  72197. return HDRCubeTexture;
  72198. }(BABYLON.BaseTexture));
  72199. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72200. })(BABYLON || (BABYLON = {}));
  72201. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72202. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72203. // Huge respect for a such great lib.
  72204. // Earcut license:
  72205. // Copyright (c) 2016, Mapbox
  72206. //
  72207. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72208. // with or without fee is hereby granted, provided that the above copyright notice
  72209. // and this permission notice appear in all copies.
  72210. //
  72211. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72212. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72213. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72214. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72215. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72216. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72217. // THIS SOFTWARE.
  72218. var Earcut;
  72219. (function (Earcut) {
  72220. /**
  72221. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72222. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72223. * @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).
  72224. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72225. */
  72226. function earcut(data, holeIndices, dim) {
  72227. dim = dim || 2;
  72228. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72229. if (!outerNode)
  72230. return triangles;
  72231. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72232. if (hasHoles)
  72233. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72234. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72235. if (data.length > 80 * dim) {
  72236. minX = maxX = data[0];
  72237. minY = maxY = data[1];
  72238. for (var i = dim; i < outerLen; i += dim) {
  72239. x = data[i];
  72240. y = data[i + 1];
  72241. if (x < minX)
  72242. minX = x;
  72243. if (y < minY)
  72244. minY = y;
  72245. if (x > maxX)
  72246. maxX = x;
  72247. if (y > maxY)
  72248. maxY = y;
  72249. }
  72250. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72251. size = Math.max(maxX - minX, maxY - minY);
  72252. }
  72253. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72254. return triangles;
  72255. }
  72256. Earcut.earcut = earcut;
  72257. var Node = /** @class */ (function () {
  72258. function Node(i, x, y) {
  72259. this.i = i;
  72260. this.x = x;
  72261. this.y = y;
  72262. this.prev = null;
  72263. this.next = null;
  72264. this.z = null;
  72265. this.prevZ = null;
  72266. this.nextZ = null;
  72267. this.steiner = false;
  72268. }
  72269. return Node;
  72270. }());
  72271. // create a circular doubly linked list from polygon points in the specified winding order
  72272. function linkedList(data, start, end, dim, clockwise) {
  72273. var i, last = null;
  72274. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72275. for (i = start; i < end; i += dim)
  72276. last = insertNode(i, data[i], data[i + 1], last);
  72277. }
  72278. else {
  72279. for (i = end - dim; i >= start; i -= dim)
  72280. last = insertNode(i, data[i], data[i + 1], last);
  72281. }
  72282. if (last && equals(last, last.next)) {
  72283. removeNode(last);
  72284. last = last.next;
  72285. }
  72286. return last;
  72287. }
  72288. // eliminate colinear or duplicate points
  72289. function filterPoints(start, end) {
  72290. if (!start)
  72291. return start;
  72292. if (!end)
  72293. end = start;
  72294. var p = start, again;
  72295. do {
  72296. again = false;
  72297. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72298. removeNode(p);
  72299. p = end = p.prev;
  72300. if (p === p.next)
  72301. return undefined;
  72302. again = true;
  72303. }
  72304. else {
  72305. p = p.next;
  72306. }
  72307. } while (again || p !== end);
  72308. return end;
  72309. }
  72310. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72311. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72312. if (!ear)
  72313. return;
  72314. // interlink polygon nodes in z-order
  72315. if (!pass && size)
  72316. indexCurve(ear, minX, minY, size);
  72317. var stop = ear, prev, next;
  72318. // iterate through ears, slicing them one by one
  72319. while (ear.prev !== ear.next) {
  72320. prev = ear.prev;
  72321. next = ear.next;
  72322. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72323. // cut off the triangle
  72324. triangles.push(prev.i / dim);
  72325. triangles.push(ear.i / dim);
  72326. triangles.push(next.i / dim);
  72327. removeNode(ear);
  72328. // skipping the next vertice leads to less sliver triangles
  72329. ear = next.next;
  72330. stop = next.next;
  72331. continue;
  72332. }
  72333. ear = next;
  72334. // if we looped through the whole remaining polygon and can't find any more ears
  72335. if (ear === stop) {
  72336. // try filtering points and slicing again
  72337. if (!pass) {
  72338. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72339. // if this didn't work, try curing all small self-intersections locally
  72340. }
  72341. else if (pass === 1) {
  72342. ear = cureLocalIntersections(ear, triangles, dim);
  72343. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72344. // as a last resort, try splitting the remaining polygon into two
  72345. }
  72346. else if (pass === 2) {
  72347. splitEarcut(ear, triangles, dim, minX, minY, size);
  72348. }
  72349. break;
  72350. }
  72351. }
  72352. }
  72353. // check whether a polygon node forms a valid ear with adjacent nodes
  72354. function isEar(ear) {
  72355. var a = ear.prev, b = ear, c = ear.next;
  72356. if (area(a, b, c) >= 0)
  72357. return false; // reflex, can't be an ear
  72358. // now make sure we don't have other points inside the potential ear
  72359. var p = ear.next.next;
  72360. while (p !== ear.prev) {
  72361. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72362. area(p.prev, p, p.next) >= 0)
  72363. return false;
  72364. p = p.next;
  72365. }
  72366. return true;
  72367. }
  72368. function isEarHashed(ear, minX, minY, size) {
  72369. var a = ear.prev, b = ear, c = ear.next;
  72370. if (area(a, b, c) >= 0)
  72371. return false; // reflex, can't be an ear
  72372. // triangle bbox; min & max are calculated like this for speed
  72373. 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);
  72374. // z-order range for the current triangle bbox;
  72375. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  72376. // first look for points inside the triangle in increasing z-order
  72377. var p = ear.nextZ;
  72378. while (p && p.z <= maxZ) {
  72379. if (p !== ear.prev &&
  72380. p !== ear.next &&
  72381. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72382. area(p.prev, p, p.next) >= 0)
  72383. return false;
  72384. p = p.nextZ;
  72385. }
  72386. // then look for points in decreasing z-order
  72387. p = ear.prevZ;
  72388. while (p && p.z >= minZ) {
  72389. if (p !== ear.prev &&
  72390. p !== ear.next &&
  72391. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72392. area(p.prev, p, p.next) >= 0)
  72393. return false;
  72394. p = p.prevZ;
  72395. }
  72396. return true;
  72397. }
  72398. // go through all polygon nodes and cure small local self-intersections
  72399. function cureLocalIntersections(start, triangles, dim) {
  72400. var p = start;
  72401. do {
  72402. var a = p.prev, b = p.next.next;
  72403. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  72404. triangles.push(a.i / dim);
  72405. triangles.push(p.i / dim);
  72406. triangles.push(b.i / dim);
  72407. // remove two nodes involved
  72408. removeNode(p);
  72409. removeNode(p.next);
  72410. p = start = b;
  72411. }
  72412. p = p.next;
  72413. } while (p !== start);
  72414. return p;
  72415. }
  72416. // try splitting polygon into two and triangulate them independently
  72417. function splitEarcut(start, triangles, dim, minX, minY, size) {
  72418. // look for a valid diagonal that divides the polygon into two
  72419. var a = start;
  72420. do {
  72421. var b = a.next.next;
  72422. while (b !== a.prev) {
  72423. if (a.i !== b.i && isValidDiagonal(a, b)) {
  72424. // split the polygon in two by the diagonal
  72425. var c = splitPolygon(a, b);
  72426. // filter colinear points around the cuts
  72427. a = filterPoints(a, a.next);
  72428. c = filterPoints(c, c.next);
  72429. // run earcut on each half
  72430. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  72431. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  72432. return;
  72433. }
  72434. b = b.next;
  72435. }
  72436. a = a.next;
  72437. } while (a !== start);
  72438. }
  72439. // link every hole into the outer loop, producing a single-ring polygon without holes
  72440. function eliminateHoles(data, holeIndices, outerNode, dim) {
  72441. var queue = [], i, len, start, end, list;
  72442. for (i = 0, len = holeIndices.length; i < len; i++) {
  72443. start = holeIndices[i] * dim;
  72444. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72445. list = linkedList(data, start, end, dim, false);
  72446. if (list === list.next)
  72447. list.steiner = true;
  72448. queue.push(getLeftmost(list));
  72449. }
  72450. queue.sort(compareX);
  72451. // process holes from left to right
  72452. for (i = 0; i < queue.length; i++) {
  72453. eliminateHole(queue[i], outerNode);
  72454. outerNode = filterPoints(outerNode, outerNode.next);
  72455. }
  72456. return outerNode;
  72457. }
  72458. function compareX(a, b) {
  72459. return a.x - b.x;
  72460. }
  72461. // find a bridge between vertices that connects hole with an outer ring and and link it
  72462. function eliminateHole(hole, outerNode) {
  72463. outerNode = findHoleBridge(hole, outerNode);
  72464. if (outerNode) {
  72465. var b = splitPolygon(outerNode, hole);
  72466. filterPoints(b, b.next);
  72467. }
  72468. }
  72469. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  72470. function findHoleBridge(hole, outerNode) {
  72471. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  72472. // find a segment intersected by a ray from the hole's leftmost point to the left;
  72473. // segment's endpoint with lesser x will be potential connection point
  72474. do {
  72475. if (hy <= p.y && hy >= p.next.y) {
  72476. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  72477. if (x <= hx && x > qx) {
  72478. qx = x;
  72479. if (x === hx) {
  72480. if (hy === p.y)
  72481. return p;
  72482. if (hy === p.next.y)
  72483. return p.next;
  72484. }
  72485. m = p.x < p.next.x ? p : p.next;
  72486. }
  72487. }
  72488. p = p.next;
  72489. } while (p !== outerNode);
  72490. if (!m)
  72491. return null;
  72492. if (hx === qx)
  72493. return m.prev; // hole touches outer segment; pick lower endpoint
  72494. // look for points inside the triangle of hole point, segment intersection and endpoint;
  72495. // if there are no points found, we have a valid connection;
  72496. // otherwise choose the point of the minimum angle with the ray as connection point
  72497. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  72498. p = m.next;
  72499. while (p !== stop) {
  72500. if (hx >= p.x &&
  72501. p.x >= mx &&
  72502. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  72503. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  72504. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  72505. m = p;
  72506. tanMin = tan;
  72507. }
  72508. }
  72509. p = p.next;
  72510. }
  72511. return m;
  72512. }
  72513. // interlink polygon nodes in z-order
  72514. function indexCurve(start, minX, minY, size) {
  72515. var p = start;
  72516. do {
  72517. if (p.z === null)
  72518. p.z = zOrder(p.x, p.y, minX, minY, size);
  72519. p.prevZ = p.prev;
  72520. p.nextZ = p.next;
  72521. p = p.next;
  72522. } while (p !== start);
  72523. p.prevZ.nextZ = null;
  72524. p.prevZ = null;
  72525. sortLinked(p);
  72526. }
  72527. // Simon Tatham's linked list merge sort algorithm
  72528. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  72529. function sortLinked(list) {
  72530. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  72531. do {
  72532. p = list;
  72533. list = null;
  72534. tail = null;
  72535. numMerges = 0;
  72536. while (p) {
  72537. numMerges++;
  72538. q = p;
  72539. pSize = 0;
  72540. for (i = 0; i < inSize; i++) {
  72541. pSize++;
  72542. q = q.nextZ;
  72543. if (!q)
  72544. break;
  72545. }
  72546. qSize = inSize;
  72547. while (pSize > 0 || (qSize > 0 && q)) {
  72548. if (pSize === 0) {
  72549. e = q;
  72550. q = q.nextZ;
  72551. qSize--;
  72552. }
  72553. else if (qSize === 0 || !q) {
  72554. e = p;
  72555. p = p.nextZ;
  72556. pSize--;
  72557. }
  72558. else if (p.z <= q.z) {
  72559. e = p;
  72560. p = p.nextZ;
  72561. pSize--;
  72562. }
  72563. else {
  72564. e = q;
  72565. q = q.nextZ;
  72566. qSize--;
  72567. }
  72568. if (tail)
  72569. tail.nextZ = e;
  72570. else
  72571. list = e;
  72572. e.prevZ = tail;
  72573. tail = e;
  72574. }
  72575. p = q;
  72576. }
  72577. tail.nextZ = null;
  72578. inSize *= 2;
  72579. } while (numMerges > 1);
  72580. return list;
  72581. }
  72582. // z-order of a point given coords and size of the data bounding box
  72583. function zOrder(x, y, minX, minY, size) {
  72584. // coords are transformed into non-negative 15-bit integer range
  72585. x = 32767 * (x - minX) / size;
  72586. y = 32767 * (y - minY) / size;
  72587. x = (x | (x << 8)) & 0x00FF00FF;
  72588. x = (x | (x << 4)) & 0x0F0F0F0F;
  72589. x = (x | (x << 2)) & 0x33333333;
  72590. x = (x | (x << 1)) & 0x55555555;
  72591. y = (y | (y << 8)) & 0x00FF00FF;
  72592. y = (y | (y << 4)) & 0x0F0F0F0F;
  72593. y = (y | (y << 2)) & 0x33333333;
  72594. y = (y | (y << 1)) & 0x55555555;
  72595. return x | (y << 1);
  72596. }
  72597. // find the leftmost node of a polygon ring
  72598. function getLeftmost(start) {
  72599. var p = start, leftmost = start;
  72600. do {
  72601. if (p.x < leftmost.x)
  72602. leftmost = p;
  72603. p = p.next;
  72604. } while (p !== start);
  72605. return leftmost;
  72606. }
  72607. // check if a point lies within a convex triangle
  72608. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  72609. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  72610. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  72611. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  72612. }
  72613. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  72614. function isValidDiagonal(a, b) {
  72615. return a.next.i !== b.i &&
  72616. a.prev.i !== b.i &&
  72617. !intersectsPolygon(a, b) &&
  72618. locallyInside(a, b) &&
  72619. locallyInside(b, a) &&
  72620. middleInside(a, b);
  72621. }
  72622. // signed area of a triangle
  72623. function area(p, q, r) {
  72624. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  72625. }
  72626. // check if two points are equal
  72627. function equals(p1, p2) {
  72628. return p1.x === p2.x && p1.y === p2.y;
  72629. }
  72630. // check if two segments intersect
  72631. function intersects(p1, q1, p2, q2) {
  72632. if ((equals(p1, q1) && equals(p2, q2)) ||
  72633. (equals(p1, q2) && equals(p2, q1)))
  72634. return true;
  72635. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  72636. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  72637. }
  72638. // check if a polygon diagonal intersects any polygon segments
  72639. function intersectsPolygon(a, b) {
  72640. var p = a;
  72641. do {
  72642. if (p.i !== a.i &&
  72643. p.next.i !== a.i &&
  72644. p.i !== b.i &&
  72645. p.next.i !== b.i &&
  72646. intersects(p, p.next, a, b))
  72647. return true;
  72648. p = p.next;
  72649. } while (p !== a);
  72650. return false;
  72651. }
  72652. // check if a polygon diagonal is locally inside the polygon
  72653. function locallyInside(a, b) {
  72654. return area(a.prev, a, a.next) < 0
  72655. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  72656. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  72657. }
  72658. // check if the middle point of a polygon diagonal is inside the polygon
  72659. function middleInside(a, b) {
  72660. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  72661. do {
  72662. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  72663. inside = !inside;
  72664. p = p.next;
  72665. } while (p !== a);
  72666. return inside;
  72667. }
  72668. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  72669. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  72670. function splitPolygon(a, b) {
  72671. 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;
  72672. a.next = b;
  72673. b.prev = a;
  72674. a2.next = an;
  72675. an.prev = a2;
  72676. b2.next = a2;
  72677. a2.prev = b2;
  72678. bp.next = b2;
  72679. b2.prev = bp;
  72680. return b2;
  72681. }
  72682. // create a node and optionally link it with previous one (in a circular doubly linked list)
  72683. function insertNode(i, x, y, last) {
  72684. var p = new Node(i, x, y);
  72685. if (!last) {
  72686. p.prev = p;
  72687. p.next = p;
  72688. }
  72689. else {
  72690. p.next = last.next;
  72691. p.prev = last;
  72692. last.next.prev = p;
  72693. last.next = p;
  72694. }
  72695. return p;
  72696. }
  72697. function removeNode(p) {
  72698. p.next.prev = p.prev;
  72699. p.prev.next = p.next;
  72700. if (p.prevZ)
  72701. p.prevZ.nextZ = p.nextZ;
  72702. if (p.nextZ)
  72703. p.nextZ.prevZ = p.prevZ;
  72704. }
  72705. /**
  72706. * return a percentage difference between the polygon area and its triangulation area;
  72707. * used to verify correctness of triangulation
  72708. */
  72709. function deviation(data, holeIndices, dim, triangles) {
  72710. var hasHoles = holeIndices && holeIndices.length;
  72711. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  72712. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  72713. if (hasHoles) {
  72714. for (var i = 0, len = holeIndices.length; i < len; i++) {
  72715. var start = holeIndices[i] * dim;
  72716. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72717. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  72718. }
  72719. }
  72720. var trianglesArea = 0;
  72721. for (i = 0; i < triangles.length; i += 3) {
  72722. var a = triangles[i] * dim;
  72723. var b = triangles[i + 1] * dim;
  72724. var c = triangles[i + 2] * dim;
  72725. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  72726. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  72727. }
  72728. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  72729. }
  72730. Earcut.deviation = deviation;
  72731. ;
  72732. function signedArea(data, start, end, dim) {
  72733. var sum = 0;
  72734. for (var i = start, j = end - dim; i < end; i += dim) {
  72735. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  72736. j = i;
  72737. }
  72738. return sum;
  72739. }
  72740. /**
  72741. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  72742. */
  72743. function flatten(data) {
  72744. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  72745. for (var i = 0; i < data.length; i++) {
  72746. for (var j = 0; j < data[i].length; j++) {
  72747. for (var d = 0; d < dim; d++)
  72748. result.vertices.push(data[i][j][d]);
  72749. }
  72750. if (i > 0) {
  72751. holeIndex += data[i - 1].length;
  72752. result.holes.push(holeIndex);
  72753. }
  72754. }
  72755. return result;
  72756. }
  72757. Earcut.flatten = flatten;
  72758. ;
  72759. })(Earcut || (Earcut = {}));
  72760. //# sourceMappingURL=babylon.earcut.js.map
  72761. var BABYLON;
  72762. (function (BABYLON) {
  72763. var IndexedVector2 = /** @class */ (function (_super) {
  72764. __extends(IndexedVector2, _super);
  72765. function IndexedVector2(original, index) {
  72766. var _this = _super.call(this, original.x, original.y) || this;
  72767. _this.index = index;
  72768. return _this;
  72769. }
  72770. return IndexedVector2;
  72771. }(BABYLON.Vector2));
  72772. var PolygonPoints = /** @class */ (function () {
  72773. function PolygonPoints() {
  72774. this.elements = new Array();
  72775. }
  72776. PolygonPoints.prototype.add = function (originalPoints) {
  72777. var _this = this;
  72778. var result = new Array();
  72779. originalPoints.forEach(function (point) {
  72780. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  72781. var newPoint = new IndexedVector2(point, _this.elements.length);
  72782. result.push(newPoint);
  72783. _this.elements.push(newPoint);
  72784. }
  72785. });
  72786. return result;
  72787. };
  72788. PolygonPoints.prototype.computeBounds = function () {
  72789. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72790. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  72791. this.elements.forEach(function (point) {
  72792. // x
  72793. if (point.x < lmin.x) {
  72794. lmin.x = point.x;
  72795. }
  72796. else if (point.x > lmax.x) {
  72797. lmax.x = point.x;
  72798. }
  72799. // y
  72800. if (point.y < lmin.y) {
  72801. lmin.y = point.y;
  72802. }
  72803. else if (point.y > lmax.y) {
  72804. lmax.y = point.y;
  72805. }
  72806. });
  72807. return {
  72808. min: lmin,
  72809. max: lmax,
  72810. width: lmax.x - lmin.x,
  72811. height: lmax.y - lmin.y
  72812. };
  72813. };
  72814. return PolygonPoints;
  72815. }());
  72816. var Polygon = /** @class */ (function () {
  72817. function Polygon() {
  72818. }
  72819. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  72820. return [
  72821. new BABYLON.Vector2(xmin, ymin),
  72822. new BABYLON.Vector2(xmax, ymin),
  72823. new BABYLON.Vector2(xmax, ymax),
  72824. new BABYLON.Vector2(xmin, ymax)
  72825. ];
  72826. };
  72827. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  72828. if (cx === void 0) { cx = 0; }
  72829. if (cy === void 0) { cy = 0; }
  72830. if (numberOfSides === void 0) { numberOfSides = 32; }
  72831. var result = new Array();
  72832. var angle = 0;
  72833. var increment = (Math.PI * 2) / numberOfSides;
  72834. for (var i = 0; i < numberOfSides; i++) {
  72835. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  72836. angle -= increment;
  72837. }
  72838. return result;
  72839. };
  72840. Polygon.Parse = function (input) {
  72841. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  72842. var i, result = [];
  72843. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  72844. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  72845. }
  72846. return result;
  72847. };
  72848. Polygon.StartingAt = function (x, y) {
  72849. return BABYLON.Path2.StartingAt(x, y);
  72850. };
  72851. return Polygon;
  72852. }());
  72853. BABYLON.Polygon = Polygon;
  72854. var PolygonMeshBuilder = /** @class */ (function () {
  72855. function PolygonMeshBuilder(name, contours, scene) {
  72856. this._points = new PolygonPoints();
  72857. this._outlinepoints = new PolygonPoints();
  72858. this._holes = new Array();
  72859. this._epoints = new Array();
  72860. this._eholes = new Array();
  72861. this._name = name;
  72862. this._scene = scene;
  72863. var points;
  72864. if (contours instanceof BABYLON.Path2) {
  72865. points = contours.getPoints();
  72866. }
  72867. else {
  72868. points = contours;
  72869. }
  72870. this._addToepoint(points);
  72871. this._points.add(points);
  72872. this._outlinepoints.add(points);
  72873. }
  72874. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  72875. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  72876. var p = points_1[_i];
  72877. this._epoints.push(p.x, p.y);
  72878. }
  72879. };
  72880. PolygonMeshBuilder.prototype.addHole = function (hole) {
  72881. this._points.add(hole);
  72882. var holepoints = new PolygonPoints();
  72883. holepoints.add(hole);
  72884. this._holes.push(holepoints);
  72885. this._eholes.push(this._epoints.length / 2);
  72886. this._addToepoint(hole);
  72887. return this;
  72888. };
  72889. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  72890. var _this = this;
  72891. if (updatable === void 0) { updatable = false; }
  72892. if (depth === void 0) { depth = 0; }
  72893. var result = new BABYLON.Mesh(this._name, this._scene);
  72894. var normals = new Array();
  72895. var positions = new Array();
  72896. var uvs = new Array();
  72897. var bounds = this._points.computeBounds();
  72898. this._points.elements.forEach(function (p) {
  72899. normals.push(0, 1.0, 0);
  72900. positions.push(p.x, 0, p.y);
  72901. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  72902. });
  72903. var indices = new Array();
  72904. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  72905. for (var i = 0; i < res.length; i++) {
  72906. indices.push(res[i]);
  72907. }
  72908. if (depth > 0) {
  72909. var positionscount = (positions.length / 3); //get the current pointcount
  72910. this._points.elements.forEach(function (p) {
  72911. normals.push(0, -1.0, 0);
  72912. positions.push(p.x, -depth, p.y);
  72913. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  72914. });
  72915. var totalCount = indices.length;
  72916. for (var i = 0; i < totalCount; i += 3) {
  72917. var i0 = indices[i + 0];
  72918. var i1 = indices[i + 1];
  72919. var i2 = indices[i + 2];
  72920. indices.push(i2 + positionscount);
  72921. indices.push(i1 + positionscount);
  72922. indices.push(i0 + positionscount);
  72923. }
  72924. //Add the sides
  72925. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  72926. this._holes.forEach(function (hole) {
  72927. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  72928. });
  72929. }
  72930. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  72931. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  72932. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  72933. result.setIndices(indices);
  72934. return result;
  72935. };
  72936. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  72937. var StartIndex = positions.length / 3;
  72938. var ulength = 0;
  72939. for (var i = 0; i < points.elements.length; i++) {
  72940. var p = points.elements[i];
  72941. var p1;
  72942. if ((i + 1) > points.elements.length - 1) {
  72943. p1 = points.elements[0];
  72944. }
  72945. else {
  72946. p1 = points.elements[i + 1];
  72947. }
  72948. positions.push(p.x, 0, p.y);
  72949. positions.push(p.x, -depth, p.y);
  72950. positions.push(p1.x, 0, p1.y);
  72951. positions.push(p1.x, -depth, p1.y);
  72952. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  72953. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  72954. var v3 = v2.subtract(v1);
  72955. var v4 = new BABYLON.Vector3(0, 1, 0);
  72956. var vn = BABYLON.Vector3.Cross(v3, v4);
  72957. vn = vn.normalize();
  72958. uvs.push(ulength / bounds.width, 0);
  72959. uvs.push(ulength / bounds.width, 1);
  72960. ulength += v3.length();
  72961. uvs.push((ulength / bounds.width), 0);
  72962. uvs.push((ulength / bounds.width), 1);
  72963. if (!flip) {
  72964. normals.push(-vn.x, -vn.y, -vn.z);
  72965. normals.push(-vn.x, -vn.y, -vn.z);
  72966. normals.push(-vn.x, -vn.y, -vn.z);
  72967. normals.push(-vn.x, -vn.y, -vn.z);
  72968. indices.push(StartIndex);
  72969. indices.push(StartIndex + 1);
  72970. indices.push(StartIndex + 2);
  72971. indices.push(StartIndex + 1);
  72972. indices.push(StartIndex + 3);
  72973. indices.push(StartIndex + 2);
  72974. }
  72975. else {
  72976. normals.push(vn.x, vn.y, vn.z);
  72977. normals.push(vn.x, vn.y, vn.z);
  72978. normals.push(vn.x, vn.y, vn.z);
  72979. normals.push(vn.x, vn.y, vn.z);
  72980. indices.push(StartIndex);
  72981. indices.push(StartIndex + 2);
  72982. indices.push(StartIndex + 1);
  72983. indices.push(StartIndex + 1);
  72984. indices.push(StartIndex + 2);
  72985. indices.push(StartIndex + 3);
  72986. }
  72987. StartIndex += 4;
  72988. }
  72989. ;
  72990. };
  72991. return PolygonMeshBuilder;
  72992. }());
  72993. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  72994. })(BABYLON || (BABYLON = {}));
  72995. //# sourceMappingURL=babylon.polygonMesh.js.map
  72996. var BABYLON;
  72997. (function (BABYLON) {
  72998. // Unique ID when we import meshes from Babylon to CSG
  72999. var currentCSGMeshId = 0;
  73000. // # class Vertex
  73001. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73002. // one to provide additional features like texture coordinates and vertex
  73003. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73004. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73005. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73006. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73007. // is not used anywhere else.
  73008. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73009. var Vertex = /** @class */ (function () {
  73010. function Vertex(pos, normal, uv) {
  73011. this.pos = pos;
  73012. this.normal = normal;
  73013. this.uv = uv;
  73014. }
  73015. Vertex.prototype.clone = function () {
  73016. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73017. };
  73018. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73019. // orientation of a polygon is flipped.
  73020. Vertex.prototype.flip = function () {
  73021. this.normal = this.normal.scale(-1);
  73022. };
  73023. // Create a new vertex between this vertex and `other` by linearly
  73024. // interpolating all properties using a parameter of `t`. Subclasses should
  73025. // override this to interpolate additional properties.
  73026. Vertex.prototype.interpolate = function (other, t) {
  73027. 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));
  73028. };
  73029. return Vertex;
  73030. }());
  73031. // # class Plane
  73032. // Represents a plane in 3D space.
  73033. var Plane = /** @class */ (function () {
  73034. function Plane(normal, w) {
  73035. this.normal = normal;
  73036. this.w = w;
  73037. }
  73038. Plane.FromPoints = function (a, b, c) {
  73039. var v0 = c.subtract(a);
  73040. var v1 = b.subtract(a);
  73041. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73042. return null;
  73043. }
  73044. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73045. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73046. };
  73047. Plane.prototype.clone = function () {
  73048. return new Plane(this.normal.clone(), this.w);
  73049. };
  73050. Plane.prototype.flip = function () {
  73051. this.normal.scaleInPlace(-1);
  73052. this.w = -this.w;
  73053. };
  73054. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73055. // fragments in the appropriate lists. Coplanar polygons go into either
  73056. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73057. // respect to this plane. Polygons in front or in back of this plane go into
  73058. // either `front` or `back`.
  73059. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73060. var COPLANAR = 0;
  73061. var FRONT = 1;
  73062. var BACK = 2;
  73063. var SPANNING = 3;
  73064. // Classify each point as well as the entire polygon into one of the above
  73065. // four classes.
  73066. var polygonType = 0;
  73067. var types = [];
  73068. var i;
  73069. var t;
  73070. for (i = 0; i < polygon.vertices.length; i++) {
  73071. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73072. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73073. polygonType |= type;
  73074. types.push(type);
  73075. }
  73076. // Put the polygon in the correct list, splitting it when necessary.
  73077. switch (polygonType) {
  73078. case COPLANAR:
  73079. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73080. break;
  73081. case FRONT:
  73082. front.push(polygon);
  73083. break;
  73084. case BACK:
  73085. back.push(polygon);
  73086. break;
  73087. case SPANNING:
  73088. var f = [], b = [];
  73089. for (i = 0; i < polygon.vertices.length; i++) {
  73090. var j = (i + 1) % polygon.vertices.length;
  73091. var ti = types[i], tj = types[j];
  73092. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73093. if (ti !== BACK)
  73094. f.push(vi);
  73095. if (ti !== FRONT)
  73096. b.push(ti !== BACK ? vi.clone() : vi);
  73097. if ((ti | tj) === SPANNING) {
  73098. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73099. var v = vi.interpolate(vj, t);
  73100. f.push(v);
  73101. b.push(v.clone());
  73102. }
  73103. }
  73104. var poly;
  73105. if (f.length >= 3) {
  73106. poly = new Polygon(f, polygon.shared);
  73107. if (poly.plane)
  73108. front.push(poly);
  73109. }
  73110. if (b.length >= 3) {
  73111. poly = new Polygon(b, polygon.shared);
  73112. if (poly.plane)
  73113. back.push(poly);
  73114. }
  73115. break;
  73116. }
  73117. };
  73118. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73119. // point is on the plane.
  73120. Plane.EPSILON = 1e-5;
  73121. return Plane;
  73122. }());
  73123. // # class Polygon
  73124. // Represents a convex polygon. The vertices used to initialize a polygon must
  73125. // be coplanar and form a convex loop.
  73126. //
  73127. // Each convex polygon has a `shared` property, which is shared between all
  73128. // polygons that are clones of each other or were split from the same polygon.
  73129. // This can be used to define per-polygon properties (such as surface color).
  73130. var Polygon = /** @class */ (function () {
  73131. function Polygon(vertices, shared) {
  73132. this.vertices = vertices;
  73133. this.shared = shared;
  73134. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73135. }
  73136. Polygon.prototype.clone = function () {
  73137. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73138. return new Polygon(vertices, this.shared);
  73139. };
  73140. Polygon.prototype.flip = function () {
  73141. this.vertices.reverse().map(function (v) { v.flip(); });
  73142. this.plane.flip();
  73143. };
  73144. return Polygon;
  73145. }());
  73146. // # class Node
  73147. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73148. // by picking a polygon to split along. That polygon (and all other coplanar
  73149. // polygons) are added directly to that node and the other polygons are added to
  73150. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73151. // no distinction between internal and leaf nodes.
  73152. var Node = /** @class */ (function () {
  73153. function Node(polygons) {
  73154. this.plane = null;
  73155. this.front = null;
  73156. this.back = null;
  73157. this.polygons = new Array();
  73158. if (polygons) {
  73159. this.build(polygons);
  73160. }
  73161. }
  73162. Node.prototype.clone = function () {
  73163. var node = new Node();
  73164. node.plane = this.plane && this.plane.clone();
  73165. node.front = this.front && this.front.clone();
  73166. node.back = this.back && this.back.clone();
  73167. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73168. return node;
  73169. };
  73170. // Convert solid space to empty space and empty space to solid space.
  73171. Node.prototype.invert = function () {
  73172. for (var i = 0; i < this.polygons.length; i++) {
  73173. this.polygons[i].flip();
  73174. }
  73175. if (this.plane) {
  73176. this.plane.flip();
  73177. }
  73178. if (this.front) {
  73179. this.front.invert();
  73180. }
  73181. if (this.back) {
  73182. this.back.invert();
  73183. }
  73184. var temp = this.front;
  73185. this.front = this.back;
  73186. this.back = temp;
  73187. };
  73188. // Recursively remove all polygons in `polygons` that are inside this BSP
  73189. // tree.
  73190. Node.prototype.clipPolygons = function (polygons) {
  73191. if (!this.plane)
  73192. return polygons.slice();
  73193. var front = new Array(), back = new Array();
  73194. for (var i = 0; i < polygons.length; i++) {
  73195. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73196. }
  73197. if (this.front) {
  73198. front = this.front.clipPolygons(front);
  73199. }
  73200. if (this.back) {
  73201. back = this.back.clipPolygons(back);
  73202. }
  73203. else {
  73204. back = [];
  73205. }
  73206. return front.concat(back);
  73207. };
  73208. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73209. // `bsp`.
  73210. Node.prototype.clipTo = function (bsp) {
  73211. this.polygons = bsp.clipPolygons(this.polygons);
  73212. if (this.front)
  73213. this.front.clipTo(bsp);
  73214. if (this.back)
  73215. this.back.clipTo(bsp);
  73216. };
  73217. // Return a list of all polygons in this BSP tree.
  73218. Node.prototype.allPolygons = function () {
  73219. var polygons = this.polygons.slice();
  73220. if (this.front)
  73221. polygons = polygons.concat(this.front.allPolygons());
  73222. if (this.back)
  73223. polygons = polygons.concat(this.back.allPolygons());
  73224. return polygons;
  73225. };
  73226. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73227. // new polygons are filtered down to the bottom of the tree and become new
  73228. // nodes there. Each set of polygons is partitioned using the first polygon
  73229. // (no heuristic is used to pick a good split).
  73230. Node.prototype.build = function (polygons) {
  73231. if (!polygons.length)
  73232. return;
  73233. if (!this.plane)
  73234. this.plane = polygons[0].plane.clone();
  73235. var front = new Array(), back = new Array();
  73236. for (var i = 0; i < polygons.length; i++) {
  73237. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73238. }
  73239. if (front.length) {
  73240. if (!this.front)
  73241. this.front = new Node();
  73242. this.front.build(front);
  73243. }
  73244. if (back.length) {
  73245. if (!this.back)
  73246. this.back = new Node();
  73247. this.back.build(back);
  73248. }
  73249. };
  73250. return Node;
  73251. }());
  73252. var CSG = /** @class */ (function () {
  73253. function CSG() {
  73254. this.polygons = new Array();
  73255. }
  73256. // Convert BABYLON.Mesh to BABYLON.CSG
  73257. CSG.FromMesh = function (mesh) {
  73258. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73259. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73260. if (mesh instanceof BABYLON.Mesh) {
  73261. mesh.computeWorldMatrix(true);
  73262. matrix = mesh.getWorldMatrix();
  73263. meshPosition = mesh.position.clone();
  73264. meshRotation = mesh.rotation.clone();
  73265. if (mesh.rotationQuaternion) {
  73266. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73267. }
  73268. meshScaling = mesh.scaling.clone();
  73269. }
  73270. else {
  73271. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73272. }
  73273. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73274. var subMeshes = mesh.subMeshes;
  73275. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73276. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73277. vertices = [];
  73278. for (var j = 0; j < 3; j++) {
  73279. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73280. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73281. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73282. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73283. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73284. vertex = new Vertex(position, normal, uv);
  73285. vertices.push(vertex);
  73286. }
  73287. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73288. // To handle the case of degenerated triangle
  73289. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73290. if (polygon.plane)
  73291. polygons.push(polygon);
  73292. }
  73293. }
  73294. var csg = CSG.FromPolygons(polygons);
  73295. csg.matrix = matrix;
  73296. csg.position = meshPosition;
  73297. csg.rotation = meshRotation;
  73298. csg.scaling = meshScaling;
  73299. csg.rotationQuaternion = meshRotationQuaternion;
  73300. currentCSGMeshId++;
  73301. return csg;
  73302. };
  73303. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73304. CSG.FromPolygons = function (polygons) {
  73305. var csg = new CSG();
  73306. csg.polygons = polygons;
  73307. return csg;
  73308. };
  73309. CSG.prototype.clone = function () {
  73310. var csg = new CSG();
  73311. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73312. csg.copyTransformAttributes(this);
  73313. return csg;
  73314. };
  73315. CSG.prototype.union = function (csg) {
  73316. var a = new Node(this.clone().polygons);
  73317. var b = new Node(csg.clone().polygons);
  73318. a.clipTo(b);
  73319. b.clipTo(a);
  73320. b.invert();
  73321. b.clipTo(a);
  73322. b.invert();
  73323. a.build(b.allPolygons());
  73324. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73325. };
  73326. CSG.prototype.unionInPlace = function (csg) {
  73327. var a = new Node(this.polygons);
  73328. var b = new Node(csg.polygons);
  73329. a.clipTo(b);
  73330. b.clipTo(a);
  73331. b.invert();
  73332. b.clipTo(a);
  73333. b.invert();
  73334. a.build(b.allPolygons());
  73335. this.polygons = a.allPolygons();
  73336. };
  73337. CSG.prototype.subtract = function (csg) {
  73338. var a = new Node(this.clone().polygons);
  73339. var b = new Node(csg.clone().polygons);
  73340. a.invert();
  73341. a.clipTo(b);
  73342. b.clipTo(a);
  73343. b.invert();
  73344. b.clipTo(a);
  73345. b.invert();
  73346. a.build(b.allPolygons());
  73347. a.invert();
  73348. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73349. };
  73350. CSG.prototype.subtractInPlace = function (csg) {
  73351. var a = new Node(this.polygons);
  73352. var b = new Node(csg.polygons);
  73353. a.invert();
  73354. a.clipTo(b);
  73355. b.clipTo(a);
  73356. b.invert();
  73357. b.clipTo(a);
  73358. b.invert();
  73359. a.build(b.allPolygons());
  73360. a.invert();
  73361. this.polygons = a.allPolygons();
  73362. };
  73363. CSG.prototype.intersect = function (csg) {
  73364. var a = new Node(this.clone().polygons);
  73365. var b = new Node(csg.clone().polygons);
  73366. a.invert();
  73367. b.clipTo(a);
  73368. b.invert();
  73369. a.clipTo(b);
  73370. b.clipTo(a);
  73371. a.build(b.allPolygons());
  73372. a.invert();
  73373. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73374. };
  73375. CSG.prototype.intersectInPlace = function (csg) {
  73376. var a = new Node(this.polygons);
  73377. var b = new Node(csg.polygons);
  73378. a.invert();
  73379. b.clipTo(a);
  73380. b.invert();
  73381. a.clipTo(b);
  73382. b.clipTo(a);
  73383. a.build(b.allPolygons());
  73384. a.invert();
  73385. this.polygons = a.allPolygons();
  73386. };
  73387. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  73388. // not modified.
  73389. CSG.prototype.inverse = function () {
  73390. var csg = this.clone();
  73391. csg.inverseInPlace();
  73392. return csg;
  73393. };
  73394. CSG.prototype.inverseInPlace = function () {
  73395. this.polygons.map(function (p) { p.flip(); });
  73396. };
  73397. // This is used to keep meshes transformations so they can be restored
  73398. // when we build back a Babylon Mesh
  73399. // NB : All CSG operations are performed in world coordinates
  73400. CSG.prototype.copyTransformAttributes = function (csg) {
  73401. this.matrix = csg.matrix;
  73402. this.position = csg.position;
  73403. this.rotation = csg.rotation;
  73404. this.scaling = csg.scaling;
  73405. this.rotationQuaternion = csg.rotationQuaternion;
  73406. return this;
  73407. };
  73408. // Build Raw mesh from CSG
  73409. // Coordinates here are in world space
  73410. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  73411. var matrix = this.matrix.clone();
  73412. matrix.invert();
  73413. 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;
  73414. if (keepSubMeshes) {
  73415. // Sort Polygons, since subMeshes are indices range
  73416. polygons.sort(function (a, b) {
  73417. if (a.shared.meshId === b.shared.meshId) {
  73418. return a.shared.subMeshId - b.shared.subMeshId;
  73419. }
  73420. else {
  73421. return a.shared.meshId - b.shared.meshId;
  73422. }
  73423. });
  73424. }
  73425. for (var i = 0, il = polygons.length; i < il; i++) {
  73426. polygon = polygons[i];
  73427. // Building SubMeshes
  73428. if (!subMesh_dict[polygon.shared.meshId]) {
  73429. subMesh_dict[polygon.shared.meshId] = {};
  73430. }
  73431. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  73432. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  73433. indexStart: +Infinity,
  73434. indexEnd: -Infinity,
  73435. materialIndex: polygon.shared.materialIndex
  73436. };
  73437. }
  73438. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  73439. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  73440. polygonIndices[0] = 0;
  73441. polygonIndices[1] = j - 1;
  73442. polygonIndices[2] = j;
  73443. for (var k = 0; k < 3; k++) {
  73444. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  73445. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  73446. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  73447. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  73448. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  73449. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  73450. // Check if 2 points can be merged
  73451. if (!(typeof vertex_idx !== 'undefined' &&
  73452. normals[vertex_idx * 3] === localNormal.x &&
  73453. normals[vertex_idx * 3 + 1] === localNormal.y &&
  73454. normals[vertex_idx * 3 + 2] === localNormal.z &&
  73455. uvs[vertex_idx * 2] === uv.x &&
  73456. uvs[vertex_idx * 2 + 1] === uv.y)) {
  73457. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  73458. uvs.push(uv.x, uv.y);
  73459. normals.push(normal.x, normal.y, normal.z);
  73460. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  73461. }
  73462. indices.push(vertex_idx);
  73463. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  73464. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  73465. currentIndex++;
  73466. }
  73467. }
  73468. }
  73469. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  73470. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  73471. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  73472. mesh.setIndices(indices, null);
  73473. if (keepSubMeshes) {
  73474. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  73475. var materialIndexOffset = 0, materialMaxIndex;
  73476. mesh.subMeshes = new Array();
  73477. for (var m in subMesh_dict) {
  73478. materialMaxIndex = -1;
  73479. for (var sm in subMesh_dict[m]) {
  73480. subMesh_obj = subMesh_dict[m][sm];
  73481. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  73482. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  73483. }
  73484. materialIndexOffset += ++materialMaxIndex;
  73485. }
  73486. }
  73487. return mesh;
  73488. };
  73489. // Build Mesh from CSG taking material and transforms into account
  73490. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  73491. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  73492. mesh.material = material;
  73493. mesh.position.copyFrom(this.position);
  73494. mesh.rotation.copyFrom(this.rotation);
  73495. if (this.rotationQuaternion) {
  73496. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  73497. }
  73498. mesh.scaling.copyFrom(this.scaling);
  73499. mesh.computeWorldMatrix(true);
  73500. return mesh;
  73501. };
  73502. return CSG;
  73503. }());
  73504. BABYLON.CSG = CSG;
  73505. })(BABYLON || (BABYLON = {}));
  73506. //# sourceMappingURL=babylon.csg.js.map
  73507. var BABYLON;
  73508. (function (BABYLON) {
  73509. var LensFlare = /** @class */ (function () {
  73510. function LensFlare(size, position, color, imgUrl, system) {
  73511. this.size = size;
  73512. this.position = position;
  73513. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  73514. this.color = color || new BABYLON.Color3(1, 1, 1);
  73515. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  73516. this._system = system;
  73517. system.lensFlares.push(this);
  73518. }
  73519. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  73520. return new LensFlare(size, position, color, imgUrl, system);
  73521. };
  73522. LensFlare.prototype.dispose = function () {
  73523. if (this.texture) {
  73524. this.texture.dispose();
  73525. }
  73526. // Remove from scene
  73527. var index = this._system.lensFlares.indexOf(this);
  73528. this._system.lensFlares.splice(index, 1);
  73529. };
  73530. ;
  73531. return LensFlare;
  73532. }());
  73533. BABYLON.LensFlare = LensFlare;
  73534. })(BABYLON || (BABYLON = {}));
  73535. //# sourceMappingURL=babylon.lensFlare.js.map
  73536. var BABYLON;
  73537. (function (BABYLON) {
  73538. var LensFlareSystem = /** @class */ (function () {
  73539. function LensFlareSystem(name, emitter, scene) {
  73540. this.name = name;
  73541. this.lensFlares = new Array();
  73542. this.borderLimit = 300;
  73543. this.viewportBorder = 0;
  73544. this.layerMask = 0x0FFFFFFF;
  73545. this._vertexBuffers = {};
  73546. this._isEnabled = true;
  73547. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73548. this._emitter = emitter;
  73549. this.id = name;
  73550. scene.lensFlareSystems.push(this);
  73551. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  73552. var engine = scene.getEngine();
  73553. // VBO
  73554. var vertices = [];
  73555. vertices.push(1, 1);
  73556. vertices.push(-1, 1);
  73557. vertices.push(-1, -1);
  73558. vertices.push(1, -1);
  73559. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73560. // Indices
  73561. var indices = [];
  73562. indices.push(0);
  73563. indices.push(1);
  73564. indices.push(2);
  73565. indices.push(0);
  73566. indices.push(2);
  73567. indices.push(3);
  73568. this._indexBuffer = engine.createIndexBuffer(indices);
  73569. // Effects
  73570. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  73571. }
  73572. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  73573. get: function () {
  73574. return this._isEnabled;
  73575. },
  73576. set: function (value) {
  73577. this._isEnabled = value;
  73578. },
  73579. enumerable: true,
  73580. configurable: true
  73581. });
  73582. LensFlareSystem.prototype.getScene = function () {
  73583. return this._scene;
  73584. };
  73585. LensFlareSystem.prototype.getEmitter = function () {
  73586. return this._emitter;
  73587. };
  73588. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  73589. this._emitter = newEmitter;
  73590. };
  73591. LensFlareSystem.prototype.getEmitterPosition = function () {
  73592. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  73593. };
  73594. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  73595. var position = this.getEmitterPosition();
  73596. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  73597. this._positionX = position.x;
  73598. this._positionY = position.y;
  73599. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  73600. if (this.viewportBorder > 0) {
  73601. globalViewport.x -= this.viewportBorder;
  73602. globalViewport.y -= this.viewportBorder;
  73603. globalViewport.width += this.viewportBorder * 2;
  73604. globalViewport.height += this.viewportBorder * 2;
  73605. position.x += this.viewportBorder;
  73606. position.y += this.viewportBorder;
  73607. this._positionX += this.viewportBorder;
  73608. this._positionY += this.viewportBorder;
  73609. }
  73610. if (position.z > 0) {
  73611. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  73612. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  73613. return true;
  73614. }
  73615. return true;
  73616. }
  73617. return false;
  73618. };
  73619. LensFlareSystem.prototype._isVisible = function () {
  73620. if (!this._isEnabled || !this._scene.activeCamera) {
  73621. return false;
  73622. }
  73623. var emitterPosition = this.getEmitterPosition();
  73624. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  73625. var distance = direction.length();
  73626. direction.normalize();
  73627. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  73628. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  73629. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  73630. };
  73631. LensFlareSystem.prototype.render = function () {
  73632. if (!this._effect.isReady() || !this._scene.activeCamera)
  73633. return false;
  73634. var engine = this._scene.getEngine();
  73635. var viewport = this._scene.activeCamera.viewport;
  73636. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  73637. // Position
  73638. if (!this.computeEffectivePosition(globalViewport)) {
  73639. return false;
  73640. }
  73641. // Visibility
  73642. if (!this._isVisible()) {
  73643. return false;
  73644. }
  73645. // Intensity
  73646. var awayX;
  73647. var awayY;
  73648. if (this._positionX < this.borderLimit + globalViewport.x) {
  73649. awayX = this.borderLimit + globalViewport.x - this._positionX;
  73650. }
  73651. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  73652. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  73653. }
  73654. else {
  73655. awayX = 0;
  73656. }
  73657. if (this._positionY < this.borderLimit + globalViewport.y) {
  73658. awayY = this.borderLimit + globalViewport.y - this._positionY;
  73659. }
  73660. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  73661. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  73662. }
  73663. else {
  73664. awayY = 0;
  73665. }
  73666. var away = (awayX > awayY) ? awayX : awayY;
  73667. away -= this.viewportBorder;
  73668. if (away > this.borderLimit) {
  73669. away = this.borderLimit;
  73670. }
  73671. var intensity = 1.0 - (away / this.borderLimit);
  73672. if (intensity < 0) {
  73673. return false;
  73674. }
  73675. if (intensity > 1.0) {
  73676. intensity = 1.0;
  73677. }
  73678. if (this.viewportBorder > 0) {
  73679. globalViewport.x += this.viewportBorder;
  73680. globalViewport.y += this.viewportBorder;
  73681. globalViewport.width -= this.viewportBorder * 2;
  73682. globalViewport.height -= this.viewportBorder * 2;
  73683. this._positionX -= this.viewportBorder;
  73684. this._positionY -= this.viewportBorder;
  73685. }
  73686. // Position
  73687. var centerX = globalViewport.x + globalViewport.width / 2;
  73688. var centerY = globalViewport.y + globalViewport.height / 2;
  73689. var distX = centerX - this._positionX;
  73690. var distY = centerY - this._positionY;
  73691. // Effects
  73692. engine.enableEffect(this._effect);
  73693. engine.setState(false);
  73694. engine.setDepthBuffer(false);
  73695. // VBOs
  73696. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  73697. // Flares
  73698. for (var index = 0; index < this.lensFlares.length; index++) {
  73699. var flare = this.lensFlares[index];
  73700. engine.setAlphaMode(flare.alphaMode);
  73701. var x = centerX - (distX * flare.position);
  73702. var y = centerY - (distY * flare.position);
  73703. var cw = flare.size;
  73704. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  73705. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  73706. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  73707. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  73708. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  73709. // Texture
  73710. this._effect.setTexture("textureSampler", flare.texture);
  73711. // Color
  73712. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  73713. // Draw order
  73714. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73715. }
  73716. engine.setDepthBuffer(true);
  73717. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73718. return true;
  73719. };
  73720. LensFlareSystem.prototype.dispose = function () {
  73721. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73722. if (vertexBuffer) {
  73723. vertexBuffer.dispose();
  73724. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73725. }
  73726. if (this._indexBuffer) {
  73727. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73728. this._indexBuffer = null;
  73729. }
  73730. while (this.lensFlares.length) {
  73731. this.lensFlares[0].dispose();
  73732. }
  73733. // Remove from scene
  73734. var index = this._scene.lensFlareSystems.indexOf(this);
  73735. this._scene.lensFlareSystems.splice(index, 1);
  73736. };
  73737. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  73738. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  73739. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  73740. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  73741. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  73742. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  73743. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  73744. var parsedFlare = parsedLensFlareSystem.flares[index];
  73745. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  73746. }
  73747. return lensFlareSystem;
  73748. };
  73749. LensFlareSystem.prototype.serialize = function () {
  73750. var serializationObject = {};
  73751. serializationObject.id = this.id;
  73752. serializationObject.name = this.name;
  73753. serializationObject.emitterId = this.getEmitter().id;
  73754. serializationObject.borderLimit = this.borderLimit;
  73755. serializationObject.flares = [];
  73756. for (var index = 0; index < this.lensFlares.length; index++) {
  73757. var flare = this.lensFlares[index];
  73758. serializationObject.flares.push({
  73759. size: flare.size,
  73760. position: flare.position,
  73761. color: flare.color.asArray(),
  73762. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  73763. });
  73764. }
  73765. return serializationObject;
  73766. };
  73767. return LensFlareSystem;
  73768. }());
  73769. BABYLON.LensFlareSystem = LensFlareSystem;
  73770. })(BABYLON || (BABYLON = {}));
  73771. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  73772. var BABYLON;
  73773. (function (BABYLON) {
  73774. /**
  73775. * This is a holder class for the physics joint created by the physics plugin.
  73776. * It holds a set of functions to control the underlying joint.
  73777. */
  73778. var PhysicsJoint = /** @class */ (function () {
  73779. function PhysicsJoint(type, jointData) {
  73780. this.type = type;
  73781. this.jointData = jointData;
  73782. jointData.nativeParams = jointData.nativeParams || {};
  73783. }
  73784. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  73785. get: function () {
  73786. return this._physicsJoint;
  73787. },
  73788. set: function (newJoint) {
  73789. if (this._physicsJoint) {
  73790. //remove from the wolrd
  73791. }
  73792. this._physicsJoint = newJoint;
  73793. },
  73794. enumerable: true,
  73795. configurable: true
  73796. });
  73797. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  73798. set: function (physicsPlugin) {
  73799. this._physicsPlugin = physicsPlugin;
  73800. },
  73801. enumerable: true,
  73802. configurable: true
  73803. });
  73804. /**
  73805. * Execute a function that is physics-plugin specific.
  73806. * @param {Function} func the function that will be executed.
  73807. * It accepts two parameters: the physics world and the physics joint.
  73808. */
  73809. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  73810. func(this._physicsPlugin.world, this._physicsJoint);
  73811. };
  73812. //TODO check if the native joints are the same
  73813. //Joint Types
  73814. PhysicsJoint.DistanceJoint = 0;
  73815. PhysicsJoint.HingeJoint = 1;
  73816. PhysicsJoint.BallAndSocketJoint = 2;
  73817. PhysicsJoint.WheelJoint = 3;
  73818. PhysicsJoint.SliderJoint = 4;
  73819. //OIMO
  73820. PhysicsJoint.PrismaticJoint = 5;
  73821. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  73822. PhysicsJoint.UniversalJoint = 6;
  73823. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  73824. //Cannon
  73825. //Similar to a Ball-Joint. Different in params
  73826. PhysicsJoint.PointToPointJoint = 8;
  73827. //Cannon only at the moment
  73828. PhysicsJoint.SpringJoint = 9;
  73829. PhysicsJoint.LockJoint = 10;
  73830. return PhysicsJoint;
  73831. }());
  73832. BABYLON.PhysicsJoint = PhysicsJoint;
  73833. /**
  73834. * A class representing a physics distance joint.
  73835. */
  73836. var DistanceJoint = /** @class */ (function (_super) {
  73837. __extends(DistanceJoint, _super);
  73838. function DistanceJoint(jointData) {
  73839. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  73840. }
  73841. /**
  73842. * Update the predefined distance.
  73843. */
  73844. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  73845. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  73846. };
  73847. return DistanceJoint;
  73848. }(PhysicsJoint));
  73849. BABYLON.DistanceJoint = DistanceJoint;
  73850. var MotorEnabledJoint = /** @class */ (function (_super) {
  73851. __extends(MotorEnabledJoint, _super);
  73852. function MotorEnabledJoint(type, jointData) {
  73853. return _super.call(this, type, jointData) || this;
  73854. }
  73855. /**
  73856. * Set the motor values.
  73857. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73858. * @param {number} force the force to apply
  73859. * @param {number} maxForce max force for this motor.
  73860. */
  73861. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  73862. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73863. };
  73864. /**
  73865. * Set the motor's limits.
  73866. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73867. */
  73868. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73869. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73870. };
  73871. return MotorEnabledJoint;
  73872. }(PhysicsJoint));
  73873. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  73874. /**
  73875. * This class represents a single hinge physics joint
  73876. */
  73877. var HingeJoint = /** @class */ (function (_super) {
  73878. __extends(HingeJoint, _super);
  73879. function HingeJoint(jointData) {
  73880. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  73881. }
  73882. /**
  73883. * Set the motor values.
  73884. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73885. * @param {number} force the force to apply
  73886. * @param {number} maxForce max force for this motor.
  73887. */
  73888. HingeJoint.prototype.setMotor = function (force, maxForce) {
  73889. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  73890. };
  73891. /**
  73892. * Set the motor's limits.
  73893. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73894. */
  73895. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  73896. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  73897. };
  73898. return HingeJoint;
  73899. }(MotorEnabledJoint));
  73900. BABYLON.HingeJoint = HingeJoint;
  73901. /**
  73902. * This class represents a dual hinge physics joint (same as wheel joint)
  73903. */
  73904. var Hinge2Joint = /** @class */ (function (_super) {
  73905. __extends(Hinge2Joint, _super);
  73906. function Hinge2Joint(jointData) {
  73907. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  73908. }
  73909. /**
  73910. * Set the motor values.
  73911. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73912. * @param {number} force the force to apply
  73913. * @param {number} maxForce max force for this motor.
  73914. * @param {motorIndex} the motor's index, 0 or 1.
  73915. */
  73916. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  73917. if (motorIndex === void 0) { motorIndex = 0; }
  73918. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  73919. };
  73920. /**
  73921. * Set the motor limits.
  73922. * Attention, this function is plugin specific. Engines won't react 100% the same.
  73923. * @param {number} upperLimit the upper limit
  73924. * @param {number} lowerLimit lower limit
  73925. * @param {motorIndex} the motor's index, 0 or 1.
  73926. */
  73927. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  73928. if (motorIndex === void 0) { motorIndex = 0; }
  73929. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  73930. };
  73931. return Hinge2Joint;
  73932. }(MotorEnabledJoint));
  73933. BABYLON.Hinge2Joint = Hinge2Joint;
  73934. })(BABYLON || (BABYLON = {}));
  73935. //# sourceMappingURL=babylon.physicsJoint.js.map
  73936. var BABYLON;
  73937. (function (BABYLON) {
  73938. var PhysicsImpostor = /** @class */ (function () {
  73939. function PhysicsImpostor(object, type, _options, _scene) {
  73940. if (_options === void 0) { _options = { mass: 0 }; }
  73941. var _this = this;
  73942. this.object = object;
  73943. this.type = type;
  73944. this._options = _options;
  73945. this._scene = _scene;
  73946. this._bodyUpdateRequired = false;
  73947. this._onBeforePhysicsStepCallbacks = new Array();
  73948. this._onAfterPhysicsStepCallbacks = new Array();
  73949. this._onPhysicsCollideCallbacks = [];
  73950. this._deltaPosition = BABYLON.Vector3.Zero();
  73951. this._isDisposed = false;
  73952. //temp variables for parent rotation calculations
  73953. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  73954. this._tmpQuat = new BABYLON.Quaternion();
  73955. this._tmpQuat2 = new BABYLON.Quaternion();
  73956. /**
  73957. * this function is executed by the physics engine.
  73958. */
  73959. this.beforeStep = function () {
  73960. if (!_this._physicsEngine) {
  73961. return;
  73962. }
  73963. _this.object.translate(_this._deltaPosition, -1);
  73964. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  73965. _this.object.computeWorldMatrix(false);
  73966. if (_this.object.parent && _this.object.rotationQuaternion) {
  73967. _this.getParentsRotation();
  73968. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  73969. }
  73970. else {
  73971. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  73972. }
  73973. if (!_this._options.disableBidirectionalTransformation) {
  73974. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  73975. }
  73976. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  73977. func(_this);
  73978. });
  73979. };
  73980. /**
  73981. * this function is executed by the physics engine.
  73982. */
  73983. this.afterStep = function () {
  73984. if (!_this._physicsEngine) {
  73985. return;
  73986. }
  73987. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  73988. func(_this);
  73989. });
  73990. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  73991. // object has now its world rotation. needs to be converted to local.
  73992. if (_this.object.parent && _this.object.rotationQuaternion) {
  73993. _this.getParentsRotation();
  73994. _this._tmpQuat.conjugateInPlace();
  73995. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  73996. }
  73997. // take the position set and make it the absolute position of this object.
  73998. _this.object.setAbsolutePosition(_this.object.position);
  73999. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74000. _this.object.translate(_this._deltaPosition, 1);
  74001. };
  74002. /**
  74003. * Legacy collision detection event support
  74004. */
  74005. this.onCollideEvent = null;
  74006. //event and body object due to cannon's event-based architecture.
  74007. this.onCollide = function (e) {
  74008. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74009. return;
  74010. }
  74011. if (!_this._physicsEngine) {
  74012. return;
  74013. }
  74014. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74015. if (otherImpostor) {
  74016. // Legacy collision detection event support
  74017. if (_this.onCollideEvent) {
  74018. _this.onCollideEvent(_this, otherImpostor);
  74019. }
  74020. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74021. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74022. }).forEach(function (obj) {
  74023. obj.callback(_this, otherImpostor);
  74024. });
  74025. }
  74026. };
  74027. //sanity check!
  74028. if (!this.object) {
  74029. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74030. return;
  74031. }
  74032. //legacy support for old syntax.
  74033. if (!this._scene && object.getScene) {
  74034. this._scene = object.getScene();
  74035. }
  74036. if (!this._scene) {
  74037. return;
  74038. }
  74039. this._physicsEngine = this._scene.getPhysicsEngine();
  74040. if (!this._physicsEngine) {
  74041. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74042. }
  74043. else {
  74044. //set the object's quaternion, if not set
  74045. if (!this.object.rotationQuaternion) {
  74046. if (this.object.rotation) {
  74047. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74048. }
  74049. else {
  74050. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74051. }
  74052. }
  74053. //default options params
  74054. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74055. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74056. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74057. this._joints = [];
  74058. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74059. if (!this.object.parent || this._options.ignoreParent) {
  74060. this._init();
  74061. }
  74062. else if (this.object.parent.physicsImpostor) {
  74063. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74064. }
  74065. }
  74066. }
  74067. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74068. get: function () {
  74069. return this._isDisposed;
  74070. },
  74071. enumerable: true,
  74072. configurable: true
  74073. });
  74074. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74075. get: function () {
  74076. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74077. },
  74078. set: function (value) {
  74079. this.setMass(value);
  74080. },
  74081. enumerable: true,
  74082. configurable: true
  74083. });
  74084. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74085. get: function () {
  74086. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74087. },
  74088. set: function (value) {
  74089. if (!this._physicsEngine) {
  74090. return;
  74091. }
  74092. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74093. },
  74094. enumerable: true,
  74095. configurable: true
  74096. });
  74097. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74098. get: function () {
  74099. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74100. },
  74101. set: function (value) {
  74102. if (!this._physicsEngine) {
  74103. return;
  74104. }
  74105. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74106. },
  74107. enumerable: true,
  74108. configurable: true
  74109. });
  74110. /**
  74111. * This function will completly initialize this impostor.
  74112. * It will create a new body - but only if this mesh has no parent.
  74113. * If it has, this impostor will not be used other than to define the impostor
  74114. * of the child mesh.
  74115. */
  74116. PhysicsImpostor.prototype._init = function () {
  74117. if (!this._physicsEngine) {
  74118. return;
  74119. }
  74120. this._physicsEngine.removeImpostor(this);
  74121. this.physicsBody = null;
  74122. this._parent = this._parent || this._getPhysicsParent();
  74123. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74124. this._physicsEngine.addImpostor(this);
  74125. }
  74126. };
  74127. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74128. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74129. var parentMesh = this.object.parent;
  74130. return parentMesh.physicsImpostor;
  74131. }
  74132. return null;
  74133. };
  74134. /**
  74135. * Should a new body be generated.
  74136. */
  74137. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74138. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74139. };
  74140. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74141. this.forceUpdate();
  74142. };
  74143. /**
  74144. * Force a regeneration of this or the parent's impostor's body.
  74145. * Use under cautious - This will remove all joints already implemented.
  74146. */
  74147. PhysicsImpostor.prototype.forceUpdate = function () {
  74148. this._init();
  74149. if (this.parent && !this._options.ignoreParent) {
  74150. this.parent.forceUpdate();
  74151. }
  74152. };
  74153. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74154. /*public get mesh(): AbstractMesh {
  74155. return this._mesh;
  74156. }*/
  74157. /**
  74158. * Gets the body that holds this impostor. Either its own, or its parent.
  74159. */
  74160. get: function () {
  74161. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74162. },
  74163. /**
  74164. * Set the physics body. Used mainly by the physics engine/plugin
  74165. */
  74166. set: function (physicsBody) {
  74167. if (this._physicsBody && this._physicsEngine) {
  74168. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74169. }
  74170. this._physicsBody = physicsBody;
  74171. this.resetUpdateFlags();
  74172. },
  74173. enumerable: true,
  74174. configurable: true
  74175. });
  74176. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74177. get: function () {
  74178. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74179. },
  74180. set: function (value) {
  74181. this._parent = value;
  74182. },
  74183. enumerable: true,
  74184. configurable: true
  74185. });
  74186. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74187. this._bodyUpdateRequired = false;
  74188. };
  74189. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74190. if (this.object.getBoundingInfo) {
  74191. var q = this.object.rotationQuaternion;
  74192. //reset rotation
  74193. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74194. //calculate the world matrix with no rotation
  74195. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74196. var boundingInfo = this.object.getBoundingInfo();
  74197. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74198. //bring back the rotation
  74199. this.object.rotationQuaternion = q;
  74200. //calculate the world matrix with the new rotation
  74201. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74202. return size;
  74203. }
  74204. else {
  74205. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74206. }
  74207. };
  74208. PhysicsImpostor.prototype.getObjectCenter = function () {
  74209. if (this.object.getBoundingInfo) {
  74210. var boundingInfo = this.object.getBoundingInfo();
  74211. return boundingInfo.boundingBox.centerWorld;
  74212. }
  74213. else {
  74214. return this.object.position;
  74215. }
  74216. };
  74217. /**
  74218. * Get a specific parametes from the options parameter.
  74219. */
  74220. PhysicsImpostor.prototype.getParam = function (paramName) {
  74221. return this._options[paramName];
  74222. };
  74223. /**
  74224. * Sets a specific parameter in the options given to the physics plugin
  74225. */
  74226. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74227. this._options[paramName] = value;
  74228. this._bodyUpdateRequired = true;
  74229. };
  74230. /**
  74231. * Specifically change the body's mass option. Won't recreate the physics body object
  74232. */
  74233. PhysicsImpostor.prototype.setMass = function (mass) {
  74234. if (this.getParam("mass") !== mass) {
  74235. this.setParam("mass", mass);
  74236. }
  74237. if (this._physicsEngine) {
  74238. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74239. }
  74240. };
  74241. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74242. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74243. };
  74244. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74245. if (this._physicsEngine) {
  74246. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74247. }
  74248. };
  74249. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74250. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74251. };
  74252. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74253. if (this._physicsEngine) {
  74254. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74255. }
  74256. };
  74257. /**
  74258. * Execute a function with the physics plugin native code.
  74259. * Provide a function the will have two variables - the world object and the physics body object.
  74260. */
  74261. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74262. if (this._physicsEngine) {
  74263. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74264. }
  74265. };
  74266. /**
  74267. * Register a function that will be executed before the physics world is stepping forward.
  74268. */
  74269. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74270. this._onBeforePhysicsStepCallbacks.push(func);
  74271. };
  74272. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74273. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74274. if (index > -1) {
  74275. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74276. }
  74277. else {
  74278. BABYLON.Tools.Warn("Function to remove was not found");
  74279. }
  74280. };
  74281. /**
  74282. * Register a function that will be executed after the physics step
  74283. */
  74284. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74285. this._onAfterPhysicsStepCallbacks.push(func);
  74286. };
  74287. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74288. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74289. if (index > -1) {
  74290. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74291. }
  74292. else {
  74293. BABYLON.Tools.Warn("Function to remove was not found");
  74294. }
  74295. };
  74296. /**
  74297. * register a function that will be executed when this impostor collides against a different body.
  74298. */
  74299. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74300. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74301. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74302. };
  74303. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74304. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74305. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74306. if (index > -1) {
  74307. this._onPhysicsCollideCallbacks.splice(index, 1);
  74308. }
  74309. else {
  74310. BABYLON.Tools.Warn("Function to remove was not found");
  74311. }
  74312. };
  74313. PhysicsImpostor.prototype.getParentsRotation = function () {
  74314. var parent = this.object.parent;
  74315. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74316. while (parent) {
  74317. if (parent.rotationQuaternion) {
  74318. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74319. }
  74320. else {
  74321. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74322. }
  74323. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74324. parent = parent.parent;
  74325. }
  74326. return this._tmpQuat;
  74327. };
  74328. /**
  74329. * Apply a force
  74330. */
  74331. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74332. if (this._physicsEngine) {
  74333. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74334. }
  74335. return this;
  74336. };
  74337. /**
  74338. * Apply an impulse
  74339. */
  74340. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74341. if (this._physicsEngine) {
  74342. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74343. }
  74344. return this;
  74345. };
  74346. /**
  74347. * A help function to create a joint.
  74348. */
  74349. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74350. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74351. this.addJoint(otherImpostor, joint);
  74352. return this;
  74353. };
  74354. /**
  74355. * Add a joint to this impostor with a different impostor.
  74356. */
  74357. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74358. this._joints.push({
  74359. otherImpostor: otherImpostor,
  74360. joint: joint
  74361. });
  74362. if (this._physicsEngine) {
  74363. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74364. }
  74365. return this;
  74366. };
  74367. /**
  74368. * Will keep this body still, in a sleep mode.
  74369. */
  74370. PhysicsImpostor.prototype.sleep = function () {
  74371. if (this._physicsEngine) {
  74372. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  74373. }
  74374. return this;
  74375. };
  74376. /**
  74377. * Wake the body up.
  74378. */
  74379. PhysicsImpostor.prototype.wakeUp = function () {
  74380. if (this._physicsEngine) {
  74381. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  74382. }
  74383. return this;
  74384. };
  74385. PhysicsImpostor.prototype.clone = function (newObject) {
  74386. if (!newObject)
  74387. return null;
  74388. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  74389. };
  74390. PhysicsImpostor.prototype.dispose = function () {
  74391. var _this = this;
  74392. //no dispose if no physics engine is available.
  74393. if (!this._physicsEngine) {
  74394. return;
  74395. }
  74396. this._joints.forEach(function (j) {
  74397. if (_this._physicsEngine) {
  74398. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  74399. }
  74400. });
  74401. //dispose the physics body
  74402. this._physicsEngine.removeImpostor(this);
  74403. if (this.parent) {
  74404. this.parent.forceUpdate();
  74405. }
  74406. else {
  74407. /*this._object.getChildMeshes().forEach(function(mesh) {
  74408. if (mesh.physicsImpostor) {
  74409. if (disposeChildren) {
  74410. mesh.physicsImpostor.dispose();
  74411. mesh.physicsImpostor = null;
  74412. }
  74413. }
  74414. })*/
  74415. }
  74416. this._isDisposed = true;
  74417. };
  74418. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  74419. this._deltaPosition.copyFrom(position);
  74420. };
  74421. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  74422. if (!this._deltaRotation) {
  74423. this._deltaRotation = new BABYLON.Quaternion();
  74424. }
  74425. this._deltaRotation.copyFrom(rotation);
  74426. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  74427. };
  74428. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  74429. if (this._physicsEngine) {
  74430. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  74431. }
  74432. return this;
  74433. };
  74434. PhysicsImpostor.prototype.getRadius = function () {
  74435. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  74436. };
  74437. /**
  74438. * Sync a bone with this impostor
  74439. * @param bone The bone to sync to the impostor.
  74440. * @param boneMesh The mesh that the bone is influencing.
  74441. * @param jointPivot The pivot of the joint / bone in local space.
  74442. * @param distToJoint Optional distance from the impostor to the joint.
  74443. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74444. */
  74445. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  74446. var tempVec = PhysicsImpostor._tmpVecs[0];
  74447. var mesh = this.object;
  74448. if (mesh.rotationQuaternion) {
  74449. if (adjustRotation) {
  74450. var tempQuat = PhysicsImpostor._tmpQuat;
  74451. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  74452. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  74453. }
  74454. else {
  74455. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  74456. }
  74457. }
  74458. tempVec.x = 0;
  74459. tempVec.y = 0;
  74460. tempVec.z = 0;
  74461. if (jointPivot) {
  74462. tempVec.x = jointPivot.x;
  74463. tempVec.y = jointPivot.y;
  74464. tempVec.z = jointPivot.z;
  74465. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  74466. if (distToJoint === undefined || distToJoint === null) {
  74467. distToJoint = jointPivot.length();
  74468. }
  74469. tempVec.x *= distToJoint;
  74470. tempVec.y *= distToJoint;
  74471. tempVec.z *= distToJoint;
  74472. }
  74473. if (bone.getParent()) {
  74474. tempVec.addInPlace(mesh.getAbsolutePosition());
  74475. bone.setAbsolutePosition(tempVec, boneMesh);
  74476. }
  74477. else {
  74478. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  74479. boneMesh.position.x -= tempVec.x;
  74480. boneMesh.position.y -= tempVec.y;
  74481. boneMesh.position.z -= tempVec.z;
  74482. }
  74483. };
  74484. /**
  74485. * Sync impostor to a bone
  74486. * @param bone The bone that the impostor will be synced to.
  74487. * @param boneMesh The mesh that the bone is influencing.
  74488. * @param jointPivot The pivot of the joint / bone in local space.
  74489. * @param distToJoint Optional distance from the impostor to the joint.
  74490. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74491. * @param boneAxis Optional vector3 axis the bone is aligned with
  74492. */
  74493. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  74494. var mesh = this.object;
  74495. if (mesh.rotationQuaternion) {
  74496. if (adjustRotation) {
  74497. var tempQuat = PhysicsImpostor._tmpQuat;
  74498. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  74499. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  74500. }
  74501. else {
  74502. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  74503. }
  74504. }
  74505. var pos = PhysicsImpostor._tmpVecs[0];
  74506. var boneDir = PhysicsImpostor._tmpVecs[1];
  74507. if (!boneAxis) {
  74508. boneAxis = PhysicsImpostor._tmpVecs[2];
  74509. boneAxis.x = 0;
  74510. boneAxis.y = 1;
  74511. boneAxis.z = 0;
  74512. }
  74513. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  74514. bone.getAbsolutePositionToRef(boneMesh, pos);
  74515. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  74516. distToJoint = jointPivot.length();
  74517. }
  74518. if (distToJoint !== undefined && distToJoint !== null) {
  74519. pos.x += boneDir.x * distToJoint;
  74520. pos.y += boneDir.y * distToJoint;
  74521. pos.z += boneDir.z * distToJoint;
  74522. }
  74523. mesh.setAbsolutePosition(pos);
  74524. };
  74525. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  74526. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  74527. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  74528. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  74529. //Impostor types
  74530. PhysicsImpostor.NoImpostor = 0;
  74531. PhysicsImpostor.SphereImpostor = 1;
  74532. PhysicsImpostor.BoxImpostor = 2;
  74533. PhysicsImpostor.PlaneImpostor = 3;
  74534. PhysicsImpostor.MeshImpostor = 4;
  74535. PhysicsImpostor.CylinderImpostor = 7;
  74536. PhysicsImpostor.ParticleImpostor = 8;
  74537. PhysicsImpostor.HeightmapImpostor = 9;
  74538. return PhysicsImpostor;
  74539. }());
  74540. BABYLON.PhysicsImpostor = PhysicsImpostor;
  74541. })(BABYLON || (BABYLON = {}));
  74542. //# sourceMappingURL=babylon.physicsImpostor.js.map
  74543. var BABYLON;
  74544. (function (BABYLON) {
  74545. var PhysicsEngine = /** @class */ (function () {
  74546. function PhysicsEngine(gravity, _physicsPlugin) {
  74547. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  74548. this._physicsPlugin = _physicsPlugin;
  74549. //new methods and parameters
  74550. this._impostors = [];
  74551. this._joints = [];
  74552. if (!this._physicsPlugin.isSupported()) {
  74553. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  74554. + "Please make sure it is included.");
  74555. }
  74556. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  74557. this.setGravity(gravity);
  74558. this.setTimeStep();
  74559. }
  74560. PhysicsEngine.prototype.setGravity = function (gravity) {
  74561. this.gravity = gravity;
  74562. this._physicsPlugin.setGravity(this.gravity);
  74563. };
  74564. /**
  74565. * Set the time step of the physics engine.
  74566. * default is 1/60.
  74567. * To slow it down, enter 1/600 for example.
  74568. * To speed it up, 1/30
  74569. * @param {number} newTimeStep the new timestep to apply to this world.
  74570. */
  74571. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  74572. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  74573. this._physicsPlugin.setTimeStep(newTimeStep);
  74574. };
  74575. /**
  74576. * Get the time step of the physics engine.
  74577. */
  74578. PhysicsEngine.prototype.getTimeStep = function () {
  74579. return this._physicsPlugin.getTimeStep();
  74580. };
  74581. PhysicsEngine.prototype.dispose = function () {
  74582. this._impostors.forEach(function (impostor) {
  74583. impostor.dispose();
  74584. });
  74585. this._physicsPlugin.dispose();
  74586. };
  74587. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  74588. return this._physicsPlugin.name;
  74589. };
  74590. /**
  74591. * Adding a new impostor for the impostor tracking.
  74592. * This will be done by the impostor itself.
  74593. * @param {PhysicsImpostor} impostor the impostor to add
  74594. */
  74595. PhysicsEngine.prototype.addImpostor = function (impostor) {
  74596. impostor.uniqueId = this._impostors.push(impostor);
  74597. //if no parent, generate the body
  74598. if (!impostor.parent) {
  74599. this._physicsPlugin.generatePhysicsBody(impostor);
  74600. }
  74601. };
  74602. /**
  74603. * Remove an impostor from the engine.
  74604. * This impostor and its mesh will not longer be updated by the physics engine.
  74605. * @param {PhysicsImpostor} impostor the impostor to remove
  74606. */
  74607. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  74608. var index = this._impostors.indexOf(impostor);
  74609. if (index > -1) {
  74610. var removed = this._impostors.splice(index, 1);
  74611. //Is it needed?
  74612. if (removed.length) {
  74613. //this will also remove it from the world.
  74614. removed[0].physicsBody = null;
  74615. }
  74616. }
  74617. };
  74618. /**
  74619. * Add a joint to the physics engine
  74620. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  74621. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  74622. * @param {PhysicsJoint} the joint that will connect both impostors.
  74623. */
  74624. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  74625. var impostorJoint = {
  74626. mainImpostor: mainImpostor,
  74627. connectedImpostor: connectedImpostor,
  74628. joint: joint
  74629. };
  74630. joint.physicsPlugin = this._physicsPlugin;
  74631. this._joints.push(impostorJoint);
  74632. this._physicsPlugin.generateJoint(impostorJoint);
  74633. };
  74634. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  74635. var matchingJoints = this._joints.filter(function (impostorJoint) {
  74636. return (impostorJoint.connectedImpostor === connectedImpostor
  74637. && impostorJoint.joint === joint
  74638. && impostorJoint.mainImpostor === mainImpostor);
  74639. });
  74640. if (matchingJoints.length) {
  74641. this._physicsPlugin.removeJoint(matchingJoints[0]);
  74642. //TODO remove it from the list as well
  74643. }
  74644. };
  74645. /**
  74646. * Called by the scene. no need to call it.
  74647. */
  74648. PhysicsEngine.prototype._step = function (delta) {
  74649. var _this = this;
  74650. //check if any mesh has no body / requires an update
  74651. this._impostors.forEach(function (impostor) {
  74652. if (impostor.isBodyInitRequired()) {
  74653. _this._physicsPlugin.generatePhysicsBody(impostor);
  74654. }
  74655. });
  74656. if (delta > 0.1) {
  74657. delta = 0.1;
  74658. }
  74659. else if (delta <= 0) {
  74660. delta = 1.0 / 60.0;
  74661. }
  74662. this._physicsPlugin.executeStep(delta, this._impostors);
  74663. };
  74664. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  74665. return this._physicsPlugin;
  74666. };
  74667. PhysicsEngine.prototype.getImpostors = function () {
  74668. return this._impostors;
  74669. };
  74670. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  74671. for (var i = 0; i < this._impostors.length; ++i) {
  74672. if (this._impostors[i].object === object) {
  74673. return this._impostors[i];
  74674. }
  74675. }
  74676. return null;
  74677. };
  74678. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  74679. for (var i = 0; i < this._impostors.length; ++i) {
  74680. if (this._impostors[i].physicsBody === body) {
  74681. return this._impostors[i];
  74682. }
  74683. }
  74684. return null;
  74685. };
  74686. // Statics
  74687. PhysicsEngine.Epsilon = 0.001;
  74688. return PhysicsEngine;
  74689. }());
  74690. BABYLON.PhysicsEngine = PhysicsEngine;
  74691. })(BABYLON || (BABYLON = {}));
  74692. //# sourceMappingURL=babylon.physicsEngine.js.map
  74693. var BABYLON;
  74694. (function (BABYLON) {
  74695. var PhysicsHelper = /** @class */ (function () {
  74696. function PhysicsHelper(scene) {
  74697. this._scene = scene;
  74698. this._physicsEngine = this._scene.getPhysicsEngine();
  74699. if (!this._physicsEngine) {
  74700. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  74701. }
  74702. }
  74703. /**
  74704. * @param {Vector3} origin the origin of the explosion
  74705. * @param {number} radius the explosion radius
  74706. * @param {number} strength the explosion strength
  74707. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74708. */
  74709. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  74710. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74711. if (!this._physicsEngine) {
  74712. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  74713. return null;
  74714. }
  74715. var impostors = this._physicsEngine.getImpostors();
  74716. if (impostors.length === 0) {
  74717. return null;
  74718. }
  74719. var event = new PhysicsRadialExplosionEvent(this._scene);
  74720. impostors.forEach(function (impostor) {
  74721. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74722. if (!impostorForceAndContactPoint) {
  74723. return;
  74724. }
  74725. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74726. });
  74727. event.dispose(false);
  74728. return event;
  74729. };
  74730. /**
  74731. * @param {Vector3} origin the origin of the explosion
  74732. * @param {number} radius the explosion radius
  74733. * @param {number} strength the explosion strength
  74734. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74735. */
  74736. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  74737. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74738. if (!this._physicsEngine) {
  74739. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74740. return null;
  74741. }
  74742. var impostors = this._physicsEngine.getImpostors();
  74743. if (impostors.length === 0) {
  74744. return null;
  74745. }
  74746. var event = new PhysicsRadialExplosionEvent(this._scene);
  74747. impostors.forEach(function (impostor) {
  74748. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  74749. if (!impostorForceAndContactPoint) {
  74750. return;
  74751. }
  74752. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  74753. });
  74754. event.dispose(false);
  74755. return event;
  74756. };
  74757. /**
  74758. * @param {Vector3} origin the origin of the explosion
  74759. * @param {number} radius the explosion radius
  74760. * @param {number} strength the explosion strength
  74761. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  74762. */
  74763. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  74764. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74765. if (!this._physicsEngine) {
  74766. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74767. return null;
  74768. }
  74769. var impostors = this._physicsEngine.getImpostors();
  74770. if (impostors.length === 0) {
  74771. return null;
  74772. }
  74773. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  74774. event.dispose(false);
  74775. return event;
  74776. };
  74777. /**
  74778. * @param {Vector3} origin the origin of the updraft
  74779. * @param {number} radius the radius of the updraft
  74780. * @param {number} strength the strength of the updraft
  74781. * @param {number} height the height of the updraft
  74782. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  74783. */
  74784. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  74785. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  74786. if (!this._physicsEngine) {
  74787. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74788. return null;
  74789. }
  74790. if (this._physicsEngine.getImpostors().length === 0) {
  74791. return null;
  74792. }
  74793. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  74794. event.dispose(false);
  74795. return event;
  74796. };
  74797. /**
  74798. * @param {Vector3} origin the of the vortex
  74799. * @param {number} radius the radius of the vortex
  74800. * @param {number} strength the strength of the vortex
  74801. * @param {number} height the height of the vortex
  74802. */
  74803. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  74804. if (!this._physicsEngine) {
  74805. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  74806. return null;
  74807. }
  74808. if (this._physicsEngine.getImpostors().length === 0) {
  74809. return null;
  74810. }
  74811. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  74812. event.dispose(false);
  74813. return event;
  74814. };
  74815. return PhysicsHelper;
  74816. }());
  74817. BABYLON.PhysicsHelper = PhysicsHelper;
  74818. /***** Radial explosion *****/
  74819. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  74820. function PhysicsRadialExplosionEvent(scene) {
  74821. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  74822. this._rays = [];
  74823. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  74824. this._scene = scene;
  74825. }
  74826. /**
  74827. * Returns the data related to the radial explosion event (sphere & rays).
  74828. * @returns {PhysicsRadialExplosionEventData}
  74829. */
  74830. PhysicsRadialExplosionEvent.prototype.getData = function () {
  74831. this._dataFetched = true;
  74832. return {
  74833. sphere: this._sphere,
  74834. rays: this._rays,
  74835. };
  74836. };
  74837. /**
  74838. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  74839. * @param impostor
  74840. * @param {Vector3} origin the origin of the explosion
  74841. * @param {number} radius the explosion radius
  74842. * @param {number} strength the explosion strength
  74843. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  74844. * @returns {Nullable<PhysicsForceAndContactPoint>}
  74845. */
  74846. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  74847. if (impostor.mass === 0) {
  74848. return null;
  74849. }
  74850. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  74851. return null;
  74852. }
  74853. if (impostor.object.getClassName() !== 'Mesh') {
  74854. return null;
  74855. }
  74856. var impostorObject = impostor.object;
  74857. var impostorObjectCenter = impostor.getObjectCenter();
  74858. var direction = impostorObjectCenter.subtract(origin);
  74859. var ray = new BABYLON.Ray(origin, direction, radius);
  74860. this._rays.push(ray);
  74861. var hit = ray.intersectsMesh(impostorObject);
  74862. var contactPoint = hit.pickedPoint;
  74863. if (!contactPoint) {
  74864. return null;
  74865. }
  74866. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  74867. if (distanceFromOrigin > radius) {
  74868. return null;
  74869. }
  74870. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  74871. ? strength
  74872. : strength * (1 - (distanceFromOrigin / radius));
  74873. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  74874. return { force: force, contactPoint: contactPoint };
  74875. };
  74876. /**
  74877. * Disposes the sphere.
  74878. * @param {bolean} force
  74879. */
  74880. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  74881. var _this = this;
  74882. if (force === void 0) { force = true; }
  74883. if (force) {
  74884. this._sphere.dispose();
  74885. }
  74886. else {
  74887. setTimeout(function () {
  74888. if (!_this._dataFetched) {
  74889. _this._sphere.dispose();
  74890. }
  74891. }, 0);
  74892. }
  74893. };
  74894. /*** Helpers ***/
  74895. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  74896. if (!this._sphere) {
  74897. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  74898. this._sphere.isVisible = false;
  74899. }
  74900. };
  74901. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  74902. var impostorObject = impostor.object;
  74903. this._prepareSphere();
  74904. this._sphere.position = origin;
  74905. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  74906. this._sphere._updateBoundingInfo();
  74907. this._sphere.computeWorldMatrix(true);
  74908. return this._sphere.intersectsMesh(impostorObject, true);
  74909. };
  74910. return PhysicsRadialExplosionEvent;
  74911. }());
  74912. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  74913. /***** Gravitational Field *****/
  74914. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  74915. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  74916. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  74917. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74918. this._physicsHelper = physicsHelper;
  74919. this._scene = scene;
  74920. this._origin = origin;
  74921. this._radius = radius;
  74922. this._strength = strength;
  74923. this._falloff = falloff;
  74924. this._tickCallback = this._tick.bind(this);
  74925. }
  74926. /**
  74927. * Returns the data related to the gravitational field event (sphere).
  74928. * @returns {PhysicsGravitationalFieldEventData}
  74929. */
  74930. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  74931. this._dataFetched = true;
  74932. return {
  74933. sphere: this._sphere,
  74934. };
  74935. };
  74936. /**
  74937. * Enables the gravitational field.
  74938. */
  74939. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  74940. this._tickCallback.call(this);
  74941. this._scene.registerBeforeRender(this._tickCallback);
  74942. };
  74943. /**
  74944. * Disables the gravitational field.
  74945. */
  74946. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  74947. this._scene.unregisterBeforeRender(this._tickCallback);
  74948. };
  74949. /**
  74950. * Disposes the sphere.
  74951. * @param {bolean} force
  74952. */
  74953. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  74954. var _this = this;
  74955. if (force === void 0) { force = true; }
  74956. if (force) {
  74957. this._sphere.dispose();
  74958. }
  74959. else {
  74960. setTimeout(function () {
  74961. if (!_this._dataFetched) {
  74962. _this._sphere.dispose();
  74963. }
  74964. }, 0);
  74965. }
  74966. };
  74967. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  74968. // Since the params won't change, we fetch the event only once
  74969. if (this._sphere) {
  74970. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74971. }
  74972. else {
  74973. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  74974. if (radialExplosionEvent) {
  74975. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  74976. }
  74977. }
  74978. };
  74979. return PhysicsGravitationalFieldEvent;
  74980. }());
  74981. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  74982. /***** Updraft *****/
  74983. var PhysicsUpdraftEvent = /** @class */ (function () {
  74984. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  74985. this._scene = _scene;
  74986. this._origin = _origin;
  74987. this._radius = _radius;
  74988. this._strength = _strength;
  74989. this._height = _height;
  74990. this._updraftMode = _updraftMode;
  74991. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  74992. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  74993. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  74994. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  74995. this._physicsEngine = this._scene.getPhysicsEngine();
  74996. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  74997. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  74998. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  74999. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75000. }
  75001. this._tickCallback = this._tick.bind(this);
  75002. }
  75003. /**
  75004. * Returns the data related to the updraft event (cylinder).
  75005. * @returns {PhysicsUpdraftEventData}
  75006. */
  75007. PhysicsUpdraftEvent.prototype.getData = function () {
  75008. this._dataFetched = true;
  75009. return {
  75010. cylinder: this._cylinder,
  75011. };
  75012. };
  75013. /**
  75014. * Enables the updraft.
  75015. */
  75016. PhysicsUpdraftEvent.prototype.enable = function () {
  75017. this._tickCallback.call(this);
  75018. this._scene.registerBeforeRender(this._tickCallback);
  75019. };
  75020. /**
  75021. * Disables the cortex.
  75022. */
  75023. PhysicsUpdraftEvent.prototype.disable = function () {
  75024. this._scene.unregisterBeforeRender(this._tickCallback);
  75025. };
  75026. /**
  75027. * Disposes the sphere.
  75028. * @param {bolean} force
  75029. */
  75030. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75031. var _this = this;
  75032. if (force === void 0) { force = true; }
  75033. if (force) {
  75034. this._cylinder.dispose();
  75035. }
  75036. else {
  75037. setTimeout(function () {
  75038. if (!_this._dataFetched) {
  75039. _this._cylinder.dispose();
  75040. }
  75041. }, 0);
  75042. }
  75043. };
  75044. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75045. if (impostor.mass === 0) {
  75046. return null;
  75047. }
  75048. if (!this._intersectsWithCylinder(impostor)) {
  75049. return null;
  75050. }
  75051. var impostorObjectCenter = impostor.getObjectCenter();
  75052. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75053. var direction = this._originDirection;
  75054. }
  75055. else {
  75056. var direction = impostorObjectCenter.subtract(this._originTop);
  75057. }
  75058. var multiplier = this._strength * -1;
  75059. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75060. return { force: force, contactPoint: impostorObjectCenter };
  75061. };
  75062. PhysicsUpdraftEvent.prototype._tick = function () {
  75063. var _this = this;
  75064. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75065. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75066. if (!impostorForceAndContactPoint) {
  75067. return;
  75068. }
  75069. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75070. });
  75071. };
  75072. /*** Helpers ***/
  75073. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75074. if (!this._cylinder) {
  75075. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75076. height: this._height,
  75077. diameter: this._radius * 2,
  75078. }, this._scene);
  75079. this._cylinder.isVisible = false;
  75080. }
  75081. };
  75082. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75083. var impostorObject = impostor.object;
  75084. this._prepareCylinder();
  75085. this._cylinder.position = this._cylinderPosition;
  75086. return this._cylinder.intersectsMesh(impostorObject, true);
  75087. };
  75088. return PhysicsUpdraftEvent;
  75089. }());
  75090. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75091. /***** Vortex *****/
  75092. var PhysicsVortexEvent = /** @class */ (function () {
  75093. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75094. this._scene = _scene;
  75095. this._origin = _origin;
  75096. this._radius = _radius;
  75097. this._strength = _strength;
  75098. this._height = _height;
  75099. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75100. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75101. this._updraftMultiplier = 0.02;
  75102. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75103. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75104. this._physicsEngine = this._scene.getPhysicsEngine();
  75105. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75106. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75107. this._tickCallback = this._tick.bind(this);
  75108. }
  75109. /**
  75110. * Returns the data related to the vortex event (cylinder).
  75111. * @returns {PhysicsVortexEventData}
  75112. */
  75113. PhysicsVortexEvent.prototype.getData = function () {
  75114. this._dataFetched = true;
  75115. return {
  75116. cylinder: this._cylinder,
  75117. };
  75118. };
  75119. /**
  75120. * Enables the vortex.
  75121. */
  75122. PhysicsVortexEvent.prototype.enable = function () {
  75123. this._tickCallback.call(this);
  75124. this._scene.registerBeforeRender(this._tickCallback);
  75125. };
  75126. /**
  75127. * Disables the cortex.
  75128. */
  75129. PhysicsVortexEvent.prototype.disable = function () {
  75130. this._scene.unregisterBeforeRender(this._tickCallback);
  75131. };
  75132. /**
  75133. * Disposes the sphere.
  75134. * @param {bolean} force
  75135. */
  75136. PhysicsVortexEvent.prototype.dispose = function (force) {
  75137. var _this = this;
  75138. if (force === void 0) { force = true; }
  75139. if (force) {
  75140. this._cylinder.dispose();
  75141. }
  75142. else {
  75143. setTimeout(function () {
  75144. if (!_this._dataFetched) {
  75145. _this._cylinder.dispose();
  75146. }
  75147. }, 0);
  75148. }
  75149. };
  75150. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75151. if (impostor.mass === 0) {
  75152. return null;
  75153. }
  75154. if (!this._intersectsWithCylinder(impostor)) {
  75155. return null;
  75156. }
  75157. if (impostor.object.getClassName() !== 'Mesh') {
  75158. return null;
  75159. }
  75160. var impostorObject = impostor.object;
  75161. var impostorObjectCenter = impostor.getObjectCenter();
  75162. 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)
  75163. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75164. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75165. var hit = ray.intersectsMesh(impostorObject);
  75166. var contactPoint = hit.pickedPoint;
  75167. if (!contactPoint) {
  75168. return null;
  75169. }
  75170. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75171. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75172. var directionToOrigin = contactPoint.normalize();
  75173. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75174. directionToOrigin = directionToOrigin.negate();
  75175. }
  75176. // TODO: find a more physically based solution
  75177. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75178. var forceX = directionToOrigin.x * this._strength / 8;
  75179. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75180. var forceZ = directionToOrigin.z * this._strength / 8;
  75181. }
  75182. else {
  75183. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75184. var forceY = this._originTop.y * this._updraftMultiplier;
  75185. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75186. }
  75187. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75188. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75189. return { force: force, contactPoint: impostorObjectCenter };
  75190. };
  75191. PhysicsVortexEvent.prototype._tick = function () {
  75192. var _this = this;
  75193. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75194. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75195. if (!impostorForceAndContactPoint) {
  75196. return;
  75197. }
  75198. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75199. });
  75200. };
  75201. /*** Helpers ***/
  75202. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75203. if (!this._cylinder) {
  75204. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75205. height: this._height,
  75206. diameter: this._radius * 2,
  75207. }, this._scene);
  75208. this._cylinder.isVisible = false;
  75209. }
  75210. };
  75211. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75212. var impostorObject = impostor.object;
  75213. this._prepareCylinder();
  75214. this._cylinder.position = this._cylinderPosition;
  75215. return this._cylinder.intersectsMesh(impostorObject, true);
  75216. };
  75217. return PhysicsVortexEvent;
  75218. }());
  75219. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75220. /***** Enums *****/
  75221. /**
  75222. * The strenght of the force in correspondence to the distance of the affected object
  75223. */
  75224. var PhysicsRadialImpulseFalloff;
  75225. (function (PhysicsRadialImpulseFalloff) {
  75226. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75227. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75228. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75229. /**
  75230. * The strenght of the force in correspondence to the distance of the affected object
  75231. */
  75232. var PhysicsUpdraftMode;
  75233. (function (PhysicsUpdraftMode) {
  75234. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75235. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75236. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75237. })(BABYLON || (BABYLON = {}));
  75238. //# sourceMappingURL=babylon.physicsHelper.js.map
  75239. var BABYLON;
  75240. (function (BABYLON) {
  75241. var CannonJSPlugin = /** @class */ (function () {
  75242. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75243. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75244. if (iterations === void 0) { iterations = 10; }
  75245. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75246. this.name = "CannonJSPlugin";
  75247. this._physicsMaterials = new Array();
  75248. this._fixedTimeStep = 1 / 60;
  75249. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75250. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : ( true ? __webpack_require__(17) : undefined);
  75251. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75252. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75253. this._tmpPosition = BABYLON.Vector3.Zero();
  75254. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75255. this._tmpUnityRotation = new BABYLON.Quaternion();
  75256. if (!this.isSupported()) {
  75257. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75258. return;
  75259. }
  75260. this._extendNamespace();
  75261. this.world = new this.BJSCANNON.World();
  75262. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75263. this.world.solver.iterations = iterations;
  75264. }
  75265. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75266. this.world.gravity.copy(gravity);
  75267. };
  75268. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75269. this._fixedTimeStep = timeStep;
  75270. };
  75271. CannonJSPlugin.prototype.getTimeStep = function () {
  75272. return this._fixedTimeStep;
  75273. };
  75274. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75275. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75276. };
  75277. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75278. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75279. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75280. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75281. };
  75282. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75283. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75284. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75285. impostor.physicsBody.applyForce(impulse, worldPoint);
  75286. };
  75287. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75288. //parent-child relationship. Does this impostor has a parent impostor?
  75289. if (impostor.parent) {
  75290. if (impostor.physicsBody) {
  75291. this.removePhysicsBody(impostor);
  75292. //TODO is that needed?
  75293. impostor.forceUpdate();
  75294. }
  75295. return;
  75296. }
  75297. //should a new body be created for this impostor?
  75298. if (impostor.isBodyInitRequired()) {
  75299. var shape = this._createShape(impostor);
  75300. //unregister events, if body is being changed
  75301. var oldBody = impostor.physicsBody;
  75302. if (oldBody) {
  75303. this.removePhysicsBody(impostor);
  75304. }
  75305. //create the body and material
  75306. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75307. var bodyCreationObject = {
  75308. mass: impostor.getParam("mass"),
  75309. material: material
  75310. };
  75311. // A simple extend, in case native options were used.
  75312. var nativeOptions = impostor.getParam("nativeOptions");
  75313. for (var key in nativeOptions) {
  75314. if (nativeOptions.hasOwnProperty(key)) {
  75315. bodyCreationObject[key] = nativeOptions[key];
  75316. }
  75317. }
  75318. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75319. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75320. this.world.addEventListener("preStep", impostor.beforeStep);
  75321. this.world.addEventListener("postStep", impostor.afterStep);
  75322. impostor.physicsBody.addShape(shape);
  75323. this.world.add(impostor.physicsBody);
  75324. //try to keep the body moving in the right direction by taking old properties.
  75325. //Should be tested!
  75326. if (oldBody) {
  75327. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75328. impostor.physicsBody[param].copy(oldBody[param]);
  75329. });
  75330. }
  75331. this._processChildMeshes(impostor);
  75332. }
  75333. //now update the body's transformation
  75334. this._updatePhysicsBodyTransformation(impostor);
  75335. };
  75336. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75337. var _this = this;
  75338. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75339. var currentRotation = mainImpostor.object.rotationQuaternion;
  75340. if (meshChildren.length) {
  75341. var processMesh = function (localPosition, mesh) {
  75342. if (!currentRotation || !mesh.rotationQuaternion) {
  75343. return;
  75344. }
  75345. var childImpostor = mesh.getPhysicsImpostor();
  75346. if (childImpostor) {
  75347. var parent = childImpostor.parent;
  75348. if (parent !== mainImpostor) {
  75349. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75350. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75351. if (childImpostor.physicsBody) {
  75352. _this.removePhysicsBody(childImpostor);
  75353. childImpostor.physicsBody = null;
  75354. }
  75355. childImpostor.parent = mainImpostor;
  75356. childImpostor.resetUpdateFlags();
  75357. 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));
  75358. //Add the mass of the children.
  75359. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75360. }
  75361. }
  75362. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75363. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75364. };
  75365. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75366. }
  75367. };
  75368. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75369. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  75370. this.world.removeEventListener("preStep", impostor.beforeStep);
  75371. this.world.removeEventListener("postStep", impostor.afterStep);
  75372. this.world.remove(impostor.physicsBody);
  75373. };
  75374. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75375. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75376. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75377. if (!mainBody || !connectedBody) {
  75378. return;
  75379. }
  75380. var constraint;
  75381. var jointData = impostorJoint.joint.jointData;
  75382. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  75383. var constraintData = {
  75384. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  75385. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  75386. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  75387. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  75388. maxForce: jointData.nativeParams.maxForce,
  75389. collideConnected: !!jointData.collision
  75390. };
  75391. switch (impostorJoint.joint.type) {
  75392. case BABYLON.PhysicsJoint.HingeJoint:
  75393. case BABYLON.PhysicsJoint.Hinge2Joint:
  75394. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  75395. break;
  75396. case BABYLON.PhysicsJoint.DistanceJoint:
  75397. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  75398. break;
  75399. case BABYLON.PhysicsJoint.SpringJoint:
  75400. var springData = jointData;
  75401. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  75402. restLength: springData.length,
  75403. stiffness: springData.stiffness,
  75404. damping: springData.damping,
  75405. localAnchorA: constraintData.pivotA,
  75406. localAnchorB: constraintData.pivotB
  75407. });
  75408. break;
  75409. case BABYLON.PhysicsJoint.LockJoint:
  75410. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  75411. break;
  75412. case BABYLON.PhysicsJoint.PointToPointJoint:
  75413. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75414. default:
  75415. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  75416. break;
  75417. }
  75418. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  75419. constraint.collideConnected = !!jointData.collision;
  75420. impostorJoint.joint.physicsJoint = constraint;
  75421. //don't add spring as constraint, as it is not one.
  75422. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  75423. this.world.addConstraint(constraint);
  75424. }
  75425. else {
  75426. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  75427. constraint.applyForce();
  75428. });
  75429. }
  75430. };
  75431. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75432. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  75433. };
  75434. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  75435. var index;
  75436. var mat;
  75437. for (index = 0; index < this._physicsMaterials.length; index++) {
  75438. mat = this._physicsMaterials[index];
  75439. if (mat.friction === friction && mat.restitution === restitution) {
  75440. return mat;
  75441. }
  75442. }
  75443. var currentMat = new this.BJSCANNON.Material(name);
  75444. currentMat.friction = friction;
  75445. currentMat.restitution = restitution;
  75446. this._physicsMaterials.push(currentMat);
  75447. return currentMat;
  75448. };
  75449. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  75450. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  75451. };
  75452. CannonJSPlugin.prototype._createShape = function (impostor) {
  75453. var object = impostor.object;
  75454. var returnValue;
  75455. var extendSize = impostor.getObjectExtendSize();
  75456. switch (impostor.type) {
  75457. case BABYLON.PhysicsImpostor.SphereImpostor:
  75458. var radiusX = extendSize.x;
  75459. var radiusY = extendSize.y;
  75460. var radiusZ = extendSize.z;
  75461. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  75462. break;
  75463. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  75464. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75465. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  75466. break;
  75467. case BABYLON.PhysicsImpostor.BoxImpostor:
  75468. var box = extendSize.scale(0.5);
  75469. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  75470. break;
  75471. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75472. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  75473. returnValue = new this.BJSCANNON.Plane();
  75474. break;
  75475. case BABYLON.PhysicsImpostor.MeshImpostor:
  75476. // should transform the vertex data to world coordinates!!
  75477. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  75478. var rawFaces = object.getIndices ? object.getIndices() : [];
  75479. if (!rawVerts)
  75480. return;
  75481. // get only scale! so the object could transform correctly.
  75482. var oldPosition = object.position.clone();
  75483. var oldRotation = object.rotation && object.rotation.clone();
  75484. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  75485. object.position.copyFromFloats(0, 0, 0);
  75486. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75487. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75488. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75489. var transform = object.computeWorldMatrix(true);
  75490. // convert rawVerts to object space
  75491. var temp = new Array();
  75492. var index;
  75493. for (index = 0; index < rawVerts.length; index += 3) {
  75494. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  75495. }
  75496. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  75497. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  75498. //now set back the transformation!
  75499. object.position.copyFrom(oldPosition);
  75500. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  75501. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  75502. break;
  75503. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  75504. var oldPosition2 = object.position.clone();
  75505. var oldRotation2 = object.rotation && object.rotation.clone();
  75506. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  75507. object.position.copyFromFloats(0, 0, 0);
  75508. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  75509. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  75510. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  75511. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  75512. returnValue = this._createHeightmap(object);
  75513. object.position.copyFrom(oldPosition2);
  75514. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  75515. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  75516. object.computeWorldMatrix(true);
  75517. break;
  75518. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75519. returnValue = new this.BJSCANNON.Particle();
  75520. break;
  75521. }
  75522. return returnValue;
  75523. };
  75524. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  75525. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  75526. var transform = object.computeWorldMatrix(true);
  75527. // convert rawVerts to object space
  75528. var temp = new Array();
  75529. var index;
  75530. for (index = 0; index < pos.length; index += 3) {
  75531. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  75532. }
  75533. pos = temp;
  75534. var matrix = new Array();
  75535. //For now pointDepth will not be used and will be automatically calculated.
  75536. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  75537. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  75538. var boundingInfo = object.getBoundingInfo();
  75539. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  75540. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  75541. var elementSize = dim * 2 / arraySize;
  75542. for (var i = 0; i < pos.length; i = i + 3) {
  75543. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  75544. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  75545. var y = -pos[i + 2] + minY;
  75546. if (!matrix[x]) {
  75547. matrix[x] = [];
  75548. }
  75549. if (!matrix[x][z]) {
  75550. matrix[x][z] = y;
  75551. }
  75552. matrix[x][z] = Math.max(y, matrix[x][z]);
  75553. }
  75554. for (var x = 0; x <= arraySize; ++x) {
  75555. if (!matrix[x]) {
  75556. var loc = 1;
  75557. while (!matrix[(x + loc) % arraySize]) {
  75558. loc++;
  75559. }
  75560. matrix[x] = matrix[(x + loc) % arraySize].slice();
  75561. //console.log("missing x", x);
  75562. }
  75563. for (var z = 0; z <= arraySize; ++z) {
  75564. if (!matrix[x][z]) {
  75565. var loc = 1;
  75566. var newValue;
  75567. while (newValue === undefined) {
  75568. newValue = matrix[x][(z + loc++) % arraySize];
  75569. }
  75570. matrix[x][z] = newValue;
  75571. }
  75572. }
  75573. }
  75574. var shape = new this.BJSCANNON.Heightfield(matrix, {
  75575. elementSize: elementSize
  75576. });
  75577. //For future reference, needed for body transformation
  75578. shape.minY = minY;
  75579. return shape;
  75580. };
  75581. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  75582. var object = impostor.object;
  75583. //make sure it is updated...
  75584. object.computeWorldMatrix && object.computeWorldMatrix(true);
  75585. // The delta between the mesh position and the mesh bounding box center
  75586. var bInfo = object.getBoundingInfo();
  75587. if (!bInfo)
  75588. return;
  75589. var center = impostor.getObjectCenter();
  75590. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  75591. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  75592. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  75593. this._tmpPosition.copyFrom(center);
  75594. var quaternion = object.rotationQuaternion;
  75595. if (!quaternion) {
  75596. return;
  75597. }
  75598. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  75599. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  75600. //-90 DEG in X, precalculated
  75601. quaternion = quaternion.multiply(this._minus90X);
  75602. //Invert! (Precalculated, 90 deg in X)
  75603. //No need to clone. this will never change.
  75604. impostor.setDeltaRotation(this._plus90X);
  75605. }
  75606. //If it is a heightfield, if should be centered.
  75607. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  75608. var mesh = object;
  75609. var boundingInfo = mesh.getBoundingInfo();
  75610. //calculate the correct body position:
  75611. var rotationQuaternion = mesh.rotationQuaternion;
  75612. mesh.rotationQuaternion = this._tmpUnityRotation;
  75613. mesh.computeWorldMatrix(true);
  75614. //get original center with no rotation
  75615. var c = center.clone();
  75616. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  75617. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  75618. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  75619. mesh.setPreTransformMatrix(p);
  75620. mesh.computeWorldMatrix(true);
  75621. //calculate the translation
  75622. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  75623. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  75624. //add it inverted to the delta
  75625. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  75626. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  75627. //rotation is back
  75628. mesh.rotationQuaternion = rotationQuaternion;
  75629. mesh.setPreTransformMatrix(oldPivot);
  75630. mesh.computeWorldMatrix(true);
  75631. }
  75632. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  75633. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  75634. //this._tmpPosition.copyFrom(object.position);
  75635. }
  75636. impostor.setDeltaPosition(this._tmpDeltaPosition);
  75637. //Now update the impostor object
  75638. impostor.physicsBody.position.copy(this._tmpPosition);
  75639. impostor.physicsBody.quaternion.copy(quaternion);
  75640. };
  75641. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  75642. impostor.object.position.copyFrom(impostor.physicsBody.position);
  75643. if (impostor.object.rotationQuaternion) {
  75644. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  75645. }
  75646. };
  75647. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  75648. impostor.physicsBody.position.copy(newPosition);
  75649. impostor.physicsBody.quaternion.copy(newRotation);
  75650. };
  75651. CannonJSPlugin.prototype.isSupported = function () {
  75652. return this.BJSCANNON !== undefined;
  75653. };
  75654. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  75655. impostor.physicsBody.velocity.copy(velocity);
  75656. };
  75657. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  75658. impostor.physicsBody.angularVelocity.copy(velocity);
  75659. };
  75660. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  75661. var v = impostor.physicsBody.velocity;
  75662. if (!v) {
  75663. return null;
  75664. }
  75665. return new BABYLON.Vector3(v.x, v.y, v.z);
  75666. };
  75667. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  75668. var v = impostor.physicsBody.angularVelocity;
  75669. if (!v) {
  75670. return null;
  75671. }
  75672. return new BABYLON.Vector3(v.x, v.y, v.z);
  75673. };
  75674. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  75675. impostor.physicsBody.mass = mass;
  75676. impostor.physicsBody.updateMassProperties();
  75677. };
  75678. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  75679. return impostor.physicsBody.mass;
  75680. };
  75681. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  75682. return impostor.physicsBody.material.friction;
  75683. };
  75684. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  75685. impostor.physicsBody.material.friction = friction;
  75686. };
  75687. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  75688. return impostor.physicsBody.material.restitution;
  75689. };
  75690. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  75691. impostor.physicsBody.material.restitution = restitution;
  75692. };
  75693. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  75694. impostor.physicsBody.sleep();
  75695. };
  75696. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  75697. impostor.physicsBody.wakeUp();
  75698. };
  75699. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  75700. joint.physicsJoint.distance = maxDistance;
  75701. };
  75702. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75703. // if (!motorIndex) {
  75704. // joint.physicsJoint.enableMotor();
  75705. // }
  75706. // }
  75707. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  75708. // if (!motorIndex) {
  75709. // joint.physicsJoint.disableMotor();
  75710. // }
  75711. // }
  75712. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  75713. if (!motorIndex) {
  75714. joint.physicsJoint.enableMotor();
  75715. joint.physicsJoint.setMotorSpeed(speed);
  75716. if (maxForce) {
  75717. this.setLimit(joint, maxForce);
  75718. }
  75719. }
  75720. };
  75721. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  75722. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  75723. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  75724. };
  75725. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  75726. var body = impostor.physicsBody;
  75727. mesh.position.x = body.position.x;
  75728. mesh.position.y = body.position.y;
  75729. mesh.position.z = body.position.z;
  75730. if (mesh.rotationQuaternion) {
  75731. mesh.rotationQuaternion.x = body.quaternion.x;
  75732. mesh.rotationQuaternion.y = body.quaternion.y;
  75733. mesh.rotationQuaternion.z = body.quaternion.z;
  75734. mesh.rotationQuaternion.w = body.quaternion.w;
  75735. }
  75736. };
  75737. CannonJSPlugin.prototype.getRadius = function (impostor) {
  75738. var shape = impostor.physicsBody.shapes[0];
  75739. return shape.boundingSphereRadius;
  75740. };
  75741. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  75742. var shape = impostor.physicsBody.shapes[0];
  75743. result.x = shape.halfExtents.x * 2;
  75744. result.y = shape.halfExtents.y * 2;
  75745. result.z = shape.halfExtents.z * 2;
  75746. };
  75747. CannonJSPlugin.prototype.dispose = function () {
  75748. };
  75749. CannonJSPlugin.prototype._extendNamespace = function () {
  75750. //this will force cannon to execute at least one step when using interpolation
  75751. var step_tmp1 = new this.BJSCANNON.Vec3();
  75752. var Engine = this.BJSCANNON;
  75753. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  75754. maxSubSteps = maxSubSteps || 10;
  75755. timeSinceLastCalled = timeSinceLastCalled || 0;
  75756. if (timeSinceLastCalled === 0) {
  75757. this.internalStep(dt);
  75758. this.time += dt;
  75759. }
  75760. else {
  75761. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  75762. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  75763. var t0 = performance.now();
  75764. for (var i = 0; i !== internalSteps; i++) {
  75765. this.internalStep(dt);
  75766. if (performance.now() - t0 > dt * 1000) {
  75767. break;
  75768. }
  75769. }
  75770. this.time += timeSinceLastCalled;
  75771. var h = this.time % dt;
  75772. var h_div_dt = h / dt;
  75773. var interpvelo = step_tmp1;
  75774. var bodies = this.bodies;
  75775. for (var j = 0; j !== bodies.length; j++) {
  75776. var b = bodies[j];
  75777. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  75778. b.position.vsub(b.previousPosition, interpvelo);
  75779. interpvelo.scale(h_div_dt, interpvelo);
  75780. b.position.vadd(interpvelo, b.interpolatedPosition);
  75781. }
  75782. else {
  75783. b.interpolatedPosition.copy(b.position);
  75784. b.interpolatedQuaternion.copy(b.quaternion);
  75785. }
  75786. }
  75787. }
  75788. };
  75789. };
  75790. return CannonJSPlugin;
  75791. }());
  75792. BABYLON.CannonJSPlugin = CannonJSPlugin;
  75793. })(BABYLON || (BABYLON = {}));
  75794. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  75795. var BABYLON;
  75796. (function (BABYLON) {
  75797. var OimoJSPlugin = /** @class */ (function () {
  75798. function OimoJSPlugin(iterations) {
  75799. this.name = "OimoJSPlugin";
  75800. this._tmpImpostorsArray = [];
  75801. this._tmpPositionVector = BABYLON.Vector3.Zero();
  75802. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : ( true ? __webpack_require__(18) : undefined);
  75803. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  75804. this.world.worldscale(1);
  75805. this.world.clear();
  75806. //making sure no stats are calculated
  75807. this.world.isNoStat = true;
  75808. }
  75809. OimoJSPlugin.prototype.setGravity = function (gravity) {
  75810. this.world.gravity.copy(gravity);
  75811. };
  75812. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  75813. this.world.timeStep = timeStep;
  75814. };
  75815. OimoJSPlugin.prototype.getTimeStep = function () {
  75816. return this.world.timeStep;
  75817. };
  75818. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  75819. var _this = this;
  75820. impostors.forEach(function (impostor) {
  75821. impostor.beforeStep();
  75822. });
  75823. this.world.step();
  75824. impostors.forEach(function (impostor) {
  75825. impostor.afterStep();
  75826. //update the ordered impostors array
  75827. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  75828. });
  75829. //check for collisions
  75830. var contact = this.world.contacts;
  75831. while (contact !== null) {
  75832. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  75833. contact = contact.next;
  75834. continue;
  75835. }
  75836. //is this body colliding with any other? get the impostor
  75837. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  75838. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  75839. if (!mainImpostor || !collidingImpostor) {
  75840. contact = contact.next;
  75841. continue;
  75842. }
  75843. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  75844. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  75845. contact = contact.next;
  75846. }
  75847. };
  75848. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75849. var mass = impostor.physicsBody.massInfo.mass;
  75850. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  75851. };
  75852. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75853. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  75854. this.applyImpulse(impostor, force, contactPoint);
  75855. };
  75856. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75857. var _this = this;
  75858. //parent-child relationship. Does this impostor has a parent impostor?
  75859. if (impostor.parent) {
  75860. if (impostor.physicsBody) {
  75861. this.removePhysicsBody(impostor);
  75862. //TODO is that needed?
  75863. impostor.forceUpdate();
  75864. }
  75865. return;
  75866. }
  75867. if (impostor.isBodyInitRequired()) {
  75868. var bodyConfig = {
  75869. name: impostor.uniqueId,
  75870. //Oimo must have mass, also for static objects.
  75871. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  75872. size: [],
  75873. type: [],
  75874. pos: [],
  75875. rot: [],
  75876. move: impostor.getParam("mass") !== 0,
  75877. //Supporting older versions of Oimo
  75878. world: this.world
  75879. };
  75880. var impostors = [impostor];
  75881. var addToArray = function (parent) {
  75882. if (!parent.getChildMeshes)
  75883. return;
  75884. parent.getChildMeshes().forEach(function (m) {
  75885. if (m.physicsImpostor) {
  75886. impostors.push(m.physicsImpostor);
  75887. //m.physicsImpostor._init();
  75888. }
  75889. });
  75890. };
  75891. addToArray(impostor.object);
  75892. var checkWithEpsilon_1 = function (value) {
  75893. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  75894. };
  75895. impostors.forEach(function (i) {
  75896. if (!impostor.object.rotationQuaternion) {
  75897. return;
  75898. }
  75899. //get the correct bounding box
  75900. var oldQuaternion = i.object.rotationQuaternion;
  75901. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  75902. x: impostor.object.rotationQuaternion.x,
  75903. y: impostor.object.rotationQuaternion.y,
  75904. z: impostor.object.rotationQuaternion.z,
  75905. s: impostor.object.rotationQuaternion.w
  75906. });
  75907. var extendSize = i.getObjectExtendSize();
  75908. if (i === impostor) {
  75909. var center = impostor.getObjectCenter();
  75910. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  75911. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  75912. //Can also use Array.prototype.push.apply
  75913. bodyConfig.pos.push(center.x);
  75914. bodyConfig.pos.push(center.y);
  75915. bodyConfig.pos.push(center.z);
  75916. //tmp solution
  75917. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75918. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75919. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  75920. }
  75921. else {
  75922. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  75923. bodyConfig.pos.push(localPosition.x);
  75924. bodyConfig.pos.push(localPosition.y);
  75925. bodyConfig.pos.push(localPosition.z);
  75926. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  75927. bodyConfig.rot.push(0);
  75928. bodyConfig.rot.push(0);
  75929. bodyConfig.rot.push(0);
  75930. }
  75931. // register mesh
  75932. switch (i.type) {
  75933. case BABYLON.PhysicsImpostor.ParticleImpostor:
  75934. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  75935. case BABYLON.PhysicsImpostor.SphereImpostor:
  75936. var radiusX = extendSize.x;
  75937. var radiusY = extendSize.y;
  75938. var radiusZ = extendSize.z;
  75939. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  75940. bodyConfig.type.push('sphere');
  75941. //due to the way oimo works with compounds, add 3 times
  75942. bodyConfig.size.push(size);
  75943. bodyConfig.size.push(size);
  75944. bodyConfig.size.push(size);
  75945. break;
  75946. case BABYLON.PhysicsImpostor.CylinderImpostor:
  75947. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  75948. var sizeY = checkWithEpsilon_1(extendSize.y);
  75949. bodyConfig.type.push('cylinder');
  75950. bodyConfig.size.push(sizeX);
  75951. bodyConfig.size.push(sizeY);
  75952. //due to the way oimo works with compounds, add one more value.
  75953. bodyConfig.size.push(sizeY);
  75954. break;
  75955. case BABYLON.PhysicsImpostor.PlaneImpostor:
  75956. case BABYLON.PhysicsImpostor.BoxImpostor:
  75957. default:
  75958. var sizeX = checkWithEpsilon_1(extendSize.x);
  75959. var sizeY = checkWithEpsilon_1(extendSize.y);
  75960. var sizeZ = checkWithEpsilon_1(extendSize.z);
  75961. bodyConfig.type.push('box');
  75962. bodyConfig.size.push(sizeX);
  75963. bodyConfig.size.push(sizeY);
  75964. bodyConfig.size.push(sizeZ);
  75965. break;
  75966. }
  75967. //actually not needed, but hey...
  75968. i.object.rotationQuaternion = oldQuaternion;
  75969. });
  75970. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  75971. }
  75972. else {
  75973. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  75974. }
  75975. impostor.setDeltaPosition(this._tmpPositionVector);
  75976. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  75977. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  75978. };
  75979. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75980. //impostor.physicsBody.dispose();
  75981. //Same as : (older oimo versions)
  75982. this.world.removeRigidBody(impostor.physicsBody);
  75983. };
  75984. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75985. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75986. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75987. if (!mainBody || !connectedBody) {
  75988. return;
  75989. }
  75990. var jointData = impostorJoint.joint.jointData;
  75991. var options = jointData.nativeParams || {};
  75992. var type;
  75993. var nativeJointData = {
  75994. body1: mainBody,
  75995. body2: connectedBody,
  75996. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  75997. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  75998. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  75999. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76000. min: options.min,
  76001. max: options.max,
  76002. collision: options.collision || jointData.collision,
  76003. spring: options.spring,
  76004. //supporting older version of Oimo
  76005. world: this.world
  76006. };
  76007. switch (impostorJoint.joint.type) {
  76008. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76009. type = "jointBall";
  76010. break;
  76011. case BABYLON.PhysicsJoint.SpringJoint:
  76012. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76013. var springData = jointData;
  76014. nativeJointData.min = springData.length || nativeJointData.min;
  76015. //Max should also be set, just make sure it is at least min
  76016. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76017. case BABYLON.PhysicsJoint.DistanceJoint:
  76018. type = "jointDistance";
  76019. nativeJointData.max = jointData.maxDistance;
  76020. break;
  76021. case BABYLON.PhysicsJoint.PrismaticJoint:
  76022. type = "jointPrisme";
  76023. break;
  76024. case BABYLON.PhysicsJoint.SliderJoint:
  76025. type = "jointSlide";
  76026. break;
  76027. case BABYLON.PhysicsJoint.WheelJoint:
  76028. type = "jointWheel";
  76029. break;
  76030. case BABYLON.PhysicsJoint.HingeJoint:
  76031. default:
  76032. type = "jointHinge";
  76033. break;
  76034. }
  76035. nativeJointData.type = type;
  76036. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76037. };
  76038. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76039. //Bug in Oimo prevents us from disposing a joint in the playground
  76040. //joint.joint.physicsJoint.dispose();
  76041. //So we will bruteforce it!
  76042. try {
  76043. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76044. }
  76045. catch (e) {
  76046. BABYLON.Tools.Warn(e);
  76047. }
  76048. };
  76049. OimoJSPlugin.prototype.isSupported = function () {
  76050. return this.BJSOIMO !== undefined;
  76051. };
  76052. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76053. if (!impostor.physicsBody.sleeping) {
  76054. //TODO check that
  76055. if (impostor.physicsBody.shapes.next) {
  76056. var parentShape = this._getLastShape(impostor.physicsBody);
  76057. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76058. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76059. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76060. }
  76061. else {
  76062. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76063. }
  76064. if (impostor.object.rotationQuaternion) {
  76065. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76066. impostor.object.rotationQuaternion.normalize();
  76067. }
  76068. }
  76069. };
  76070. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76071. var body = impostor.physicsBody;
  76072. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76073. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76074. body.syncShapes();
  76075. body.awake();
  76076. };
  76077. OimoJSPlugin.prototype._getLastShape = function (body) {
  76078. var lastShape = body.shapes;
  76079. while (lastShape.next) {
  76080. lastShape = lastShape.next;
  76081. }
  76082. return lastShape;
  76083. };
  76084. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76085. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76086. };
  76087. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76088. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76089. };
  76090. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76091. var v = impostor.physicsBody.linearVelocity;
  76092. if (!v) {
  76093. return null;
  76094. }
  76095. return new BABYLON.Vector3(v.x, v.y, v.z);
  76096. };
  76097. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76098. var v = impostor.physicsBody.angularVelocity;
  76099. if (!v) {
  76100. return null;
  76101. }
  76102. return new BABYLON.Vector3(v.x, v.y, v.z);
  76103. };
  76104. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76105. var staticBody = mass === 0;
  76106. //this will actually set the body's density and not its mass.
  76107. //But this is how oimo treats the mass variable.
  76108. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76109. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76110. };
  76111. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76112. return impostor.physicsBody.shapes.density;
  76113. };
  76114. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76115. return impostor.physicsBody.shapes.friction;
  76116. };
  76117. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76118. impostor.physicsBody.shapes.friction = friction;
  76119. };
  76120. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76121. return impostor.physicsBody.shapes.restitution;
  76122. };
  76123. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76124. impostor.physicsBody.shapes.restitution = restitution;
  76125. };
  76126. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76127. impostor.physicsBody.sleep();
  76128. };
  76129. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76130. impostor.physicsBody.awake();
  76131. };
  76132. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76133. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76134. if (minDistance !== void 0) {
  76135. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76136. }
  76137. };
  76138. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76139. //TODO separate rotational and transational motors.
  76140. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76141. if (motor) {
  76142. motor.setMotor(speed, maxForce);
  76143. }
  76144. };
  76145. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76146. //TODO separate rotational and transational motors.
  76147. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76148. if (motor) {
  76149. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76150. }
  76151. };
  76152. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76153. var body = impostor.physicsBody;
  76154. mesh.position.x = body.position.x;
  76155. mesh.position.y = body.position.y;
  76156. mesh.position.z = body.position.z;
  76157. if (mesh.rotationQuaternion) {
  76158. mesh.rotationQuaternion.x = body.orientation.x;
  76159. mesh.rotationQuaternion.y = body.orientation.y;
  76160. mesh.rotationQuaternion.z = body.orientation.z;
  76161. mesh.rotationQuaternion.w = body.orientation.s;
  76162. }
  76163. };
  76164. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76165. return impostor.physicsBody.shapes.radius;
  76166. };
  76167. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76168. var shape = impostor.physicsBody.shapes;
  76169. result.x = shape.halfWidth * 2;
  76170. result.y = shape.halfHeight * 2;
  76171. result.z = shape.halfDepth * 2;
  76172. };
  76173. OimoJSPlugin.prototype.dispose = function () {
  76174. this.world.clear();
  76175. };
  76176. return OimoJSPlugin;
  76177. }());
  76178. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76179. })(BABYLON || (BABYLON = {}));
  76180. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76181. var BABYLON;
  76182. (function (BABYLON) {
  76183. /*
  76184. * Based on jsTGALoader - Javascript loader for TGA file
  76185. * By Vincent Thibault
  76186. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76187. */
  76188. var TGATools = /** @class */ (function () {
  76189. function TGATools() {
  76190. }
  76191. TGATools.GetTGAHeader = function (data) {
  76192. var offset = 0;
  76193. var header = {
  76194. id_length: data[offset++],
  76195. colormap_type: data[offset++],
  76196. image_type: data[offset++],
  76197. colormap_index: data[offset++] | data[offset++] << 8,
  76198. colormap_length: data[offset++] | data[offset++] << 8,
  76199. colormap_size: data[offset++],
  76200. origin: [
  76201. data[offset++] | data[offset++] << 8,
  76202. data[offset++] | data[offset++] << 8
  76203. ],
  76204. width: data[offset++] | data[offset++] << 8,
  76205. height: data[offset++] | data[offset++] << 8,
  76206. pixel_size: data[offset++],
  76207. flags: data[offset++]
  76208. };
  76209. return header;
  76210. };
  76211. TGATools.UploadContent = function (gl, data) {
  76212. // Not enough data to contain header ?
  76213. if (data.length < 19) {
  76214. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76215. return;
  76216. }
  76217. // Read Header
  76218. var offset = 18;
  76219. var header = TGATools.GetTGAHeader(data);
  76220. // Assume it's a valid Targa file.
  76221. if (header.id_length + offset > data.length) {
  76222. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76223. return;
  76224. }
  76225. // Skip not needed data
  76226. offset += header.id_length;
  76227. var use_rle = false;
  76228. var use_pal = false;
  76229. var use_grey = false;
  76230. // Get some informations.
  76231. switch (header.image_type) {
  76232. case TGATools._TYPE_RLE_INDEXED:
  76233. use_rle = true;
  76234. case TGATools._TYPE_INDEXED:
  76235. use_pal = true;
  76236. break;
  76237. case TGATools._TYPE_RLE_RGB:
  76238. use_rle = true;
  76239. case TGATools._TYPE_RGB:
  76240. // use_rgb = true;
  76241. break;
  76242. case TGATools._TYPE_RLE_GREY:
  76243. use_rle = true;
  76244. case TGATools._TYPE_GREY:
  76245. use_grey = true;
  76246. break;
  76247. }
  76248. var pixel_data;
  76249. // var numAlphaBits = header.flags & 0xf;
  76250. var pixel_size = header.pixel_size >> 3;
  76251. var pixel_total = header.width * header.height * pixel_size;
  76252. // Read palettes
  76253. var palettes;
  76254. if (use_pal) {
  76255. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76256. }
  76257. // Read LRE
  76258. if (use_rle) {
  76259. pixel_data = new Uint8Array(pixel_total);
  76260. var c, count, i;
  76261. var localOffset = 0;
  76262. var pixels = new Uint8Array(pixel_size);
  76263. while (offset < pixel_total && localOffset < pixel_total) {
  76264. c = data[offset++];
  76265. count = (c & 0x7f) + 1;
  76266. // RLE pixels
  76267. if (c & 0x80) {
  76268. // Bind pixel tmp array
  76269. for (i = 0; i < pixel_size; ++i) {
  76270. pixels[i] = data[offset++];
  76271. }
  76272. // Copy pixel array
  76273. for (i = 0; i < count; ++i) {
  76274. pixel_data.set(pixels, localOffset + i * pixel_size);
  76275. }
  76276. localOffset += pixel_size * count;
  76277. }
  76278. else {
  76279. count *= pixel_size;
  76280. for (i = 0; i < count; ++i) {
  76281. pixel_data[localOffset + i] = data[offset++];
  76282. }
  76283. localOffset += count;
  76284. }
  76285. }
  76286. }
  76287. else {
  76288. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76289. }
  76290. // Load to texture
  76291. var x_start, y_start, x_step, y_step, y_end, x_end;
  76292. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76293. default:
  76294. case TGATools._ORIGIN_UL:
  76295. x_start = 0;
  76296. x_step = 1;
  76297. x_end = header.width;
  76298. y_start = 0;
  76299. y_step = 1;
  76300. y_end = header.height;
  76301. break;
  76302. case TGATools._ORIGIN_BL:
  76303. x_start = 0;
  76304. x_step = 1;
  76305. x_end = header.width;
  76306. y_start = header.height - 1;
  76307. y_step = -1;
  76308. y_end = -1;
  76309. break;
  76310. case TGATools._ORIGIN_UR:
  76311. x_start = header.width - 1;
  76312. x_step = -1;
  76313. x_end = -1;
  76314. y_start = 0;
  76315. y_step = 1;
  76316. y_end = header.height;
  76317. break;
  76318. case TGATools._ORIGIN_BR:
  76319. x_start = header.width - 1;
  76320. x_step = -1;
  76321. x_end = -1;
  76322. y_start = header.height - 1;
  76323. y_step = -1;
  76324. y_end = -1;
  76325. break;
  76326. }
  76327. // Load the specify method
  76328. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76329. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76330. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76331. };
  76332. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76333. var image = pixel_data, colormap = palettes;
  76334. var width = header.width, height = header.height;
  76335. var color, i = 0, x, y;
  76336. var imageData = new Uint8Array(width * height * 4);
  76337. for (y = y_start; y !== y_end; y += y_step) {
  76338. for (x = x_start; x !== x_end; x += x_step, i++) {
  76339. color = image[i];
  76340. imageData[(x + width * y) * 4 + 3] = 255;
  76341. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76342. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76343. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76344. }
  76345. }
  76346. return imageData;
  76347. };
  76348. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76349. var image = pixel_data;
  76350. var width = header.width, height = header.height;
  76351. var color, i = 0, x, y;
  76352. var imageData = new Uint8Array(width * height * 4);
  76353. for (y = y_start; y !== y_end; y += y_step) {
  76354. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76355. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76356. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76357. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76358. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76359. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76360. }
  76361. }
  76362. return imageData;
  76363. };
  76364. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76365. var image = pixel_data;
  76366. var width = header.width, height = header.height;
  76367. var i = 0, x, y;
  76368. var imageData = new Uint8Array(width * height * 4);
  76369. for (y = y_start; y !== y_end; y += y_step) {
  76370. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  76371. imageData[(x + width * y) * 4 + 3] = 255;
  76372. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76373. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76374. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76375. }
  76376. }
  76377. return imageData;
  76378. };
  76379. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76380. var image = pixel_data;
  76381. var width = header.width, height = header.height;
  76382. var i = 0, x, y;
  76383. var imageData = new Uint8Array(width * height * 4);
  76384. for (y = y_start; y !== y_end; y += y_step) {
  76385. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  76386. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76387. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76388. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76389. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  76390. }
  76391. }
  76392. return imageData;
  76393. };
  76394. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76395. var image = pixel_data;
  76396. var width = header.width, height = header.height;
  76397. var color, i = 0, x, y;
  76398. var imageData = new Uint8Array(width * height * 4);
  76399. for (y = y_start; y !== y_end; y += y_step) {
  76400. for (x = x_start; x !== x_end; x += x_step, i++) {
  76401. color = image[i];
  76402. imageData[(x + width * y) * 4 + 0] = color;
  76403. imageData[(x + width * y) * 4 + 1] = color;
  76404. imageData[(x + width * y) * 4 + 2] = color;
  76405. imageData[(x + width * y) * 4 + 3] = 255;
  76406. }
  76407. }
  76408. return imageData;
  76409. };
  76410. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76411. var image = pixel_data;
  76412. var width = header.width, height = header.height;
  76413. var i = 0, x, y;
  76414. var imageData = new Uint8Array(width * height * 4);
  76415. for (y = y_start; y !== y_end; y += y_step) {
  76416. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76417. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  76418. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  76419. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76420. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  76421. }
  76422. }
  76423. return imageData;
  76424. };
  76425. //private static _TYPE_NO_DATA = 0;
  76426. TGATools._TYPE_INDEXED = 1;
  76427. TGATools._TYPE_RGB = 2;
  76428. TGATools._TYPE_GREY = 3;
  76429. TGATools._TYPE_RLE_INDEXED = 9;
  76430. TGATools._TYPE_RLE_RGB = 10;
  76431. TGATools._TYPE_RLE_GREY = 11;
  76432. TGATools._ORIGIN_MASK = 0x30;
  76433. TGATools._ORIGIN_SHIFT = 0x04;
  76434. TGATools._ORIGIN_BL = 0x00;
  76435. TGATools._ORIGIN_BR = 0x01;
  76436. TGATools._ORIGIN_UL = 0x02;
  76437. TGATools._ORIGIN_UR = 0x03;
  76438. return TGATools;
  76439. }());
  76440. BABYLON.TGATools = TGATools;
  76441. })(BABYLON || (BABYLON = {}));
  76442. //# sourceMappingURL=babylon.tga.js.map
  76443. var BABYLON;
  76444. (function (BABYLON) {
  76445. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  76446. // All values and structures referenced from:
  76447. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  76448. var DDS_MAGIC = 0x20534444;
  76449. var
  76450. //DDSD_CAPS = 0x1,
  76451. //DDSD_HEIGHT = 0x2,
  76452. //DDSD_WIDTH = 0x4,
  76453. //DDSD_PITCH = 0x8,
  76454. //DDSD_PIXELFORMAT = 0x1000,
  76455. DDSD_MIPMAPCOUNT = 0x20000;
  76456. //DDSD_LINEARSIZE = 0x80000,
  76457. //DDSD_DEPTH = 0x800000;
  76458. // var DDSCAPS_COMPLEX = 0x8,
  76459. // DDSCAPS_MIPMAP = 0x400000,
  76460. // DDSCAPS_TEXTURE = 0x1000;
  76461. var DDSCAPS2_CUBEMAP = 0x200;
  76462. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  76463. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  76464. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  76465. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  76466. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  76467. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  76468. // DDSCAPS2_VOLUME = 0x200000;
  76469. var
  76470. //DDPF_ALPHAPIXELS = 0x1,
  76471. //DDPF_ALPHA = 0x2,
  76472. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  76473. //DDPF_YUV = 0x200,
  76474. DDPF_LUMINANCE = 0x20000;
  76475. function FourCCToInt32(value) {
  76476. return value.charCodeAt(0) +
  76477. (value.charCodeAt(1) << 8) +
  76478. (value.charCodeAt(2) << 16) +
  76479. (value.charCodeAt(3) << 24);
  76480. }
  76481. function Int32ToFourCC(value) {
  76482. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  76483. }
  76484. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  76485. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  76486. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  76487. var FOURCC_DX10 = FourCCToInt32("DX10");
  76488. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  76489. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  76490. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  76491. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  76492. var headerLengthInt = 31; // The header length in 32 bit ints
  76493. // Offsets into the header array
  76494. var off_magic = 0;
  76495. var off_size = 1;
  76496. var off_flags = 2;
  76497. var off_height = 3;
  76498. var off_width = 4;
  76499. var off_mipmapCount = 7;
  76500. var off_pfFlags = 20;
  76501. var off_pfFourCC = 21;
  76502. var off_RGBbpp = 22;
  76503. var off_RMask = 23;
  76504. var off_GMask = 24;
  76505. var off_BMask = 25;
  76506. var off_AMask = 26;
  76507. // var off_caps1 = 27;
  76508. var off_caps2 = 28;
  76509. // var off_caps3 = 29;
  76510. // var off_caps4 = 30;
  76511. var off_dxgiFormat = 32;
  76512. ;
  76513. var DDSTools = /** @class */ (function () {
  76514. function DDSTools() {
  76515. }
  76516. DDSTools.GetDDSInfo = function (arrayBuffer) {
  76517. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76518. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  76519. var mipmapCount = 1;
  76520. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  76521. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76522. }
  76523. var fourCC = header[off_pfFourCC];
  76524. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  76525. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76526. switch (fourCC) {
  76527. case FOURCC_D3DFMT_R16G16B16A16F:
  76528. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76529. break;
  76530. case FOURCC_D3DFMT_R32G32B32A32F:
  76531. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76532. break;
  76533. case FOURCC_DX10:
  76534. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  76535. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76536. break;
  76537. }
  76538. }
  76539. return {
  76540. width: header[off_width],
  76541. height: header[off_height],
  76542. mipmapCount: mipmapCount,
  76543. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  76544. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  76545. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  76546. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  76547. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  76548. dxgiFormat: dxgiFormat,
  76549. textureType: textureType
  76550. };
  76551. };
  76552. DDSTools._ToHalfFloat = function (value) {
  76553. if (!DDSTools._FloatView) {
  76554. DDSTools._FloatView = new Float32Array(1);
  76555. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  76556. }
  76557. DDSTools._FloatView[0] = value;
  76558. var x = DDSTools._Int32View[0];
  76559. var bits = (x >> 16) & 0x8000; /* Get the sign */
  76560. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  76561. var e = (x >> 23) & 0xff; /* Using int is faster here */
  76562. /* If zero, or denormal, or exponent underflows too much for a denormal
  76563. * half, return signed zero. */
  76564. if (e < 103) {
  76565. return bits;
  76566. }
  76567. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  76568. if (e > 142) {
  76569. bits |= 0x7c00;
  76570. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  76571. * not Inf, so make sure we set one mantissa bit too. */
  76572. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  76573. return bits;
  76574. }
  76575. /* If exponent underflows but not too much, return a denormal */
  76576. if (e < 113) {
  76577. m |= 0x0800;
  76578. /* Extra rounding may overflow and set mantissa to 0 and exponent
  76579. * to 1, which is OK. */
  76580. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  76581. return bits;
  76582. }
  76583. bits |= ((e - 112) << 10) | (m >> 1);
  76584. bits += m & 1;
  76585. return bits;
  76586. };
  76587. DDSTools._FromHalfFloat = function (value) {
  76588. var s = (value & 0x8000) >> 15;
  76589. var e = (value & 0x7C00) >> 10;
  76590. var f = value & 0x03FF;
  76591. if (e === 0) {
  76592. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  76593. }
  76594. else if (e == 0x1F) {
  76595. return f ? NaN : ((s ? -1 : 1) * Infinity);
  76596. }
  76597. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  76598. };
  76599. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76600. var destArray = new Float32Array(dataLength);
  76601. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76602. var index = 0;
  76603. for (var y = 0; y < height; y++) {
  76604. for (var x = 0; x < width; x++) {
  76605. var srcPos = (x + y * width) * 4;
  76606. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  76607. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  76608. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  76609. if (DDSTools.StoreLODInAlphaChannel) {
  76610. destArray[index + 3] = lod;
  76611. }
  76612. else {
  76613. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  76614. }
  76615. index += 4;
  76616. }
  76617. }
  76618. return destArray;
  76619. };
  76620. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76621. if (DDSTools.StoreLODInAlphaChannel) {
  76622. var destArray = new Uint16Array(dataLength);
  76623. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76624. var index = 0;
  76625. for (var y = 0; y < height; y++) {
  76626. for (var x = 0; x < width; x++) {
  76627. var srcPos = (x + y * width) * 4;
  76628. destArray[index] = srcData[srcPos];
  76629. destArray[index + 1] = srcData[srcPos + 1];
  76630. destArray[index + 2] = srcData[srcPos + 2];
  76631. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  76632. index += 4;
  76633. }
  76634. }
  76635. return destArray;
  76636. }
  76637. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  76638. };
  76639. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76640. if (DDSTools.StoreLODInAlphaChannel) {
  76641. var destArray = new Float32Array(dataLength);
  76642. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76643. var index = 0;
  76644. for (var y = 0; y < height; y++) {
  76645. for (var x = 0; x < width; x++) {
  76646. var srcPos = (x + y * width) * 4;
  76647. destArray[index] = srcData[srcPos];
  76648. destArray[index + 1] = srcData[srcPos + 1];
  76649. destArray[index + 2] = srcData[srcPos + 2];
  76650. destArray[index + 3] = lod;
  76651. index += 4;
  76652. }
  76653. }
  76654. return destArray;
  76655. }
  76656. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  76657. };
  76658. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76659. var destArray = new Uint8Array(dataLength);
  76660. var srcData = new Float32Array(arrayBuffer, dataOffset);
  76661. var index = 0;
  76662. for (var y = 0; y < height; y++) {
  76663. for (var x = 0; x < width; x++) {
  76664. var srcPos = (x + y * width) * 4;
  76665. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  76666. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  76667. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  76668. if (DDSTools.StoreLODInAlphaChannel) {
  76669. destArray[index + 3] = lod;
  76670. }
  76671. else {
  76672. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  76673. }
  76674. index += 4;
  76675. }
  76676. }
  76677. return destArray;
  76678. };
  76679. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  76680. var destArray = new Uint8Array(dataLength);
  76681. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  76682. var index = 0;
  76683. for (var y = 0; y < height; y++) {
  76684. for (var x = 0; x < width; x++) {
  76685. var srcPos = (x + y * width) * 4;
  76686. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  76687. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  76688. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  76689. if (DDSTools.StoreLODInAlphaChannel) {
  76690. destArray[index + 3] = lod;
  76691. }
  76692. else {
  76693. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  76694. }
  76695. index += 4;
  76696. }
  76697. }
  76698. return destArray;
  76699. };
  76700. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  76701. var byteArray = new Uint8Array(dataLength);
  76702. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76703. var index = 0;
  76704. for (var y = 0; y < height; y++) {
  76705. for (var x = 0; x < width; x++) {
  76706. var srcPos = (x + y * width) * 4;
  76707. byteArray[index] = srcData[srcPos + rOffset];
  76708. byteArray[index + 1] = srcData[srcPos + gOffset];
  76709. byteArray[index + 2] = srcData[srcPos + bOffset];
  76710. byteArray[index + 3] = srcData[srcPos + aOffset];
  76711. index += 4;
  76712. }
  76713. }
  76714. return byteArray;
  76715. };
  76716. DDSTools._ExtractLongWordOrder = function (value) {
  76717. if (value === 0 || value === 255 || value === -16777216) {
  76718. return 0;
  76719. }
  76720. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  76721. };
  76722. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  76723. var byteArray = new Uint8Array(dataLength);
  76724. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76725. var index = 0;
  76726. for (var y = 0; y < height; y++) {
  76727. for (var x = 0; x < width; x++) {
  76728. var srcPos = (x + y * width) * 3;
  76729. byteArray[index] = srcData[srcPos + rOffset];
  76730. byteArray[index + 1] = srcData[srcPos + gOffset];
  76731. byteArray[index + 2] = srcData[srcPos + bOffset];
  76732. index += 3;
  76733. }
  76734. }
  76735. return byteArray;
  76736. };
  76737. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  76738. var byteArray = new Uint8Array(dataLength);
  76739. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  76740. var index = 0;
  76741. for (var y = 0; y < height; y++) {
  76742. for (var x = 0; x < width; x++) {
  76743. var srcPos = (x + y * width);
  76744. byteArray[index] = srcData[srcPos];
  76745. index++;
  76746. }
  76747. }
  76748. return byteArray;
  76749. };
  76750. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  76751. if (lodIndex === void 0) { lodIndex = -1; }
  76752. var ext = engine.getCaps().s3tc;
  76753. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  76754. var fourCC, width, height, dataLength = 0, dataOffset;
  76755. var byteArray, mipmapCount, mip;
  76756. var internalFormat = 0;
  76757. var format = 0;
  76758. var blockBytes = 1;
  76759. if (header[off_magic] !== DDS_MAGIC) {
  76760. BABYLON.Tools.Error("Invalid magic number in DDS header");
  76761. return;
  76762. }
  76763. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  76764. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  76765. return;
  76766. }
  76767. if (info.isCompressed && !ext) {
  76768. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  76769. return;
  76770. }
  76771. var bpp = header[off_RGBbpp];
  76772. dataOffset = header[off_size] + 4;
  76773. var computeFormats = false;
  76774. if (info.isFourCC) {
  76775. fourCC = header[off_pfFourCC];
  76776. switch (fourCC) {
  76777. case FOURCC_DXT1:
  76778. blockBytes = 8;
  76779. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  76780. break;
  76781. case FOURCC_DXT3:
  76782. blockBytes = 16;
  76783. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  76784. break;
  76785. case FOURCC_DXT5:
  76786. blockBytes = 16;
  76787. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  76788. break;
  76789. case FOURCC_D3DFMT_R16G16B16A16F:
  76790. computeFormats = true;
  76791. break;
  76792. case FOURCC_D3DFMT_R32G32B32A32F:
  76793. computeFormats = true;
  76794. break;
  76795. case FOURCC_DX10:
  76796. // There is an additionnal header so dataOffset need to be changed
  76797. dataOffset += 5 * 4; // 5 uints
  76798. var supported = false;
  76799. switch (info.dxgiFormat) {
  76800. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  76801. computeFormats = true;
  76802. supported = true;
  76803. break;
  76804. case DXGI_FORMAT_B8G8R8X8_UNORM:
  76805. info.isRGB = true;
  76806. info.isFourCC = false;
  76807. bpp = 32;
  76808. supported = true;
  76809. break;
  76810. }
  76811. if (supported) {
  76812. break;
  76813. }
  76814. default:
  76815. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  76816. return;
  76817. }
  76818. }
  76819. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  76820. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  76821. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  76822. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  76823. if (computeFormats) {
  76824. format = engine._getWebGLTextureType(info.textureType);
  76825. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76826. }
  76827. mipmapCount = 1;
  76828. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  76829. mipmapCount = Math.max(1, header[off_mipmapCount]);
  76830. }
  76831. for (var face = 0; face < faces; face++) {
  76832. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  76833. width = header[off_width];
  76834. height = header[off_height];
  76835. for (mip = 0; mip < mipmapCount; ++mip) {
  76836. if (lodIndex === -1 || lodIndex === mip) {
  76837. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  76838. var i = (lodIndex === -1) ? mip : 0;
  76839. if (!info.isCompressed && info.isFourCC) {
  76840. dataLength = width * height * 4;
  76841. var floatArray = null;
  76842. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  76843. if (bpp === 128) {
  76844. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76845. }
  76846. else if (bpp === 64) {
  76847. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76848. }
  76849. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76850. format = engine._getWebGLTextureType(info.textureType);
  76851. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76852. }
  76853. else {
  76854. if (bpp === 128) {
  76855. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76856. }
  76857. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  76858. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76859. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76860. format = engine._getWebGLTextureType(info.textureType);
  76861. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  76862. }
  76863. else {
  76864. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  76865. }
  76866. }
  76867. if (floatArray) {
  76868. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  76869. }
  76870. }
  76871. else if (info.isRGB) {
  76872. if (bpp === 24) {
  76873. dataLength = width * height * 3;
  76874. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  76875. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  76876. }
  76877. else {
  76878. dataLength = width * height * 4;
  76879. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  76880. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  76881. }
  76882. }
  76883. else if (info.isLuminance) {
  76884. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  76885. var unpaddedRowSize = width;
  76886. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  76887. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  76888. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  76889. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  76890. }
  76891. else {
  76892. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  76893. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  76894. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  76895. }
  76896. }
  76897. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  76898. width *= 0.5;
  76899. height *= 0.5;
  76900. width = Math.max(1.0, width);
  76901. height = Math.max(1.0, height);
  76902. }
  76903. if (currentFace !== undefined) {
  76904. // Loading a single face
  76905. break;
  76906. }
  76907. }
  76908. };
  76909. DDSTools.StoreLODInAlphaChannel = false;
  76910. return DDSTools;
  76911. }());
  76912. BABYLON.DDSTools = DDSTools;
  76913. })(BABYLON || (BABYLON = {}));
  76914. //# sourceMappingURL=babylon.dds.js.map
  76915. var BABYLON;
  76916. (function (BABYLON) {
  76917. /**
  76918. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  76919. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  76920. */
  76921. var KhronosTextureContainer = /** @class */ (function () {
  76922. /**
  76923. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  76924. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  76925. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  76926. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  76927. */
  76928. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  76929. this.arrayBuffer = arrayBuffer;
  76930. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  76931. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  76932. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  76933. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  76934. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  76935. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  76936. BABYLON.Tools.Error("texture missing KTX identifier");
  76937. return;
  76938. }
  76939. // load the reset of the header in native 32 bit int
  76940. var header = new Int32Array(this.arrayBuffer, 12, 13);
  76941. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  76942. var oppositeEndianess = header[0] === 0x01020304;
  76943. // read all the header elements in order they exist in the file, without modification (sans endainness)
  76944. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  76945. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  76946. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  76947. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  76948. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  76949. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  76950. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  76951. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  76952. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  76953. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  76954. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  76955. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  76956. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  76957. if (this.glType !== 0) {
  76958. BABYLON.Tools.Error("only compressed formats currently supported");
  76959. return;
  76960. }
  76961. else {
  76962. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  76963. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  76964. }
  76965. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  76966. BABYLON.Tools.Error("only 2D textures currently supported");
  76967. return;
  76968. }
  76969. if (this.numberOfArrayElements !== 0) {
  76970. BABYLON.Tools.Error("texture arrays not currently supported");
  76971. return;
  76972. }
  76973. if (this.numberOfFaces !== facesExpected) {
  76974. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  76975. return;
  76976. }
  76977. // we now have a completely validated file, so could use existence of loadType as success
  76978. // would need to make this more elaborate & adjust checks above to support more than one load type
  76979. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  76980. }
  76981. // not as fast hardware based, but will probably never need to use
  76982. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  76983. return ((val & 0xFF) << 24)
  76984. | ((val & 0xFF00) << 8)
  76985. | ((val >> 8) & 0xFF00)
  76986. | ((val >> 24) & 0xFF);
  76987. };
  76988. /**
  76989. * It is assumed that the texture has already been created & is currently bound
  76990. */
  76991. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  76992. switch (this.loadType) {
  76993. case KhronosTextureContainer.COMPRESSED_2D:
  76994. this._upload2DCompressedLevels(gl, loadMipmaps);
  76995. break;
  76996. case KhronosTextureContainer.TEX_2D:
  76997. case KhronosTextureContainer.COMPRESSED_3D:
  76998. case KhronosTextureContainer.TEX_3D:
  76999. }
  77000. };
  77001. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77002. // initialize width & height for level 1
  77003. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77004. var width = this.pixelWidth;
  77005. var height = this.pixelHeight;
  77006. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77007. for (var level = 0; level < mipmapCount; level++) {
  77008. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77009. for (var face = 0; face < this.numberOfFaces; face++) {
  77010. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77011. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77012. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77013. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77014. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77015. }
  77016. width = Math.max(1.0, width * 0.5);
  77017. height = Math.max(1.0, height * 0.5);
  77018. }
  77019. };
  77020. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77021. // load types
  77022. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77023. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77024. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77025. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77026. return KhronosTextureContainer;
  77027. }());
  77028. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77029. })(BABYLON || (BABYLON = {}));
  77030. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77031. var BABYLON;
  77032. (function (BABYLON) {
  77033. var Debug = /** @class */ (function () {
  77034. function Debug() {
  77035. }
  77036. Debug.AxesViewer = /** @class */ (function () {
  77037. function AxesViewer(scene, scaleLines) {
  77038. if (scaleLines === void 0) { scaleLines = 1; }
  77039. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77040. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77041. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77042. this.scaleLines = 1;
  77043. this.scaleLines = scaleLines;
  77044. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77045. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77046. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77047. this._xmesh.renderingGroupId = 2;
  77048. this._ymesh.renderingGroupId = 2;
  77049. this._zmesh.renderingGroupId = 2;
  77050. this._xmesh.material.checkReadyOnlyOnce = true;
  77051. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77052. this._ymesh.material.checkReadyOnlyOnce = true;
  77053. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77054. this._zmesh.material.checkReadyOnlyOnce = true;
  77055. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77056. this.scene = scene;
  77057. }
  77058. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77059. var scaleLines = this.scaleLines;
  77060. if (this._xmesh) {
  77061. this._xmesh.position.copyFrom(position);
  77062. }
  77063. if (this._ymesh) {
  77064. this._ymesh.position.copyFrom(position);
  77065. }
  77066. if (this._zmesh) {
  77067. this._zmesh.position.copyFrom(position);
  77068. }
  77069. var point2 = this._xline[1];
  77070. point2.x = xaxis.x * scaleLines;
  77071. point2.y = xaxis.y * scaleLines;
  77072. point2.z = xaxis.z * scaleLines;
  77073. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77074. point2 = this._yline[1];
  77075. point2.x = yaxis.x * scaleLines;
  77076. point2.y = yaxis.y * scaleLines;
  77077. point2.z = yaxis.z * scaleLines;
  77078. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77079. point2 = this._zline[1];
  77080. point2.x = zaxis.x * scaleLines;
  77081. point2.y = zaxis.y * scaleLines;
  77082. point2.z = zaxis.z * scaleLines;
  77083. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77084. };
  77085. AxesViewer.prototype.dispose = function () {
  77086. if (this._xmesh) {
  77087. this._xmesh.dispose();
  77088. }
  77089. if (this._ymesh) {
  77090. this._ymesh.dispose();
  77091. }
  77092. if (this._zmesh) {
  77093. this._zmesh.dispose();
  77094. }
  77095. this._xmesh = null;
  77096. this._ymesh = null;
  77097. this._zmesh = null;
  77098. this.scene = null;
  77099. };
  77100. return AxesViewer;
  77101. }());
  77102. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77103. __extends(BoneAxesViewer, _super);
  77104. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77105. if (scaleLines === void 0) { scaleLines = 1; }
  77106. var _this = _super.call(this, scene, scaleLines) || this;
  77107. _this.pos = BABYLON.Vector3.Zero();
  77108. _this.xaxis = BABYLON.Vector3.Zero();
  77109. _this.yaxis = BABYLON.Vector3.Zero();
  77110. _this.zaxis = BABYLON.Vector3.Zero();
  77111. _this.mesh = mesh;
  77112. _this.bone = bone;
  77113. return _this;
  77114. }
  77115. BoneAxesViewer.prototype.update = function () {
  77116. if (!this.mesh || !this.bone) {
  77117. return;
  77118. }
  77119. var bone = this.bone;
  77120. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77121. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77122. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77123. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77124. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77125. };
  77126. BoneAxesViewer.prototype.dispose = function () {
  77127. if (this.mesh) {
  77128. this.mesh = null;
  77129. this.bone = null;
  77130. _super.prototype.dispose.call(this);
  77131. }
  77132. };
  77133. return BoneAxesViewer;
  77134. }(Debug.AxesViewer));
  77135. Debug.PhysicsViewer = /** @class */ (function () {
  77136. function PhysicsViewer(scene) {
  77137. this._impostors = [];
  77138. this._meshes = [];
  77139. this._numMeshes = 0;
  77140. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77141. var physicEngine = this._scene.getPhysicsEngine();
  77142. if (physicEngine) {
  77143. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77144. }
  77145. }
  77146. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77147. var plugin = this._physicsEnginePlugin;
  77148. for (var i = 0; i < this._numMeshes; i++) {
  77149. var impostor = this._impostors[i];
  77150. if (!impostor) {
  77151. continue;
  77152. }
  77153. if (impostor.isDisposed) {
  77154. this.hideImpostor(this._impostors[i--]);
  77155. }
  77156. else {
  77157. var mesh = this._meshes[i];
  77158. if (mesh && plugin) {
  77159. plugin.syncMeshWithImpostor(mesh, impostor);
  77160. }
  77161. }
  77162. }
  77163. };
  77164. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77165. if (!this._scene) {
  77166. return;
  77167. }
  77168. for (var i = 0; i < this._numMeshes; i++) {
  77169. if (this._impostors[i] == impostor) {
  77170. return;
  77171. }
  77172. }
  77173. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77174. if (debugMesh) {
  77175. this._impostors[this._numMeshes] = impostor;
  77176. this._meshes[this._numMeshes] = debugMesh;
  77177. if (this._numMeshes === 0) {
  77178. this._renderFunction = this._updateDebugMeshes.bind(this);
  77179. this._scene.registerBeforeRender(this._renderFunction);
  77180. }
  77181. this._numMeshes++;
  77182. }
  77183. };
  77184. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77185. if (!impostor || !this._scene) {
  77186. return;
  77187. }
  77188. var removed = false;
  77189. for (var i = 0; i < this._numMeshes; i++) {
  77190. if (this._impostors[i] == impostor) {
  77191. var mesh = this._meshes[i];
  77192. if (!mesh) {
  77193. continue;
  77194. }
  77195. this._scene.removeMesh(mesh);
  77196. mesh.dispose();
  77197. this._numMeshes--;
  77198. if (this._numMeshes > 0) {
  77199. this._meshes[i] = this._meshes[this._numMeshes];
  77200. this._impostors[i] = this._impostors[this._numMeshes];
  77201. this._meshes[this._numMeshes] = null;
  77202. this._impostors[this._numMeshes] = null;
  77203. }
  77204. else {
  77205. this._meshes[0] = null;
  77206. this._impostors[0] = null;
  77207. }
  77208. removed = true;
  77209. break;
  77210. }
  77211. }
  77212. if (removed && this._numMeshes === 0) {
  77213. this._scene.unregisterBeforeRender(this._renderFunction);
  77214. }
  77215. };
  77216. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77217. if (!this._debugMaterial) {
  77218. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77219. this._debugMaterial.wireframe = true;
  77220. }
  77221. return this._debugMaterial;
  77222. };
  77223. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77224. if (!this._debugBoxMesh) {
  77225. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77226. this._debugBoxMesh.renderingGroupId = 1;
  77227. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77228. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77229. scene.removeMesh(this._debugBoxMesh);
  77230. }
  77231. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77232. };
  77233. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77234. if (!this._debugSphereMesh) {
  77235. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77236. this._debugSphereMesh.renderingGroupId = 1;
  77237. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77238. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77239. scene.removeMesh(this._debugSphereMesh);
  77240. }
  77241. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77242. };
  77243. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77244. var mesh = null;
  77245. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77246. mesh = this._getDebugBoxMesh(scene);
  77247. impostor.getBoxSizeToRef(mesh.scaling);
  77248. }
  77249. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77250. mesh = this._getDebugSphereMesh(scene);
  77251. var radius = impostor.getRadius();
  77252. mesh.scaling.x = radius * 2;
  77253. mesh.scaling.y = radius * 2;
  77254. mesh.scaling.z = radius * 2;
  77255. }
  77256. return mesh;
  77257. };
  77258. PhysicsViewer.prototype.dispose = function () {
  77259. for (var i = 0; i < this._numMeshes; i++) {
  77260. this.hideImpostor(this._impostors[i]);
  77261. }
  77262. if (this._debugBoxMesh) {
  77263. this._debugBoxMesh.dispose();
  77264. }
  77265. if (this._debugSphereMesh) {
  77266. this._debugSphereMesh.dispose();
  77267. }
  77268. if (this._debugMaterial) {
  77269. this._debugMaterial.dispose();
  77270. }
  77271. this._impostors.length = 0;
  77272. this._scene = null;
  77273. this._physicsEnginePlugin = null;
  77274. };
  77275. return PhysicsViewer;
  77276. }());
  77277. Debug.SkeletonViewer = /** @class */ (function () {
  77278. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77279. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77280. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77281. this.skeleton = skeleton;
  77282. this.mesh = mesh;
  77283. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77284. this.renderingGroupId = renderingGroupId;
  77285. this.color = BABYLON.Color3.White();
  77286. this._debugLines = new Array();
  77287. this._isEnabled = false;
  77288. this._scene = scene;
  77289. this.update();
  77290. this._renderFunction = this.update.bind(this);
  77291. }
  77292. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77293. get: function () {
  77294. return this._isEnabled;
  77295. },
  77296. set: function (value) {
  77297. if (this._isEnabled === value) {
  77298. return;
  77299. }
  77300. this._isEnabled = value;
  77301. if (value) {
  77302. this._scene.registerBeforeRender(this._renderFunction);
  77303. }
  77304. else {
  77305. this._scene.unregisterBeforeRender(this._renderFunction);
  77306. }
  77307. },
  77308. enumerable: true,
  77309. configurable: true
  77310. });
  77311. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77312. if (x === void 0) { x = 0; }
  77313. if (y === void 0) { y = 0; }
  77314. if (z === void 0) { z = 0; }
  77315. var tmat = BABYLON.Tmp.Matrix[0];
  77316. var parentBone = bone.getParent();
  77317. tmat.copyFrom(bone.getLocalMatrix());
  77318. if (x !== 0 || y !== 0 || z !== 0) {
  77319. var tmat2 = BABYLON.Tmp.Matrix[1];
  77320. BABYLON.Matrix.IdentityToRef(tmat2);
  77321. tmat2.m[12] = x;
  77322. tmat2.m[13] = y;
  77323. tmat2.m[14] = z;
  77324. tmat2.multiplyToRef(tmat, tmat);
  77325. }
  77326. if (parentBone) {
  77327. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77328. }
  77329. tmat.multiplyToRef(meshMat, tmat);
  77330. position.x = tmat.m[12];
  77331. position.y = tmat.m[13];
  77332. position.z = tmat.m[14];
  77333. };
  77334. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77335. var len = bones.length;
  77336. var meshPos = this.mesh.position;
  77337. for (var i = 0; i < len; i++) {
  77338. var bone = bones[i];
  77339. var points = this._debugLines[i];
  77340. if (!points) {
  77341. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77342. this._debugLines[i] = points;
  77343. }
  77344. this._getBonePosition(points[0], bone, meshMat);
  77345. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77346. points[0].subtractInPlace(meshPos);
  77347. points[1].subtractInPlace(meshPos);
  77348. }
  77349. };
  77350. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77351. var len = bones.length;
  77352. var boneNum = 0;
  77353. var meshPos = this.mesh.position;
  77354. for (var i = len - 1; i >= 0; i--) {
  77355. var childBone = bones[i];
  77356. var parentBone = childBone.getParent();
  77357. if (!parentBone) {
  77358. continue;
  77359. }
  77360. var points = this._debugLines[boneNum];
  77361. if (!points) {
  77362. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77363. this._debugLines[boneNum] = points;
  77364. }
  77365. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77366. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77367. points[0].subtractInPlace(meshPos);
  77368. points[1].subtractInPlace(meshPos);
  77369. boneNum++;
  77370. }
  77371. };
  77372. SkeletonViewer.prototype.update = function () {
  77373. if (this.autoUpdateBonesMatrices) {
  77374. this.skeleton.computeAbsoluteTransforms();
  77375. }
  77376. if (this.skeleton.bones[0].length === undefined) {
  77377. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77378. }
  77379. else {
  77380. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77381. }
  77382. if (!this._debugMesh) {
  77383. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  77384. this._debugMesh.renderingGroupId = this.renderingGroupId;
  77385. }
  77386. else {
  77387. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  77388. }
  77389. this._debugMesh.position.copyFrom(this.mesh.position);
  77390. this._debugMesh.color = this.color;
  77391. };
  77392. SkeletonViewer.prototype.dispose = function () {
  77393. if (this._debugMesh) {
  77394. this.isEnabled = false;
  77395. this._debugMesh.dispose();
  77396. this._debugMesh = null;
  77397. }
  77398. };
  77399. return SkeletonViewer;
  77400. }());
  77401. return Debug;
  77402. }());
  77403. BABYLON.Debug = Debug;
  77404. })(BABYLON || (BABYLON = {}));
  77405. //# sourceMappingURL=babylon.debugModules.js.map
  77406. var BABYLON;
  77407. (function (BABYLON) {
  77408. var RayHelper = /** @class */ (function () {
  77409. function RayHelper(ray) {
  77410. this.ray = ray;
  77411. }
  77412. RayHelper.CreateAndShow = function (ray, scene, color) {
  77413. var helper = new RayHelper(ray);
  77414. helper.show(scene, color);
  77415. return helper;
  77416. };
  77417. RayHelper.prototype.show = function (scene, color) {
  77418. if (!this._renderFunction && this.ray) {
  77419. var ray = this.ray;
  77420. this._renderFunction = this._render.bind(this);
  77421. this._scene = scene;
  77422. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  77423. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  77424. if (this._renderFunction) {
  77425. this._scene.registerBeforeRender(this._renderFunction);
  77426. }
  77427. }
  77428. if (color && this._renderLine) {
  77429. this._renderLine.color.copyFrom(color);
  77430. }
  77431. };
  77432. RayHelper.prototype.hide = function () {
  77433. if (this._renderFunction && this._scene) {
  77434. this._scene.unregisterBeforeRender(this._renderFunction);
  77435. this._scene = null;
  77436. this._renderFunction = null;
  77437. if (this._renderLine) {
  77438. this._renderLine.dispose();
  77439. this._renderLine = null;
  77440. }
  77441. this._renderPoints = [];
  77442. }
  77443. };
  77444. RayHelper.prototype._render = function () {
  77445. var ray = this.ray;
  77446. if (!ray) {
  77447. return;
  77448. }
  77449. var point = this._renderPoints[1];
  77450. var len = Math.min(ray.length, 1000000);
  77451. point.copyFrom(ray.direction);
  77452. point.scaleInPlace(len);
  77453. point.addInPlace(ray.origin);
  77454. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  77455. };
  77456. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  77457. this._attachedToMesh = mesh;
  77458. var ray = this.ray;
  77459. if (!ray) {
  77460. return;
  77461. }
  77462. if (!ray.direction) {
  77463. ray.direction = BABYLON.Vector3.Zero();
  77464. }
  77465. if (!ray.origin) {
  77466. ray.origin = BABYLON.Vector3.Zero();
  77467. }
  77468. if (length) {
  77469. ray.length = length;
  77470. }
  77471. if (!meshSpaceOrigin) {
  77472. meshSpaceOrigin = BABYLON.Vector3.Zero();
  77473. }
  77474. if (!meshSpaceDirection) {
  77475. // -1 so that this will work with Mesh.lookAt
  77476. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  77477. }
  77478. if (!this._meshSpaceDirection) {
  77479. this._meshSpaceDirection = meshSpaceDirection.clone();
  77480. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  77481. }
  77482. else {
  77483. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  77484. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  77485. }
  77486. if (!this._updateToMeshFunction) {
  77487. this._updateToMeshFunction = this._updateToMesh.bind(this);
  77488. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  77489. }
  77490. this._updateToMesh();
  77491. };
  77492. RayHelper.prototype.detachFromMesh = function () {
  77493. if (this._attachedToMesh) {
  77494. if (this._updateToMeshFunction) {
  77495. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  77496. }
  77497. this._attachedToMesh = null;
  77498. this._updateToMeshFunction = null;
  77499. }
  77500. };
  77501. RayHelper.prototype._updateToMesh = function () {
  77502. var ray = this.ray;
  77503. if (!this._attachedToMesh || !ray) {
  77504. return;
  77505. }
  77506. if (this._attachedToMesh._isDisposed) {
  77507. this.detachFromMesh();
  77508. return;
  77509. }
  77510. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  77511. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  77512. };
  77513. RayHelper.prototype.dispose = function () {
  77514. this.hide();
  77515. this.detachFromMesh();
  77516. this.ray = null;
  77517. };
  77518. return RayHelper;
  77519. }());
  77520. BABYLON.RayHelper = RayHelper;
  77521. })(BABYLON || (BABYLON = {}));
  77522. //# sourceMappingURL=babylon.rayHelper.js.map
  77523. var BABYLON;
  77524. (function (BABYLON) {
  77525. // load the inspector using require, if not present in the global namespace.
  77526. var DebugLayer = /** @class */ (function () {
  77527. function DebugLayer(scene) {
  77528. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77529. this._scene = scene;
  77530. // load inspector using require, if it doesn't exist on the global namespace.
  77531. }
  77532. /** Creates the inspector window. */
  77533. DebugLayer.prototype._createInspector = function (config) {
  77534. if (config === void 0) { config = {}; }
  77535. var popup = config.popup || false;
  77536. var initialTab = config.initialTab || 0;
  77537. var parentElement = config.parentElement || null;
  77538. if (!this._inspector) {
  77539. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  77540. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  77541. } // else nothing to do,; instance is already existing
  77542. };
  77543. DebugLayer.prototype.isVisible = function () {
  77544. if (!this._inspector) {
  77545. return false;
  77546. }
  77547. return true;
  77548. };
  77549. DebugLayer.prototype.hide = function () {
  77550. if (this._inspector) {
  77551. try {
  77552. this._inspector.dispose();
  77553. }
  77554. catch (e) {
  77555. // If the inspector has been removed directly from the inspector tool
  77556. }
  77557. this._inspector = null;
  77558. }
  77559. };
  77560. DebugLayer.prototype.show = function (config) {
  77561. if (config === void 0) { config = {}; }
  77562. if (typeof this.BJSINSPECTOR == 'undefined') {
  77563. // Load inspector and add it to the DOM
  77564. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  77565. }
  77566. else {
  77567. // Otherwise creates the inspector
  77568. this._createInspector(config);
  77569. }
  77570. };
  77571. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  77572. return DebugLayer;
  77573. }());
  77574. BABYLON.DebugLayer = DebugLayer;
  77575. })(BABYLON || (BABYLON = {}));
  77576. //# sourceMappingURL=babylon.debugLayer.js.map
  77577. var BABYLON;
  77578. (function (BABYLON) {
  77579. var BoundingBoxRenderer = /** @class */ (function () {
  77580. function BoundingBoxRenderer(scene) {
  77581. this.frontColor = new BABYLON.Color3(1, 1, 1);
  77582. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  77583. this.showBackLines = true;
  77584. this.renderList = new BABYLON.SmartArray(32);
  77585. this._vertexBuffers = {};
  77586. this._scene = scene;
  77587. }
  77588. BoundingBoxRenderer.prototype._prepareRessources = function () {
  77589. if (this._colorShader) {
  77590. return;
  77591. }
  77592. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  77593. attributes: [BABYLON.VertexBuffer.PositionKind],
  77594. uniforms: ["world", "viewProjection", "color"]
  77595. });
  77596. var engine = this._scene.getEngine();
  77597. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  77598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  77599. this._createIndexBuffer();
  77600. };
  77601. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  77602. var engine = this._scene.getEngine();
  77603. 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]);
  77604. };
  77605. BoundingBoxRenderer.prototype._rebuild = function () {
  77606. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77607. if (vb) {
  77608. vb._rebuild();
  77609. }
  77610. this._createIndexBuffer();
  77611. };
  77612. BoundingBoxRenderer.prototype.reset = function () {
  77613. this.renderList.reset();
  77614. };
  77615. BoundingBoxRenderer.prototype.render = function () {
  77616. if (this.renderList.length === 0) {
  77617. return;
  77618. }
  77619. this._prepareRessources();
  77620. if (!this._colorShader.isReady()) {
  77621. return;
  77622. }
  77623. var engine = this._scene.getEngine();
  77624. engine.setDepthWrite(false);
  77625. this._colorShader._preBind();
  77626. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  77627. var boundingBox = this.renderList.data[boundingBoxIndex];
  77628. var min = boundingBox.minimum;
  77629. var max = boundingBox.maximum;
  77630. var diff = max.subtract(min);
  77631. var median = min.add(diff.scale(0.5));
  77632. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77633. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77634. .multiply(boundingBox.getWorldMatrix());
  77635. // VBOs
  77636. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77637. if (this.showBackLines) {
  77638. // Back
  77639. engine.setDepthFunctionToGreaterOrEqual();
  77640. this._scene.resetCachedMaterial();
  77641. this._colorShader.setColor4("color", this.backColor.toColor4());
  77642. this._colorShader.bind(worldMatrix);
  77643. // Draw order
  77644. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77645. }
  77646. // Front
  77647. engine.setDepthFunctionToLess();
  77648. this._scene.resetCachedMaterial();
  77649. this._colorShader.setColor4("color", this.frontColor.toColor4());
  77650. this._colorShader.bind(worldMatrix);
  77651. // Draw order
  77652. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77653. }
  77654. this._colorShader.unbind();
  77655. engine.setDepthFunctionToLessOrEqual();
  77656. engine.setDepthWrite(true);
  77657. };
  77658. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  77659. this._prepareRessources();
  77660. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  77661. return;
  77662. }
  77663. var engine = this._scene.getEngine();
  77664. engine.setDepthWrite(false);
  77665. engine.setColorWrite(false);
  77666. this._colorShader._preBind();
  77667. var boundingBox = mesh._boundingInfo.boundingBox;
  77668. var min = boundingBox.minimum;
  77669. var max = boundingBox.maximum;
  77670. var diff = max.subtract(min);
  77671. var median = min.add(diff.scale(0.5));
  77672. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  77673. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  77674. .multiply(boundingBox.getWorldMatrix());
  77675. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  77676. engine.setDepthFunctionToLess();
  77677. this._scene.resetCachedMaterial();
  77678. this._colorShader.bind(worldMatrix);
  77679. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  77680. this._colorShader.unbind();
  77681. engine.setDepthFunctionToLessOrEqual();
  77682. engine.setDepthWrite(true);
  77683. engine.setColorWrite(true);
  77684. };
  77685. BoundingBoxRenderer.prototype.dispose = function () {
  77686. if (!this._colorShader) {
  77687. return;
  77688. }
  77689. this.renderList.dispose();
  77690. this._colorShader.dispose();
  77691. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77692. if (buffer) {
  77693. buffer.dispose();
  77694. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77695. }
  77696. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77697. };
  77698. return BoundingBoxRenderer;
  77699. }());
  77700. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  77701. })(BABYLON || (BABYLON = {}));
  77702. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  77703. var BABYLON;
  77704. (function (BABYLON) {
  77705. var MorphTarget = /** @class */ (function () {
  77706. function MorphTarget(name, influence) {
  77707. if (influence === void 0) { influence = 0; }
  77708. this.name = name;
  77709. this.animations = new Array();
  77710. this._positions = null;
  77711. this._normals = null;
  77712. this._tangents = null;
  77713. this.onInfluenceChanged = new BABYLON.Observable();
  77714. this.influence = influence;
  77715. }
  77716. Object.defineProperty(MorphTarget.prototype, "influence", {
  77717. get: function () {
  77718. return this._influence;
  77719. },
  77720. set: function (influence) {
  77721. if (this._influence === influence) {
  77722. return;
  77723. }
  77724. var previous = this._influence;
  77725. this._influence = influence;
  77726. if (this.onInfluenceChanged.hasObservers) {
  77727. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  77728. }
  77729. },
  77730. enumerable: true,
  77731. configurable: true
  77732. });
  77733. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  77734. get: function () {
  77735. return !!this._positions;
  77736. },
  77737. enumerable: true,
  77738. configurable: true
  77739. });
  77740. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  77741. get: function () {
  77742. return !!this._normals;
  77743. },
  77744. enumerable: true,
  77745. configurable: true
  77746. });
  77747. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  77748. get: function () {
  77749. return !!this._tangents;
  77750. },
  77751. enumerable: true,
  77752. configurable: true
  77753. });
  77754. MorphTarget.prototype.setPositions = function (data) {
  77755. this._positions = data;
  77756. };
  77757. MorphTarget.prototype.getPositions = function () {
  77758. return this._positions;
  77759. };
  77760. MorphTarget.prototype.setNormals = function (data) {
  77761. this._normals = data;
  77762. };
  77763. MorphTarget.prototype.getNormals = function () {
  77764. return this._normals;
  77765. };
  77766. MorphTarget.prototype.setTangents = function (data) {
  77767. this._tangents = data;
  77768. };
  77769. MorphTarget.prototype.getTangents = function () {
  77770. return this._tangents;
  77771. };
  77772. /**
  77773. * Serializes the current target into a Serialization object.
  77774. * Returns the serialized object.
  77775. */
  77776. MorphTarget.prototype.serialize = function () {
  77777. var serializationObject = {};
  77778. serializationObject.name = this.name;
  77779. serializationObject.influence = this.influence;
  77780. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  77781. if (this.hasNormals) {
  77782. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  77783. }
  77784. if (this.hasTangents) {
  77785. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  77786. }
  77787. // Animations
  77788. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  77789. return serializationObject;
  77790. };
  77791. // Statics
  77792. MorphTarget.Parse = function (serializationObject) {
  77793. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  77794. result.setPositions(serializationObject.positions);
  77795. if (serializationObject.normals) {
  77796. result.setNormals(serializationObject.normals);
  77797. }
  77798. if (serializationObject.tangents) {
  77799. result.setTangents(serializationObject.tangents);
  77800. }
  77801. // Animations
  77802. if (serializationObject.animations) {
  77803. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  77804. var parsedAnimation = serializationObject.animations[animationIndex];
  77805. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  77806. }
  77807. }
  77808. return result;
  77809. };
  77810. MorphTarget.FromMesh = function (mesh, name, influence) {
  77811. if (!name) {
  77812. name = mesh.name;
  77813. }
  77814. var result = new MorphTarget(name, influence);
  77815. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  77816. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  77817. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  77818. }
  77819. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  77820. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  77821. }
  77822. return result;
  77823. };
  77824. return MorphTarget;
  77825. }());
  77826. BABYLON.MorphTarget = MorphTarget;
  77827. })(BABYLON || (BABYLON = {}));
  77828. //# sourceMappingURL=babylon.morphTarget.js.map
  77829. var BABYLON;
  77830. (function (BABYLON) {
  77831. var MorphTargetManager = /** @class */ (function () {
  77832. function MorphTargetManager(scene) {
  77833. if (scene === void 0) { scene = null; }
  77834. this._targets = new Array();
  77835. this._targetObservable = new Array();
  77836. this._activeTargets = new BABYLON.SmartArray(16);
  77837. this._supportsNormals = false;
  77838. this._supportsTangents = false;
  77839. this._vertexCount = 0;
  77840. this._uniqueId = 0;
  77841. this._tempInfluences = new Array();
  77842. if (!scene) {
  77843. scene = BABYLON.Engine.LastCreatedScene;
  77844. }
  77845. this._scene = scene;
  77846. if (this._scene) {
  77847. this._scene.morphTargetManagers.push(this);
  77848. this._uniqueId = this._scene.getUniqueId();
  77849. }
  77850. }
  77851. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  77852. get: function () {
  77853. return this._uniqueId;
  77854. },
  77855. enumerable: true,
  77856. configurable: true
  77857. });
  77858. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  77859. get: function () {
  77860. return this._vertexCount;
  77861. },
  77862. enumerable: true,
  77863. configurable: true
  77864. });
  77865. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  77866. get: function () {
  77867. return this._supportsNormals;
  77868. },
  77869. enumerable: true,
  77870. configurable: true
  77871. });
  77872. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  77873. get: function () {
  77874. return this._supportsTangents;
  77875. },
  77876. enumerable: true,
  77877. configurable: true
  77878. });
  77879. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  77880. get: function () {
  77881. return this._targets.length;
  77882. },
  77883. enumerable: true,
  77884. configurable: true
  77885. });
  77886. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  77887. get: function () {
  77888. return this._activeTargets.length;
  77889. },
  77890. enumerable: true,
  77891. configurable: true
  77892. });
  77893. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  77894. get: function () {
  77895. return this._influences;
  77896. },
  77897. enumerable: true,
  77898. configurable: true
  77899. });
  77900. MorphTargetManager.prototype.getActiveTarget = function (index) {
  77901. return this._activeTargets.data[index];
  77902. };
  77903. MorphTargetManager.prototype.getTarget = function (index) {
  77904. return this._targets[index];
  77905. };
  77906. MorphTargetManager.prototype.addTarget = function (target) {
  77907. var _this = this;
  77908. this._targets.push(target);
  77909. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  77910. _this._syncActiveTargets(needUpdate);
  77911. }));
  77912. this._syncActiveTargets(true);
  77913. };
  77914. MorphTargetManager.prototype.removeTarget = function (target) {
  77915. var index = this._targets.indexOf(target);
  77916. if (index >= 0) {
  77917. this._targets.splice(index, 1);
  77918. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  77919. this._syncActiveTargets(true);
  77920. }
  77921. };
  77922. /**
  77923. * Serializes the current manager into a Serialization object.
  77924. * Returns the serialized object.
  77925. */
  77926. MorphTargetManager.prototype.serialize = function () {
  77927. var serializationObject = {};
  77928. serializationObject.id = this.uniqueId;
  77929. serializationObject.targets = [];
  77930. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77931. var target = _a[_i];
  77932. serializationObject.targets.push(target.serialize());
  77933. }
  77934. return serializationObject;
  77935. };
  77936. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  77937. var influenceCount = 0;
  77938. this._activeTargets.reset();
  77939. this._supportsNormals = true;
  77940. this._supportsTangents = true;
  77941. this._vertexCount = 0;
  77942. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  77943. var target = _a[_i];
  77944. this._activeTargets.push(target);
  77945. this._tempInfluences[influenceCount++] = target.influence;
  77946. var positions = target.getPositions();
  77947. if (positions) {
  77948. this._supportsNormals = this._supportsNormals && target.hasNormals;
  77949. this._supportsTangents = this._supportsTangents && target.hasTangents;
  77950. var vertexCount = positions.length / 3;
  77951. if (this._vertexCount === 0) {
  77952. this._vertexCount = vertexCount;
  77953. }
  77954. else if (this._vertexCount !== vertexCount) {
  77955. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  77956. return;
  77957. }
  77958. }
  77959. }
  77960. if (!this._influences || this._influences.length !== influenceCount) {
  77961. this._influences = new Float32Array(influenceCount);
  77962. }
  77963. for (var index = 0; index < influenceCount; index++) {
  77964. this._influences[index] = this._tempInfluences[index];
  77965. }
  77966. if (needUpdate && this._scene) {
  77967. // Flag meshes as dirty to resync with the active targets
  77968. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  77969. var mesh = _c[_b];
  77970. if (mesh.morphTargetManager === this) {
  77971. mesh._syncGeometryWithMorphTargetManager();
  77972. }
  77973. }
  77974. }
  77975. };
  77976. // Statics
  77977. MorphTargetManager.Parse = function (serializationObject, scene) {
  77978. var result = new MorphTargetManager(scene);
  77979. result._uniqueId = serializationObject.id;
  77980. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  77981. var targetData = _a[_i];
  77982. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  77983. }
  77984. return result;
  77985. };
  77986. return MorphTargetManager;
  77987. }());
  77988. BABYLON.MorphTargetManager = MorphTargetManager;
  77989. })(BABYLON || (BABYLON = {}));
  77990. //# sourceMappingURL=babylon.morphTargetManager.js.map
  77991. var BABYLON;
  77992. (function (BABYLON) {
  77993. var Octree = /** @class */ (function () {
  77994. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  77995. if (maxDepth === void 0) { maxDepth = 2; }
  77996. this.maxDepth = maxDepth;
  77997. this.dynamicContent = new Array();
  77998. this._maxBlockCapacity = maxBlockCapacity || 64;
  77999. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78000. this._creationFunc = creationFunc;
  78001. }
  78002. // Methods
  78003. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78004. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78005. };
  78006. Octree.prototype.addMesh = function (entry) {
  78007. for (var index = 0; index < this.blocks.length; index++) {
  78008. var block = this.blocks[index];
  78009. block.addEntry(entry);
  78010. }
  78011. };
  78012. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78013. this._selectionContent.reset();
  78014. for (var index = 0; index < this.blocks.length; index++) {
  78015. var block = this.blocks[index];
  78016. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78017. }
  78018. if (allowDuplicate) {
  78019. this._selectionContent.concat(this.dynamicContent);
  78020. }
  78021. else {
  78022. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78023. }
  78024. return this._selectionContent;
  78025. };
  78026. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78027. this._selectionContent.reset();
  78028. for (var index = 0; index < this.blocks.length; index++) {
  78029. var block = this.blocks[index];
  78030. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78031. }
  78032. if (allowDuplicate) {
  78033. this._selectionContent.concat(this.dynamicContent);
  78034. }
  78035. else {
  78036. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78037. }
  78038. return this._selectionContent;
  78039. };
  78040. Octree.prototype.intersectsRay = function (ray) {
  78041. this._selectionContent.reset();
  78042. for (var index = 0; index < this.blocks.length; index++) {
  78043. var block = this.blocks[index];
  78044. block.intersectsRay(ray, this._selectionContent);
  78045. }
  78046. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78047. return this._selectionContent;
  78048. };
  78049. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78050. target.blocks = new Array();
  78051. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78052. // Segmenting space
  78053. for (var x = 0; x < 2; x++) {
  78054. for (var y = 0; y < 2; y++) {
  78055. for (var z = 0; z < 2; z++) {
  78056. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78057. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78058. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78059. block.addEntries(entries);
  78060. target.blocks.push(block);
  78061. }
  78062. }
  78063. }
  78064. };
  78065. Octree.CreationFuncForMeshes = function (entry, block) {
  78066. var boundingInfo = entry.getBoundingInfo();
  78067. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78068. block.entries.push(entry);
  78069. }
  78070. };
  78071. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78072. var boundingInfo = entry.getBoundingInfo();
  78073. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78074. block.entries.push(entry);
  78075. }
  78076. };
  78077. return Octree;
  78078. }());
  78079. BABYLON.Octree = Octree;
  78080. })(BABYLON || (BABYLON = {}));
  78081. //# sourceMappingURL=babylon.octree.js.map
  78082. var BABYLON;
  78083. (function (BABYLON) {
  78084. var OctreeBlock = /** @class */ (function () {
  78085. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78086. this.entries = new Array();
  78087. this._boundingVectors = new Array();
  78088. this._capacity = capacity;
  78089. this._depth = depth;
  78090. this._maxDepth = maxDepth;
  78091. this._creationFunc = creationFunc;
  78092. this._minPoint = minPoint;
  78093. this._maxPoint = maxPoint;
  78094. this._boundingVectors.push(minPoint.clone());
  78095. this._boundingVectors.push(maxPoint.clone());
  78096. this._boundingVectors.push(minPoint.clone());
  78097. this._boundingVectors[2].x = maxPoint.x;
  78098. this._boundingVectors.push(minPoint.clone());
  78099. this._boundingVectors[3].y = maxPoint.y;
  78100. this._boundingVectors.push(minPoint.clone());
  78101. this._boundingVectors[4].z = maxPoint.z;
  78102. this._boundingVectors.push(maxPoint.clone());
  78103. this._boundingVectors[5].z = minPoint.z;
  78104. this._boundingVectors.push(maxPoint.clone());
  78105. this._boundingVectors[6].x = minPoint.x;
  78106. this._boundingVectors.push(maxPoint.clone());
  78107. this._boundingVectors[7].y = minPoint.y;
  78108. }
  78109. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78110. // Property
  78111. get: function () {
  78112. return this._capacity;
  78113. },
  78114. enumerable: true,
  78115. configurable: true
  78116. });
  78117. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78118. get: function () {
  78119. return this._minPoint;
  78120. },
  78121. enumerable: true,
  78122. configurable: true
  78123. });
  78124. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78125. get: function () {
  78126. return this._maxPoint;
  78127. },
  78128. enumerable: true,
  78129. configurable: true
  78130. });
  78131. // Methods
  78132. OctreeBlock.prototype.addEntry = function (entry) {
  78133. if (this.blocks) {
  78134. for (var index = 0; index < this.blocks.length; index++) {
  78135. var block = this.blocks[index];
  78136. block.addEntry(entry);
  78137. }
  78138. return;
  78139. }
  78140. this._creationFunc(entry, this);
  78141. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78142. this.createInnerBlocks();
  78143. }
  78144. };
  78145. OctreeBlock.prototype.addEntries = function (entries) {
  78146. for (var index = 0; index < entries.length; index++) {
  78147. var mesh = entries[index];
  78148. this.addEntry(mesh);
  78149. }
  78150. };
  78151. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78152. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78153. if (this.blocks) {
  78154. for (var index = 0; index < this.blocks.length; index++) {
  78155. var block = this.blocks[index];
  78156. block.select(frustumPlanes, selection, allowDuplicate);
  78157. }
  78158. return;
  78159. }
  78160. if (allowDuplicate) {
  78161. selection.concat(this.entries);
  78162. }
  78163. else {
  78164. selection.concatWithNoDuplicate(this.entries);
  78165. }
  78166. }
  78167. };
  78168. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78169. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78170. if (this.blocks) {
  78171. for (var index = 0; index < this.blocks.length; index++) {
  78172. var block = this.blocks[index];
  78173. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78174. }
  78175. return;
  78176. }
  78177. if (allowDuplicate) {
  78178. selection.concat(this.entries);
  78179. }
  78180. else {
  78181. selection.concatWithNoDuplicate(this.entries);
  78182. }
  78183. }
  78184. };
  78185. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78186. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78187. if (this.blocks) {
  78188. for (var index = 0; index < this.blocks.length; index++) {
  78189. var block = this.blocks[index];
  78190. block.intersectsRay(ray, selection);
  78191. }
  78192. return;
  78193. }
  78194. selection.concatWithNoDuplicate(this.entries);
  78195. }
  78196. };
  78197. OctreeBlock.prototype.createInnerBlocks = function () {
  78198. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78199. };
  78200. return OctreeBlock;
  78201. }());
  78202. BABYLON.OctreeBlock = OctreeBlock;
  78203. })(BABYLON || (BABYLON = {}));
  78204. //# sourceMappingURL=babylon.octreeBlock.js.map
  78205. var BABYLON;
  78206. (function (BABYLON) {
  78207. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78208. __extends(VRDistortionCorrectionPostProcess, _super);
  78209. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78210. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78211. 'LensCenter',
  78212. 'Scale',
  78213. 'ScaleIn',
  78214. 'HmdWarpParam'
  78215. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78216. _this._isRightEye = isRightEye;
  78217. _this._distortionFactors = vrMetrics.distortionK;
  78218. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78219. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78220. _this.adaptScaleToCurrentViewport = true;
  78221. _this.onSizeChangedObservable.add(function () {
  78222. _this.aspectRatio = _this.width * .5 / _this.height;
  78223. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78224. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78225. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78226. });
  78227. _this.onApplyObservable.add(function (effect) {
  78228. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78229. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78230. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78231. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78232. });
  78233. return _this;
  78234. }
  78235. return VRDistortionCorrectionPostProcess;
  78236. }(BABYLON.PostProcess));
  78237. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78238. })(BABYLON || (BABYLON = {}));
  78239. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78240. var BABYLON;
  78241. (function (BABYLON) {
  78242. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78243. __extends(AnaglyphPostProcess, _super);
  78244. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78245. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78246. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78247. _this.onApplyObservable.add(function (effect) {
  78248. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78249. });
  78250. return _this;
  78251. }
  78252. return AnaglyphPostProcess;
  78253. }(BABYLON.PostProcess));
  78254. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78255. })(BABYLON || (BABYLON = {}));
  78256. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78257. var BABYLON;
  78258. (function (BABYLON) {
  78259. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78260. __extends(StereoscopicInterlacePostProcess, _super);
  78261. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78262. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78263. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78264. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78265. _this.onSizeChangedObservable.add(function () {
  78266. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78267. });
  78268. _this.onApplyObservable.add(function (effect) {
  78269. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78270. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78271. });
  78272. return _this;
  78273. }
  78274. return StereoscopicInterlacePostProcess;
  78275. }(BABYLON.PostProcess));
  78276. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78277. })(BABYLON || (BABYLON = {}));
  78278. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78279. var BABYLON;
  78280. (function (BABYLON) {
  78281. /**
  78282. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78283. * Screen rotation is taken into account.
  78284. */
  78285. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78286. function FreeCameraDeviceOrientationInput() {
  78287. var _this = this;
  78288. this._screenOrientationAngle = 0;
  78289. this._screenQuaternion = new BABYLON.Quaternion();
  78290. this._alpha = 0;
  78291. this._beta = 0;
  78292. this._gamma = 0;
  78293. this._orientationChanged = function () {
  78294. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78295. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78296. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78297. };
  78298. this._deviceOrientation = function (evt) {
  78299. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78300. _this._beta = evt.beta !== null ? evt.beta : 0;
  78301. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78302. };
  78303. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78304. this._orientationChanged();
  78305. }
  78306. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78307. get: function () {
  78308. return this._camera;
  78309. },
  78310. set: function (camera) {
  78311. this._camera = camera;
  78312. if (this._camera != null && !this._camera.rotationQuaternion) {
  78313. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78314. }
  78315. },
  78316. enumerable: true,
  78317. configurable: true
  78318. });
  78319. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78320. window.addEventListener("orientationchange", this._orientationChanged);
  78321. window.addEventListener("deviceorientation", this._deviceOrientation);
  78322. //In certain cases, the attach control is called AFTER orientation was changed,
  78323. //So this is needed.
  78324. this._orientationChanged();
  78325. };
  78326. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78327. window.removeEventListener("orientationchange", this._orientationChanged);
  78328. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78329. };
  78330. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78331. //if no device orientation provided, don't update the rotation.
  78332. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78333. if (!this._alpha)
  78334. return;
  78335. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78336. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78337. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78338. //Mirror on XY Plane
  78339. this._camera.rotationQuaternion.z *= -1;
  78340. this._camera.rotationQuaternion.w *= -1;
  78341. };
  78342. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78343. return "FreeCameraDeviceOrientationInput";
  78344. };
  78345. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78346. return "deviceOrientation";
  78347. };
  78348. return FreeCameraDeviceOrientationInput;
  78349. }());
  78350. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78351. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78352. })(BABYLON || (BABYLON = {}));
  78353. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78354. var BABYLON;
  78355. (function (BABYLON) {
  78356. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78357. function ArcRotateCameraVRDeviceOrientationInput() {
  78358. this.alphaCorrection = 1;
  78359. this.betaCorrection = 1;
  78360. this.gammaCorrection = 1;
  78361. this._alpha = 0;
  78362. this._gamma = 0;
  78363. this._dirty = false;
  78364. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78365. }
  78366. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78367. this.camera.attachControl(element, noPreventDefault);
  78368. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78369. };
  78370. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  78371. if (evt.alpha !== null) {
  78372. this._alpha = +evt.alpha | 0;
  78373. }
  78374. if (evt.gamma !== null) {
  78375. this._gamma = +evt.gamma | 0;
  78376. }
  78377. this._dirty = true;
  78378. };
  78379. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  78380. if (this._dirty) {
  78381. this._dirty = false;
  78382. if (this._gamma < 0) {
  78383. this._gamma = 180 + this._gamma;
  78384. }
  78385. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  78386. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  78387. }
  78388. };
  78389. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  78390. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  78391. };
  78392. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  78393. return "ArcRotateCameraVRDeviceOrientationInput";
  78394. };
  78395. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  78396. return "VRDeviceOrientation";
  78397. };
  78398. return ArcRotateCameraVRDeviceOrientationInput;
  78399. }());
  78400. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  78401. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  78402. })(BABYLON || (BABYLON = {}));
  78403. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  78404. var BABYLON;
  78405. (function (BABYLON) {
  78406. var VRCameraMetrics = /** @class */ (function () {
  78407. function VRCameraMetrics() {
  78408. this.compensateDistortion = true;
  78409. }
  78410. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  78411. get: function () {
  78412. return this.hResolution / (2 * this.vResolution);
  78413. },
  78414. enumerable: true,
  78415. configurable: true
  78416. });
  78417. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  78418. get: function () {
  78419. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  78420. },
  78421. enumerable: true,
  78422. configurable: true
  78423. });
  78424. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  78425. get: function () {
  78426. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78427. var h = (4 * meters) / this.hScreenSize;
  78428. return BABYLON.Matrix.Translation(h, 0, 0);
  78429. },
  78430. enumerable: true,
  78431. configurable: true
  78432. });
  78433. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  78434. get: function () {
  78435. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78436. var h = (4 * meters) / this.hScreenSize;
  78437. return BABYLON.Matrix.Translation(-h, 0, 0);
  78438. },
  78439. enumerable: true,
  78440. configurable: true
  78441. });
  78442. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  78443. get: function () {
  78444. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  78445. },
  78446. enumerable: true,
  78447. configurable: true
  78448. });
  78449. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  78450. get: function () {
  78451. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  78452. },
  78453. enumerable: true,
  78454. configurable: true
  78455. });
  78456. VRCameraMetrics.GetDefault = function () {
  78457. var result = new VRCameraMetrics();
  78458. result.hResolution = 1280;
  78459. result.vResolution = 800;
  78460. result.hScreenSize = 0.149759993;
  78461. result.vScreenSize = 0.0935999975;
  78462. result.vScreenCenter = 0.0467999987;
  78463. result.eyeToScreenDistance = 0.0410000011;
  78464. result.lensSeparationDistance = 0.0635000020;
  78465. result.interpupillaryDistance = 0.0640000030;
  78466. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  78467. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  78468. result.postProcessScaleFactor = 1.714605507808412;
  78469. result.lensCenterOffset = 0.151976421;
  78470. return result;
  78471. };
  78472. return VRCameraMetrics;
  78473. }());
  78474. BABYLON.VRCameraMetrics = VRCameraMetrics;
  78475. })(BABYLON || (BABYLON = {}));
  78476. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  78477. var BABYLON;
  78478. (function (BABYLON) {
  78479. /**
  78480. * This represents a WebVR camera.
  78481. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  78482. * @example http://doc.babylonjs.com/how_to/webvr_camera
  78483. */
  78484. var WebVRFreeCamera = /** @class */ (function (_super) {
  78485. __extends(WebVRFreeCamera, _super);
  78486. /**
  78487. * Instantiates a WebVRFreeCamera.
  78488. * @param name The name of the WebVRFreeCamera
  78489. * @param position The starting anchor position for the camera
  78490. * @param scene The scene the camera belongs to
  78491. * @param webVROptions a set of customizable options for the webVRCamera
  78492. */
  78493. function WebVRFreeCamera(name, position, scene, webVROptions) {
  78494. if (webVROptions === void 0) { webVROptions = {}; }
  78495. var _this = _super.call(this, name, position, scene) || this;
  78496. _this.webVROptions = webVROptions;
  78497. /**
  78498. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  78499. */
  78500. _this._vrDevice = null;
  78501. /**
  78502. * The rawPose of the vrDevice.
  78503. */
  78504. _this.rawPose = null;
  78505. _this._specsVersion = "1.1";
  78506. _this._attached = false;
  78507. _this._descendants = [];
  78508. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  78509. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  78510. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  78511. _this._standingMatrix = null;
  78512. /**
  78513. * Represents device position in babylon space.
  78514. */
  78515. _this.devicePosition = BABYLON.Vector3.Zero();
  78516. /**
  78517. * Represents device rotation in babylon space.
  78518. */
  78519. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  78520. /**
  78521. * The scale of the device to be used when translating from device space to babylon space.
  78522. */
  78523. _this.deviceScaleFactor = 1;
  78524. _this._deviceToWorld = BABYLON.Matrix.Identity();
  78525. _this._worldToDevice = BABYLON.Matrix.Identity();
  78526. /**
  78527. * References to the webVR controllers for the vrDevice.
  78528. */
  78529. _this.controllers = [];
  78530. /**
  78531. * Emits an event when a controller is attached.
  78532. */
  78533. _this.onControllersAttachedObservable = new BABYLON.Observable();
  78534. /**
  78535. * Emits an event when a controller's mesh has been loaded;
  78536. */
  78537. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  78538. /**
  78539. * If the rig cameras be used as parent instead of this camera.
  78540. */
  78541. _this.rigParenting = true;
  78542. _this._defaultHeight = undefined;
  78543. _this._workingVector = BABYLON.Vector3.Zero();
  78544. _this._oneVector = BABYLON.Vector3.One();
  78545. _this._workingMatrix = BABYLON.Matrix.Identity();
  78546. _this._cache.position = BABYLON.Vector3.Zero();
  78547. if (webVROptions.defaultHeight) {
  78548. _this._defaultHeight = webVROptions.defaultHeight;
  78549. _this.position.y = _this._defaultHeight;
  78550. }
  78551. _this.minZ = 0.1;
  78552. //legacy support - the compensation boolean was removed.
  78553. if (arguments.length === 5) {
  78554. _this.webVROptions = arguments[4];
  78555. }
  78556. // default webVR options
  78557. if (_this.webVROptions.trackPosition == undefined) {
  78558. _this.webVROptions.trackPosition = true;
  78559. }
  78560. if (_this.webVROptions.controllerMeshes == undefined) {
  78561. _this.webVROptions.controllerMeshes = true;
  78562. }
  78563. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  78564. _this.webVROptions.defaultLightingOnControllers = true;
  78565. }
  78566. _this.rotationQuaternion = new BABYLON.Quaternion();
  78567. if (_this.webVROptions && _this.webVROptions.positionScale) {
  78568. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  78569. }
  78570. //enable VR
  78571. var engine = _this.getEngine();
  78572. _this._onVREnabled = function (success) { if (success) {
  78573. _this.initControllers();
  78574. } };
  78575. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  78576. engine.initWebVR().add(function (event) {
  78577. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  78578. return;
  78579. }
  78580. _this._vrDevice = event.vrDisplay;
  78581. //reset the rig parameters.
  78582. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  78583. if (_this._attached) {
  78584. _this.getEngine().enableVR();
  78585. }
  78586. });
  78587. if (typeof (VRFrameData) !== "undefined")
  78588. _this._frameData = new VRFrameData();
  78589. /**
  78590. * The idea behind the following lines:
  78591. * objects that have the camera as parent should actually have the rig cameras as a parent.
  78592. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  78593. * the second will not show it correctly.
  78594. *
  78595. * To solve this - each object that has the camera as parent will be added to a protected array.
  78596. * When the rig camera renders, it will take this array and set all of those to be its children.
  78597. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  78598. * Amazing!
  78599. */
  78600. scene.onBeforeCameraRenderObservable.add(function (camera) {
  78601. if (camera.parent === _this && _this.rigParenting) {
  78602. _this._descendants = _this.getDescendants(true, function (n) {
  78603. // don't take the cameras or the controllers!
  78604. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  78605. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  78606. return !isController && !isRigCamera;
  78607. });
  78608. _this._descendants.forEach(function (node) {
  78609. node.parent = camera;
  78610. });
  78611. }
  78612. });
  78613. scene.onAfterCameraRenderObservable.add(function (camera) {
  78614. if (camera.parent === _this && _this.rigParenting) {
  78615. _this._descendants.forEach(function (node) {
  78616. node.parent = _this;
  78617. });
  78618. }
  78619. });
  78620. return _this;
  78621. }
  78622. /**
  78623. * Gets the device distance from the ground in meters.
  78624. * @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.
  78625. */
  78626. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  78627. if (this._standingMatrix) {
  78628. // Add standing matrix offset to get real offset from ground in room
  78629. this._standingMatrix.getTranslationToRef(this._workingVector);
  78630. return this._deviceRoomPosition.y + this._workingVector.y;
  78631. }
  78632. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  78633. return this._defaultHeight || 0;
  78634. };
  78635. /**
  78636. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78637. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  78638. */
  78639. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  78640. var _this = this;
  78641. if (callback === void 0) { callback = function (bool) { }; }
  78642. // Use standing matrix if available
  78643. this.getEngine().initWebVRAsync().then(function (result) {
  78644. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  78645. callback(false);
  78646. }
  78647. else {
  78648. _this._standingMatrix = new BABYLON.Matrix();
  78649. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  78650. if (!_this.getScene().useRightHandedSystem) {
  78651. [2, 6, 8, 9, 14].forEach(function (num) {
  78652. if (_this._standingMatrix) {
  78653. _this._standingMatrix.m[num] *= -1;
  78654. }
  78655. });
  78656. }
  78657. callback(true);
  78658. }
  78659. });
  78660. };
  78661. /**
  78662. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  78663. * @returns A promise with a boolean set to if the standing matrix is supported.
  78664. */
  78665. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  78666. var _this = this;
  78667. return new Promise(function (res, rej) {
  78668. _this.useStandingMatrix(function (supported) {
  78669. res(supported);
  78670. });
  78671. });
  78672. };
  78673. /**
  78674. * Disposes the camera
  78675. */
  78676. WebVRFreeCamera.prototype.dispose = function () {
  78677. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  78678. _super.prototype.dispose.call(this);
  78679. };
  78680. /**
  78681. * Gets a vrController by name.
  78682. * @param name The name of the controller to retreive
  78683. * @returns the controller matching the name specified or null if not found
  78684. */
  78685. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  78686. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  78687. var gp = _a[_i];
  78688. if (gp.hand === name) {
  78689. return gp;
  78690. }
  78691. }
  78692. return null;
  78693. };
  78694. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  78695. /**
  78696. * The controller corrisponding to the users left hand.
  78697. */
  78698. get: function () {
  78699. if (!this._leftController) {
  78700. this._leftController = this.getControllerByName("left");
  78701. }
  78702. return this._leftController;
  78703. },
  78704. enumerable: true,
  78705. configurable: true
  78706. });
  78707. ;
  78708. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  78709. /**
  78710. * The controller corrisponding to the users right hand.
  78711. */
  78712. get: function () {
  78713. if (!this._rightController) {
  78714. this._rightController = this.getControllerByName("right");
  78715. }
  78716. return this._rightController;
  78717. },
  78718. enumerable: true,
  78719. configurable: true
  78720. });
  78721. ;
  78722. /**
  78723. * Casts a ray forward from the vrCamera's gaze.
  78724. * @param length Length of the ray (default: 100)
  78725. * @returns the ray corrisponding to the gaze
  78726. */
  78727. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  78728. if (length === void 0) { length = 100; }
  78729. if (this.leftCamera) {
  78730. // Use left eye to avoid computation to compute center on every call
  78731. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  78732. }
  78733. else {
  78734. return _super.prototype.getForwardRay.call(this, length);
  78735. }
  78736. };
  78737. /**
  78738. * Updates the camera based on device's frame data
  78739. */
  78740. WebVRFreeCamera.prototype._checkInputs = function () {
  78741. if (this._vrDevice && this._vrDevice.isPresenting) {
  78742. this._vrDevice.getFrameData(this._frameData);
  78743. this.updateFromDevice(this._frameData.pose);
  78744. }
  78745. _super.prototype._checkInputs.call(this);
  78746. };
  78747. /**
  78748. * Updates the poseControlled values based on the input device pose.
  78749. * @param poseData Pose coming from the device
  78750. */
  78751. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  78752. if (poseData && poseData.orientation) {
  78753. this.rawPose = poseData;
  78754. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  78755. if (this.getScene().useRightHandedSystem) {
  78756. this._deviceRoomRotationQuaternion.z *= -1;
  78757. this._deviceRoomRotationQuaternion.w *= -1;
  78758. }
  78759. if (this.webVROptions.trackPosition && this.rawPose.position) {
  78760. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  78761. if (this.getScene().useRightHandedSystem) {
  78762. this._deviceRoomPosition.z *= -1;
  78763. }
  78764. }
  78765. }
  78766. };
  78767. /**
  78768. * WebVR's attach control will start broadcasting frames to the device.
  78769. * Note that in certain browsers (chrome for example) this function must be called
  78770. * within a user-interaction callback. Example:
  78771. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  78772. *
  78773. * @param element html element to attach the vrDevice to
  78774. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  78775. */
  78776. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  78777. _super.prototype.attachControl.call(this, element, noPreventDefault);
  78778. this._attached = true;
  78779. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  78780. if (this._vrDevice) {
  78781. this.getEngine().enableVR();
  78782. }
  78783. };
  78784. /**
  78785. * Detaches the camera from the html element and disables VR
  78786. *
  78787. * @param element html element to detach from
  78788. */
  78789. WebVRFreeCamera.prototype.detachControl = function (element) {
  78790. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  78791. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  78792. _super.prototype.detachControl.call(this, element);
  78793. this._attached = false;
  78794. this.getEngine().disableVR();
  78795. };
  78796. /**
  78797. * @returns the name of this class
  78798. */
  78799. WebVRFreeCamera.prototype.getClassName = function () {
  78800. return "WebVRFreeCamera";
  78801. };
  78802. /**
  78803. * Calls resetPose on the vrDisplay
  78804. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  78805. */
  78806. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  78807. //uses the vrDisplay's "resetPose()".
  78808. //pitch and roll won't be affected.
  78809. this._vrDevice.resetPose();
  78810. };
  78811. /**
  78812. * Updates the rig cameras (left and right eye)
  78813. */
  78814. WebVRFreeCamera.prototype._updateRigCameras = function () {
  78815. var camLeft = this._rigCameras[0];
  78816. var camRight = this._rigCameras[1];
  78817. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78818. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  78819. camLeft.position.copyFrom(this._deviceRoomPosition);
  78820. camRight.position.copyFrom(this._deviceRoomPosition);
  78821. };
  78822. /**
  78823. * Updates the cached values of the camera
  78824. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  78825. */
  78826. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  78827. var _this = this;
  78828. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  78829. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  78830. if (!this.updateCacheCalled) {
  78831. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  78832. this.updateCacheCalled = true;
  78833. this.update();
  78834. }
  78835. // Set working vector to the device position in room space rotated by the new rotation
  78836. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  78837. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  78838. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  78839. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  78840. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  78841. // Add translation from anchor position
  78842. this._deviceToWorld.getTranslationToRef(this._workingVector);
  78843. this._workingVector.addInPlace(this.position);
  78844. this._workingVector.subtractInPlace(this._cache.position);
  78845. this._deviceToWorld.setTranslation(this._workingVector);
  78846. // Set an inverted matrix to be used when updating the camera
  78847. this._deviceToWorld.invertToRef(this._worldToDevice);
  78848. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  78849. this.controllers.forEach(function (controller) {
  78850. controller._deviceToWorld = _this._deviceToWorld;
  78851. controller.update();
  78852. });
  78853. }
  78854. if (!ignoreParentClass) {
  78855. _super.prototype._updateCache.call(this);
  78856. }
  78857. this.updateCacheCalled = false;
  78858. };
  78859. /**
  78860. * Updates the current device position and rotation in the babylon world
  78861. */
  78862. WebVRFreeCamera.prototype.update = function () {
  78863. // Get current device position in babylon world
  78864. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  78865. // Get current device rotation in babylon world
  78866. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  78867. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  78868. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  78869. _super.prototype.update.call(this);
  78870. };
  78871. /**
  78872. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  78873. * @returns an identity matrix
  78874. */
  78875. WebVRFreeCamera.prototype._getViewMatrix = function () {
  78876. return BABYLON.Matrix.Identity();
  78877. };
  78878. /**
  78879. * This function is called by the two RIG cameras.
  78880. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  78881. */
  78882. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  78883. var _this = this;
  78884. //WebVR 1.1
  78885. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  78886. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  78887. if (!this.getScene().useRightHandedSystem) {
  78888. [2, 6, 8, 9, 14].forEach(function (num) {
  78889. _this._webvrViewMatrix.m[num] *= -1;
  78890. });
  78891. }
  78892. // update the camera rotation matrix
  78893. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  78894. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  78895. // Computing target and final matrix
  78896. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  78897. var parentCamera = this._cameraRigParams["parentCamera"];
  78898. // should the view matrix be updated with scale and position offset?
  78899. if (parentCamera.deviceScaleFactor !== 1) {
  78900. this._webvrViewMatrix.invert();
  78901. // scale the position, if set
  78902. if (parentCamera.deviceScaleFactor) {
  78903. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  78904. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  78905. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  78906. }
  78907. this._webvrViewMatrix.invert();
  78908. }
  78909. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  78910. return this._webvrViewMatrix;
  78911. };
  78912. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  78913. var _this = this;
  78914. var parentCamera = this.parent;
  78915. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  78916. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  78917. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  78918. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  78919. //babylon compatible matrix
  78920. if (!this.getScene().useRightHandedSystem) {
  78921. [8, 9, 10, 11].forEach(function (num) {
  78922. _this._projectionMatrix.m[num] *= -1;
  78923. });
  78924. }
  78925. return this._projectionMatrix;
  78926. };
  78927. /**
  78928. * Initializes the controllers and their meshes
  78929. */
  78930. WebVRFreeCamera.prototype.initControllers = function () {
  78931. var _this = this;
  78932. this.controllers = [];
  78933. var manager = this.getScene().gamepadManager;
  78934. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  78935. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78936. var webVrController = gamepad;
  78937. if (webVrController.defaultModel) {
  78938. webVrController.defaultModel.setEnabled(false);
  78939. }
  78940. if (webVrController.hand === "right") {
  78941. _this._rightController = null;
  78942. }
  78943. if (webVrController.hand === "left") {
  78944. _this._rightController = null;
  78945. }
  78946. var controllerIndex = _this.controllers.indexOf(webVrController);
  78947. if (controllerIndex !== -1) {
  78948. _this.controllers.splice(controllerIndex, 1);
  78949. }
  78950. }
  78951. });
  78952. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  78953. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  78954. var webVrController_1 = gamepad;
  78955. webVrController_1._deviceToWorld = _this._deviceToWorld;
  78956. if (_this.webVROptions.controllerMeshes) {
  78957. if (webVrController_1.defaultModel) {
  78958. webVrController_1.defaultModel.setEnabled(true);
  78959. }
  78960. else {
  78961. // Load the meshes
  78962. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  78963. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  78964. if (_this.webVROptions.defaultLightingOnControllers) {
  78965. if (!_this._lightOnControllers) {
  78966. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  78967. }
  78968. var activateLightOnSubMeshes_1 = function (mesh, light) {
  78969. var children = mesh.getChildren();
  78970. if (children.length !== 0) {
  78971. children.forEach(function (mesh) {
  78972. light.includedOnlyMeshes.push(mesh);
  78973. activateLightOnSubMeshes_1(mesh, light);
  78974. });
  78975. }
  78976. };
  78977. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  78978. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  78979. }
  78980. });
  78981. }
  78982. }
  78983. webVrController_1.attachToPoseControlledCamera(_this);
  78984. // since this is async - sanity check. Is the controller already stored?
  78985. if (_this.controllers.indexOf(webVrController_1) === -1) {
  78986. //add to the controllers array
  78987. _this.controllers.push(webVrController_1);
  78988. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  78989. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  78990. // So we're overriding setting left & right manually to be sure
  78991. var firstViveWandDetected = false;
  78992. for (var i = 0; i < _this.controllers.length; i++) {
  78993. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  78994. if (!firstViveWandDetected) {
  78995. firstViveWandDetected = true;
  78996. _this.controllers[i].hand = "left";
  78997. }
  78998. else {
  78999. _this.controllers[i].hand = "right";
  79000. }
  79001. }
  79002. }
  79003. //did we find enough controllers? Great! let the developer know.
  79004. if (_this.controllers.length >= 2) {
  79005. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79006. }
  79007. }
  79008. }
  79009. });
  79010. };
  79011. return WebVRFreeCamera;
  79012. }(BABYLON.FreeCamera));
  79013. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79014. })(BABYLON || (BABYLON = {}));
  79015. //# sourceMappingURL=babylon.webVRCamera.js.map
  79016. var BABYLON;
  79017. (function (BABYLON) {
  79018. // We're mainly based on the logic defined into the FreeCamera code
  79019. /**
  79020. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79021. * being tilted forward or back and left or right.
  79022. */
  79023. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79024. __extends(DeviceOrientationCamera, _super);
  79025. /**
  79026. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79027. * @param name The name of the camera
  79028. * @param position The start position camera
  79029. * @param scene The scene the camera belongs to
  79030. */
  79031. function DeviceOrientationCamera(name, position, scene) {
  79032. var _this = _super.call(this, name, position, scene) || this;
  79033. _this._quaternionCache = new BABYLON.Quaternion();
  79034. _this.inputs.addDeviceOrientation();
  79035. return _this;
  79036. }
  79037. /**
  79038. * Gets the current instance class name ("DeviceOrientationCamera").
  79039. * This helps avoiding instanceof at run time.
  79040. * @returns the class name
  79041. */
  79042. DeviceOrientationCamera.prototype.getClassName = function () {
  79043. return "DeviceOrientationCamera";
  79044. };
  79045. /**
  79046. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79047. */
  79048. DeviceOrientationCamera.prototype._checkInputs = function () {
  79049. _super.prototype._checkInputs.call(this);
  79050. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79051. if (this._initialQuaternion) {
  79052. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79053. }
  79054. };
  79055. /**
  79056. * Reset the camera to its default orientation on the specified axis only.
  79057. * @param axis The axis to reset
  79058. */
  79059. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79060. var _this = this;
  79061. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79062. //can only work if this camera has a rotation quaternion already.
  79063. if (!this.rotationQuaternion)
  79064. return;
  79065. if (!this._initialQuaternion) {
  79066. this._initialQuaternion = new BABYLON.Quaternion();
  79067. }
  79068. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79069. ['x', 'y', 'z'].forEach(function (axisName) {
  79070. if (!axis[axisName]) {
  79071. _this._initialQuaternion[axisName] = 0;
  79072. }
  79073. else {
  79074. _this._initialQuaternion[axisName] *= -1;
  79075. }
  79076. });
  79077. this._initialQuaternion.normalize();
  79078. //force rotation update
  79079. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79080. };
  79081. return DeviceOrientationCamera;
  79082. }(BABYLON.FreeCamera));
  79083. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79084. })(BABYLON || (BABYLON = {}));
  79085. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79086. var BABYLON;
  79087. (function (BABYLON) {
  79088. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79089. __extends(VRDeviceOrientationFreeCamera, _super);
  79090. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79091. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79092. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79093. var _this = _super.call(this, name, position, scene) || this;
  79094. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79095. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79096. return _this;
  79097. }
  79098. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79099. return "VRDeviceOrientationFreeCamera";
  79100. };
  79101. return VRDeviceOrientationFreeCamera;
  79102. }(BABYLON.DeviceOrientationCamera));
  79103. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79104. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79105. __extends(VRDeviceOrientationGamepadCamera, _super);
  79106. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79107. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79108. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79109. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79110. _this.inputs.addGamepad();
  79111. return _this;
  79112. }
  79113. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79114. return "VRDeviceOrientationGamepadCamera";
  79115. };
  79116. return VRDeviceOrientationGamepadCamera;
  79117. }(VRDeviceOrientationFreeCamera));
  79118. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79119. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79120. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79121. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79122. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79123. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79124. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79125. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79126. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79127. _this.inputs.addVRDeviceOrientation();
  79128. return _this;
  79129. }
  79130. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79131. return "VRDeviceOrientationArcRotateCamera";
  79132. };
  79133. return VRDeviceOrientationArcRotateCamera;
  79134. }(BABYLON.ArcRotateCamera));
  79135. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79136. })(BABYLON || (BABYLON = {}));
  79137. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79138. var BABYLON;
  79139. (function (BABYLON) {
  79140. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79141. __extends(AnaglyphFreeCamera, _super);
  79142. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79143. var _this = _super.call(this, name, position, scene) || this;
  79144. _this.interaxialDistance = interaxialDistance;
  79145. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79146. return _this;
  79147. }
  79148. AnaglyphFreeCamera.prototype.getClassName = function () {
  79149. return "AnaglyphFreeCamera";
  79150. };
  79151. return AnaglyphFreeCamera;
  79152. }(BABYLON.FreeCamera));
  79153. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79154. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79155. __extends(AnaglyphArcRotateCamera, _super);
  79156. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79157. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79158. _this.interaxialDistance = interaxialDistance;
  79159. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79160. return _this;
  79161. }
  79162. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79163. return "AnaglyphArcRotateCamera";
  79164. };
  79165. return AnaglyphArcRotateCamera;
  79166. }(BABYLON.ArcRotateCamera));
  79167. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79168. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79169. __extends(AnaglyphGamepadCamera, _super);
  79170. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79171. var _this = _super.call(this, name, position, scene) || this;
  79172. _this.interaxialDistance = interaxialDistance;
  79173. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79174. return _this;
  79175. }
  79176. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79177. return "AnaglyphGamepadCamera";
  79178. };
  79179. return AnaglyphGamepadCamera;
  79180. }(BABYLON.GamepadCamera));
  79181. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79182. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79183. __extends(AnaglyphUniversalCamera, _super);
  79184. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79185. var _this = _super.call(this, name, position, scene) || this;
  79186. _this.interaxialDistance = interaxialDistance;
  79187. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79188. return _this;
  79189. }
  79190. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79191. return "AnaglyphUniversalCamera";
  79192. };
  79193. return AnaglyphUniversalCamera;
  79194. }(BABYLON.UniversalCamera));
  79195. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79196. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79197. __extends(StereoscopicFreeCamera, _super);
  79198. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79199. var _this = _super.call(this, name, position, scene) || this;
  79200. _this.interaxialDistance = interaxialDistance;
  79201. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79202. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79203. return _this;
  79204. }
  79205. StereoscopicFreeCamera.prototype.getClassName = function () {
  79206. return "StereoscopicFreeCamera";
  79207. };
  79208. return StereoscopicFreeCamera;
  79209. }(BABYLON.FreeCamera));
  79210. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79211. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79212. __extends(StereoscopicArcRotateCamera, _super);
  79213. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79214. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79215. _this.interaxialDistance = interaxialDistance;
  79216. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79217. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79218. return _this;
  79219. }
  79220. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79221. return "StereoscopicArcRotateCamera";
  79222. };
  79223. return StereoscopicArcRotateCamera;
  79224. }(BABYLON.ArcRotateCamera));
  79225. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79226. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79227. __extends(StereoscopicGamepadCamera, _super);
  79228. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79229. var _this = _super.call(this, name, position, scene) || this;
  79230. _this.interaxialDistance = interaxialDistance;
  79231. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79232. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79233. return _this;
  79234. }
  79235. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79236. return "StereoscopicGamepadCamera";
  79237. };
  79238. return StereoscopicGamepadCamera;
  79239. }(BABYLON.GamepadCamera));
  79240. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79241. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79242. __extends(StereoscopicUniversalCamera, _super);
  79243. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79244. var _this = _super.call(this, name, position, scene) || this;
  79245. _this.interaxialDistance = interaxialDistance;
  79246. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79247. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79248. return _this;
  79249. }
  79250. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79251. return "StereoscopicUniversalCamera";
  79252. };
  79253. return StereoscopicUniversalCamera;
  79254. }(BABYLON.UniversalCamera));
  79255. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79256. })(BABYLON || (BABYLON = {}));
  79257. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79258. var BABYLON;
  79259. (function (BABYLON) {
  79260. /**
  79261. * Helps to quickly add VR support to an existing scene.
  79262. * See http://doc.babylonjs.com/how_to/webvr_helper
  79263. */
  79264. var VRExperienceHelper = /** @class */ (function () {
  79265. /**
  79266. * Instantiates a VRExperienceHelper.
  79267. * Helps to quickly add VR support to an existing scene.
  79268. * @param scene The scene the VRExperienceHelper belongs to.
  79269. * @param webVROptions Options to modify the vr experience helper's behavior.
  79270. */
  79271. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  79272. if (webVROptions === void 0) { webVROptions = {}; }
  79273. var _this = this;
  79274. this.webVROptions = webVROptions;
  79275. // Can the system support WebVR, even if a headset isn't plugged in?
  79276. this._webVRsupported = false;
  79277. // If WebVR is supported, is a headset plugged in and are we ready to present?
  79278. this._webVRready = false;
  79279. // Are we waiting for the requestPresent callback to complete?
  79280. this._webVRrequesting = false;
  79281. // Are we presenting to the headset right now?
  79282. this._webVRpresenting = false;
  79283. // Are we presenting in the fullscreen fallback?
  79284. this._fullscreenVRpresenting = false;
  79285. /**
  79286. * Observable raised when entering VR.
  79287. */
  79288. this.onEnteringVRObservable = new BABYLON.Observable();
  79289. /**
  79290. * Observable raised when exiting VR.
  79291. */
  79292. this.onExitingVRObservable = new BABYLON.Observable();
  79293. /**
  79294. * Observable raised when controller mesh is loaded.
  79295. */
  79296. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79297. this._useCustomVRButton = false;
  79298. this._teleportationRequested = false;
  79299. this._teleportationEnabledOnLeftController = false;
  79300. this._teleportationEnabledOnRightController = false;
  79301. this._interactionsEnabledOnLeftController = false;
  79302. this._interactionsEnabledOnRightController = false;
  79303. this._leftControllerReady = false;
  79304. this._rightControllerReady = false;
  79305. this._floorMeshesCollection = [];
  79306. this._teleportationAllowed = false;
  79307. this._rotationAllowed = true;
  79308. this._teleportationRequestInitiated = false;
  79309. this._teleportationBackRequestInitiated = false;
  79310. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  79311. this._rotationRightAsked = false;
  79312. this._rotationLeftAsked = false;
  79313. this._isDefaultTeleportationTarget = true;
  79314. this._teleportationFillColor = "#444444";
  79315. this._teleportationBorderColor = "#FFFFFF";
  79316. this._rotationAngle = 0;
  79317. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  79318. this._padSensibilityUp = 0.65;
  79319. this._padSensibilityDown = 0.35;
  79320. /**
  79321. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  79322. */
  79323. this.onNewMeshSelected = new BABYLON.Observable();
  79324. /**
  79325. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  79326. */
  79327. this.onNewMeshPicked = new BABYLON.Observable();
  79328. /**
  79329. * Observable raised before camera teleportation
  79330. */
  79331. this.onBeforeCameraTeleport = new BABYLON.Observable();
  79332. /**
  79333. * Observable raised after camera teleportation
  79334. */
  79335. this.onAfterCameraTeleport = new BABYLON.Observable();
  79336. /**
  79337. * Observable raised when current selected mesh gets unselected
  79338. */
  79339. this.onSelectedMeshUnselected = new BABYLON.Observable();
  79340. /**
  79341. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  79342. */
  79343. this.teleportationEnabled = true;
  79344. this._pointerDownOnMeshAsked = false;
  79345. this._isActionableMesh = false;
  79346. this._teleportationInitialized = false;
  79347. this._interactionsEnabled = false;
  79348. this._interactionsRequested = false;
  79349. this._displayGaze = true;
  79350. this._displayLaserPointer = true;
  79351. this._dpadPressed = true;
  79352. this._onResize = function () {
  79353. _this.moveButtonToBottomRight();
  79354. if (_this._fullscreenVRpresenting && _this._webVRready) {
  79355. _this.exitVR();
  79356. }
  79357. };
  79358. this._onFullscreenChange = function () {
  79359. if (document.fullscreen !== undefined) {
  79360. _this._fullscreenVRpresenting = document.fullscreen;
  79361. }
  79362. else if (document.mozFullScreen !== undefined) {
  79363. _this._fullscreenVRpresenting = document.mozFullScreen;
  79364. }
  79365. else if (document.webkitIsFullScreen !== undefined) {
  79366. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  79367. }
  79368. else if (document.msIsFullScreen !== undefined) {
  79369. _this._fullscreenVRpresenting = document.msIsFullScreen;
  79370. }
  79371. if (!_this._fullscreenVRpresenting && _this._canvas) {
  79372. _this.exitVR();
  79373. if (!_this._useCustomVRButton) {
  79374. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  79375. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  79376. }
  79377. }
  79378. };
  79379. this.beforeRender = function () {
  79380. _this._castRayAndSelectObject();
  79381. };
  79382. this._onNewGamepadConnected = function (gamepad) {
  79383. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79384. if (gamepad.leftStick) {
  79385. gamepad.onleftstickchanged(function (stickValues) {
  79386. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  79387. // Listening to classic/xbox gamepad only if no VR controller is active
  79388. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  79389. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  79390. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  79391. _this._checkTeleportWithRay(stickValues);
  79392. _this._checkTeleportBackwards(stickValues);
  79393. }
  79394. }
  79395. });
  79396. }
  79397. if (gamepad.rightStick) {
  79398. gamepad.onrightstickchanged(function (stickValues) {
  79399. if (_this._teleportationInitialized) {
  79400. _this._checkRotate(stickValues);
  79401. }
  79402. });
  79403. }
  79404. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  79405. gamepad.onbuttondown(function (buttonPressed) {
  79406. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79407. _this._selectionPointerDown();
  79408. }
  79409. });
  79410. gamepad.onbuttonup(function (buttonPressed) {
  79411. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79412. _this._selectionPointerUp();
  79413. }
  79414. });
  79415. }
  79416. }
  79417. else {
  79418. var webVRController = gamepad;
  79419. _this._tryEnableInteractionOnController(webVRController);
  79420. }
  79421. };
  79422. // 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
  79423. this._tryEnableInteractionOnController = function (webVRController) {
  79424. if (webVRController.hand === "left") {
  79425. _this._leftControllerReady = true;
  79426. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  79427. _this._enableInteractionOnController(webVRController);
  79428. }
  79429. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  79430. _this._enableTeleportationOnController(webVRController);
  79431. }
  79432. }
  79433. if (webVRController.hand === "right") {
  79434. _this._rightControllerReady = true;
  79435. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  79436. _this._enableInteractionOnController(webVRController);
  79437. }
  79438. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  79439. _this._enableTeleportationOnController(webVRController);
  79440. }
  79441. }
  79442. };
  79443. this._onNewGamepadDisconnected = function (gamepad) {
  79444. if (gamepad instanceof BABYLON.WebVRController) {
  79445. if (gamepad.hand === "left") {
  79446. _this._interactionsEnabledOnLeftController = false;
  79447. _this._teleportationEnabledOnLeftController = false;
  79448. _this._leftControllerReady = false;
  79449. if (_this._leftLaserPointer) {
  79450. _this._leftLaserPointer.dispose();
  79451. }
  79452. }
  79453. if (gamepad.hand === "right") {
  79454. _this._interactionsEnabledOnRightController = false;
  79455. _this._teleportationEnabledOnRightController = false;
  79456. _this._rightControllerReady = false;
  79457. if (_this._rightLaserPointer) {
  79458. _this._rightLaserPointer.dispose();
  79459. }
  79460. }
  79461. }
  79462. };
  79463. this._workingVector = BABYLON.Vector3.Zero();
  79464. this._workingQuaternion = BABYLON.Quaternion.Identity();
  79465. this._workingMatrix = BABYLON.Matrix.Identity();
  79466. this._scene = scene;
  79467. this._canvas = scene.getEngine().getRenderingCanvas();
  79468. // Parse options
  79469. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  79470. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  79471. }
  79472. if (webVROptions.createDeviceOrientationCamera === undefined) {
  79473. webVROptions.createDeviceOrientationCamera = true;
  79474. }
  79475. if (webVROptions.defaultHeight === undefined) {
  79476. webVROptions.defaultHeight = 1.7;
  79477. }
  79478. if (webVROptions.useCustomVRButton) {
  79479. this._useCustomVRButton = true;
  79480. if (webVROptions.customVRButton) {
  79481. this._btnVR = webVROptions.customVRButton;
  79482. }
  79483. }
  79484. if (webVROptions.rayLength) {
  79485. this._rayLength = webVROptions.rayLength;
  79486. }
  79487. this._defaultHeight = webVROptions.defaultHeight;
  79488. // Set position
  79489. if (this._scene.activeCamera) {
  79490. this._position = this._scene.activeCamera.position.clone();
  79491. }
  79492. else {
  79493. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  79494. }
  79495. // Set non-vr camera
  79496. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  79497. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  79498. // Copy data from existing camera
  79499. if (this._scene.activeCamera) {
  79500. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  79501. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  79502. // Set rotation from previous camera
  79503. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  79504. var targetCamera = this._scene.activeCamera;
  79505. if (targetCamera.rotationQuaternion) {
  79506. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  79507. }
  79508. else {
  79509. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  79510. }
  79511. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  79512. }
  79513. }
  79514. this._scene.activeCamera = this._deviceOrientationCamera;
  79515. if (this._canvas) {
  79516. this._scene.activeCamera.attachControl(this._canvas);
  79517. }
  79518. }
  79519. else {
  79520. this._existingCamera = this._scene.activeCamera;
  79521. }
  79522. // Create VR cameras
  79523. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79524. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  79525. }
  79526. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  79527. this._webVRCamera.useStandingMatrix();
  79528. // Create default button
  79529. if (!this._useCustomVRButton) {
  79530. this._btnVR = document.createElement("BUTTON");
  79531. this._btnVR.className = "babylonVRicon";
  79532. this._btnVR.id = "babylonVRiconbtn";
  79533. this._btnVR.title = "Click to switch to VR";
  79534. 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) }";
  79535. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  79536. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  79537. // css += ".babylonVRicon.vrdisplaysupported { }";
  79538. // css += ".babylonVRicon.vrdisplayready { }";
  79539. // css += ".babylonVRicon.vrdisplayrequesting { }";
  79540. var style = document.createElement('style');
  79541. style.appendChild(document.createTextNode(css));
  79542. document.getElementsByTagName('head')[0].appendChild(style);
  79543. this.moveButtonToBottomRight();
  79544. }
  79545. // VR button click event
  79546. if (this._btnVR) {
  79547. this._btnVR.addEventListener("click", function () {
  79548. if (!_this.isInVRMode) {
  79549. _this.enterVR();
  79550. }
  79551. else {
  79552. _this.exitVR();
  79553. }
  79554. });
  79555. }
  79556. // Window events
  79557. window.addEventListener("resize", this._onResize);
  79558. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  79559. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  79560. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  79561. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  79562. // Display vr button when headset is connected
  79563. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  79564. this.displayVRButton();
  79565. }
  79566. else {
  79567. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  79568. if (e.vrDisplay) {
  79569. _this.displayVRButton();
  79570. }
  79571. });
  79572. }
  79573. // Exiting VR mode using 'ESC' key on desktop
  79574. this._onKeyDown = function (event) {
  79575. if (event.keyCode === 27 && _this.isInVRMode) {
  79576. _this.exitVR();
  79577. }
  79578. };
  79579. document.addEventListener("keydown", this._onKeyDown);
  79580. // Exiting VR mode double tapping the touch screen
  79581. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  79582. if (_this.isInVRMode) {
  79583. _this.exitVR();
  79584. if (_this._fullscreenVRpresenting) {
  79585. _this._scene.getEngine().switchFullscreen(true);
  79586. }
  79587. }
  79588. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  79589. // Listen for WebVR display changes
  79590. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  79591. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  79592. this._onVRRequestPresentStart = function () {
  79593. _this._webVRrequesting = true;
  79594. _this.updateButtonVisibility();
  79595. };
  79596. this._onVRRequestPresentComplete = function (success) {
  79597. _this._webVRrequesting = false;
  79598. _this.updateButtonVisibility();
  79599. };
  79600. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  79601. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  79602. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  79603. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  79604. scene.onDisposeObservable.add(function () {
  79605. _this.dispose();
  79606. });
  79607. // Gamepad connection events
  79608. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  79609. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  79610. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  79611. this.updateButtonVisibility();
  79612. //create easing functions
  79613. this._circleEase = new BABYLON.CircleEase();
  79614. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  79615. }
  79616. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  79617. /** Return this.onEnteringVRObservable
  79618. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  79619. */
  79620. get: function () {
  79621. return this.onEnteringVRObservable;
  79622. },
  79623. enumerable: true,
  79624. configurable: true
  79625. });
  79626. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  79627. /** Return this.onExitingVRObservable
  79628. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  79629. */
  79630. get: function () {
  79631. return this.onExitingVRObservable;
  79632. },
  79633. enumerable: true,
  79634. configurable: true
  79635. });
  79636. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  79637. /** Return this.onControllerMeshLoadedObservable
  79638. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  79639. */
  79640. get: function () {
  79641. return this.onControllerMeshLoadedObservable;
  79642. },
  79643. enumerable: true,
  79644. configurable: true
  79645. });
  79646. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  79647. /**
  79648. * The mesh used to display where the user is going to teleport.
  79649. */
  79650. get: function () {
  79651. return this._teleportationTarget;
  79652. },
  79653. /**
  79654. * Sets the mesh to be used to display where the user is going to teleport.
  79655. */
  79656. set: function (value) {
  79657. if (value) {
  79658. value.name = "teleportationTarget";
  79659. this._isDefaultTeleportationTarget = false;
  79660. this._teleportationTarget = value;
  79661. }
  79662. },
  79663. enumerable: true,
  79664. configurable: true
  79665. });
  79666. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  79667. /**
  79668. * The mesh used to display where the user is selecting,
  79669. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  79670. * See http://doc.babylonjs.com/resources/baking_transformations
  79671. */
  79672. get: function () {
  79673. return this._gazeTracker;
  79674. },
  79675. set: function (value) {
  79676. if (value) {
  79677. this._gazeTracker = value;
  79678. this._gazeTracker.bakeCurrentTransformIntoVertices();
  79679. this._gazeTracker.isPickable = false;
  79680. this._gazeTracker.isVisible = false;
  79681. }
  79682. },
  79683. enumerable: true,
  79684. configurable: true
  79685. });
  79686. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  79687. /**
  79688. * If the ray of the gaze should be displayed.
  79689. */
  79690. get: function () {
  79691. return this._displayGaze;
  79692. },
  79693. /**
  79694. * Sets if the ray of the gaze should be displayed.
  79695. */
  79696. set: function (value) {
  79697. this._displayGaze = value;
  79698. if (!value) {
  79699. this._gazeTracker.isVisible = false;
  79700. }
  79701. },
  79702. enumerable: true,
  79703. configurable: true
  79704. });
  79705. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  79706. /**
  79707. * If the ray of the LaserPointer should be displayed.
  79708. */
  79709. get: function () {
  79710. return this._displayLaserPointer;
  79711. },
  79712. /**
  79713. * Sets if the ray of the LaserPointer should be displayed.
  79714. */
  79715. set: function (value) {
  79716. this._displayLaserPointer = value;
  79717. if (!value) {
  79718. if (this._rightLaserPointer) {
  79719. this._rightLaserPointer.isVisible = false;
  79720. }
  79721. if (this._leftLaserPointer) {
  79722. this._leftLaserPointer.isVisible = false;
  79723. }
  79724. }
  79725. else {
  79726. if (this._rightLaserPointer) {
  79727. this._rightLaserPointer.isVisible = true;
  79728. }
  79729. else if (this._leftLaserPointer) {
  79730. this._leftLaserPointer.isVisible = true;
  79731. }
  79732. }
  79733. },
  79734. enumerable: true,
  79735. configurable: true
  79736. });
  79737. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  79738. /**
  79739. * The deviceOrientationCamera used as the camera when not in VR.
  79740. */
  79741. get: function () {
  79742. return this._deviceOrientationCamera;
  79743. },
  79744. enumerable: true,
  79745. configurable: true
  79746. });
  79747. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  79748. /**
  79749. * Based on the current WebVR support, returns the current VR camera used.
  79750. */
  79751. get: function () {
  79752. if (this._webVRready) {
  79753. return this._webVRCamera;
  79754. }
  79755. else {
  79756. return this._scene.activeCamera;
  79757. }
  79758. },
  79759. enumerable: true,
  79760. configurable: true
  79761. });
  79762. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  79763. /**
  79764. * The webVRCamera which is used when in VR.
  79765. */
  79766. get: function () {
  79767. return this._webVRCamera;
  79768. },
  79769. enumerable: true,
  79770. configurable: true
  79771. });
  79772. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  79773. /**
  79774. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  79775. */
  79776. get: function () {
  79777. return this._vrDeviceOrientationCamera;
  79778. },
  79779. enumerable: true,
  79780. configurable: true
  79781. });
  79782. // Raised when one of the controller has loaded successfully its associated default mesh
  79783. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  79784. this._tryEnableInteractionOnController(webVRController);
  79785. try {
  79786. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  79787. }
  79788. catch (err) {
  79789. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  79790. }
  79791. };
  79792. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  79793. /**
  79794. * Gets a value indicating if we are currently in VR mode.
  79795. */
  79796. get: function () {
  79797. return this._webVRpresenting || this._fullscreenVRpresenting;
  79798. },
  79799. enumerable: true,
  79800. configurable: true
  79801. });
  79802. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  79803. var vrDisplay = this._scene.getEngine().getVRDevice();
  79804. if (vrDisplay) {
  79805. var wasPresenting = this._webVRpresenting;
  79806. // A VR display is connected
  79807. this._webVRpresenting = vrDisplay.isPresenting;
  79808. if (wasPresenting && !this._webVRpresenting)
  79809. this.exitVR();
  79810. }
  79811. else {
  79812. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  79813. }
  79814. this.updateButtonVisibility();
  79815. };
  79816. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  79817. this._webVRsupported = eventArgs.vrSupported;
  79818. this._webVRready = !!eventArgs.vrDisplay;
  79819. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  79820. this.updateButtonVisibility();
  79821. };
  79822. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  79823. if (this._canvas && !this._useCustomVRButton) {
  79824. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  79825. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  79826. }
  79827. };
  79828. VRExperienceHelper.prototype.displayVRButton = function () {
  79829. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  79830. document.body.appendChild(this._btnVR);
  79831. this._btnVRDisplayed = true;
  79832. }
  79833. };
  79834. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  79835. if (!this._btnVR || this._useCustomVRButton) {
  79836. return;
  79837. }
  79838. this._btnVR.className = "babylonVRicon";
  79839. if (this.isInVRMode) {
  79840. this._btnVR.className += " vrdisplaypresenting";
  79841. }
  79842. else {
  79843. if (this._webVRready)
  79844. this._btnVR.className += " vrdisplayready";
  79845. if (this._webVRsupported)
  79846. this._btnVR.className += " vrdisplaysupported";
  79847. if (this._webVRrequesting)
  79848. this._btnVR.className += " vrdisplayrequesting";
  79849. }
  79850. };
  79851. /**
  79852. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  79853. * Otherwise, will use the fullscreen API.
  79854. */
  79855. VRExperienceHelper.prototype.enterVR = function () {
  79856. if (this.onEnteringVRObservable) {
  79857. try {
  79858. this.onEnteringVRObservable.notifyObservers(this);
  79859. }
  79860. catch (err) {
  79861. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  79862. }
  79863. }
  79864. if (this._scene.activeCamera) {
  79865. this._position = this._scene.activeCamera.position.clone();
  79866. // make sure that we return to the last active camera
  79867. this._existingCamera = this._scene.activeCamera;
  79868. }
  79869. if (this._webVRrequesting)
  79870. return;
  79871. // If WebVR is supported and a headset is connected
  79872. if (this._webVRready) {
  79873. if (!this._webVRpresenting) {
  79874. this._webVRCamera.position = this._position;
  79875. this._scene.activeCamera = this._webVRCamera;
  79876. }
  79877. }
  79878. else if (this._vrDeviceOrientationCamera) {
  79879. this._vrDeviceOrientationCamera.position = this._position;
  79880. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  79881. this._scene.getEngine().switchFullscreen(true);
  79882. this.updateButtonVisibility();
  79883. }
  79884. if (this._scene.activeCamera && this._canvas) {
  79885. this._scene.activeCamera.attachControl(this._canvas);
  79886. }
  79887. if (this._interactionsEnabled) {
  79888. this._scene.registerBeforeRender(this.beforeRender);
  79889. }
  79890. };
  79891. /**
  79892. * Attempt to exit VR, or fullscreen.
  79893. */
  79894. VRExperienceHelper.prototype.exitVR = function () {
  79895. if (this.onExitingVRObservable) {
  79896. try {
  79897. this.onExitingVRObservable.notifyObservers(this);
  79898. }
  79899. catch (err) {
  79900. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  79901. }
  79902. }
  79903. if (this._webVRpresenting) {
  79904. this._scene.getEngine().disableVR();
  79905. }
  79906. if (this._scene.activeCamera) {
  79907. this._position = this._scene.activeCamera.position.clone();
  79908. }
  79909. if (this._deviceOrientationCamera) {
  79910. this._deviceOrientationCamera.position = this._position;
  79911. this._scene.activeCamera = this._deviceOrientationCamera;
  79912. if (this._canvas) {
  79913. this._scene.activeCamera.attachControl(this._canvas);
  79914. }
  79915. }
  79916. else if (this._existingCamera) {
  79917. this._existingCamera.position = this._position;
  79918. this._scene.activeCamera = this._existingCamera;
  79919. }
  79920. this.updateButtonVisibility();
  79921. if (this._interactionsEnabled) {
  79922. this._scene.unregisterBeforeRender(this.beforeRender);
  79923. }
  79924. };
  79925. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  79926. /**
  79927. * The position of the vr experience helper.
  79928. */
  79929. get: function () {
  79930. return this._position;
  79931. },
  79932. /**
  79933. * Sets the position of the vr experience helper.
  79934. */
  79935. set: function (value) {
  79936. this._position = value;
  79937. if (this._scene.activeCamera) {
  79938. this._scene.activeCamera.position = value;
  79939. }
  79940. },
  79941. enumerable: true,
  79942. configurable: true
  79943. });
  79944. /**
  79945. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  79946. */
  79947. VRExperienceHelper.prototype.enableInteractions = function () {
  79948. var _this = this;
  79949. if (!this._interactionsEnabled) {
  79950. this._interactionsRequested = true;
  79951. if (this._leftControllerReady && this._webVRCamera.leftController) {
  79952. this._enableInteractionOnController(this._webVRCamera.leftController);
  79953. }
  79954. if (this._rightControllerReady && this._webVRCamera.rightController) {
  79955. this._enableInteractionOnController(this._webVRCamera.rightController);
  79956. }
  79957. if (!this._gazeTracker) {
  79958. this._createGazeTracker();
  79959. }
  79960. this.raySelectionPredicate = function (mesh) {
  79961. return mesh.isVisible;
  79962. };
  79963. this.meshSelectionPredicate = function (mesh) {
  79964. return true;
  79965. };
  79966. this._raySelectionPredicate = function (mesh) {
  79967. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  79968. && mesh.name.indexOf("teleportationTarget") === -1
  79969. && mesh.name.indexOf("torusTeleportation") === -1
  79970. && mesh.name.indexOf("laserPointer") === -1)) {
  79971. return _this.raySelectionPredicate(mesh);
  79972. }
  79973. return false;
  79974. };
  79975. this._interactionsEnabled = true;
  79976. }
  79977. };
  79978. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  79979. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  79980. if (this._floorMeshesCollection[i].id === mesh.id) {
  79981. return true;
  79982. }
  79983. }
  79984. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  79985. return true;
  79986. }
  79987. return false;
  79988. };
  79989. /**
  79990. * Adds a floor mesh to be used for teleportation.
  79991. * @param floorMesh the mesh to be used for teleportation.
  79992. */
  79993. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  79994. if (!this._floorMeshesCollection) {
  79995. return;
  79996. }
  79997. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  79998. return;
  79999. }
  80000. this._floorMeshesCollection.push(floorMesh);
  80001. };
  80002. /**
  80003. * Removes a floor mesh from being used for teleportation.
  80004. * @param floorMesh the mesh to be removed.
  80005. */
  80006. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80007. if (!this._floorMeshesCollection) {
  80008. return;
  80009. }
  80010. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80011. if (meshIndex !== -1) {
  80012. this._floorMeshesCollection.splice(meshIndex, 1);
  80013. }
  80014. };
  80015. /**
  80016. * Enables interactions and teleportation using the VR controllers and gaze.
  80017. * @param vrTeleportationOptions options to modify teleportation behavior.
  80018. */
  80019. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80020. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80021. if (!this._teleportationInitialized) {
  80022. this._teleportationRequested = true;
  80023. this.enableInteractions();
  80024. if (vrTeleportationOptions.floorMeshName) {
  80025. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80026. }
  80027. if (vrTeleportationOptions.floorMeshes) {
  80028. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80029. }
  80030. if (this._leftControllerReady && this._webVRCamera.leftController) {
  80031. this._enableTeleportationOnController(this._webVRCamera.leftController);
  80032. }
  80033. if (this._rightControllerReady && this._webVRCamera.rightController) {
  80034. this._enableTeleportationOnController(this._webVRCamera.rightController);
  80035. }
  80036. // Creates an image processing post process for the vignette not relying
  80037. // on the main scene configuration for image processing to reduce setup and spaces
  80038. // (gamma/linear) conflicts.
  80039. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80040. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80041. imageProcessingConfiguration.vignetteEnabled = true;
  80042. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80043. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80044. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  80045. this._teleportationInitialized = true;
  80046. if (this._isDefaultTeleportationTarget) {
  80047. this._createTeleportationCircles();
  80048. }
  80049. }
  80050. };
  80051. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  80052. var _this = this;
  80053. var controllerMesh = webVRController.mesh;
  80054. if (controllerMesh) {
  80055. var makeNotPick = function (root) {
  80056. root.name += " laserPointer";
  80057. root.getChildMeshes().forEach(function (c) {
  80058. makeNotPick(c);
  80059. });
  80060. };
  80061. makeNotPick(controllerMesh);
  80062. var childMeshes = controllerMesh.getChildMeshes();
  80063. for (var i = 0; i < childMeshes.length; i++) {
  80064. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80065. controllerMesh = childMeshes[i];
  80066. break;
  80067. }
  80068. }
  80069. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  80070. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  80071. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80072. laserPointerMaterial.alpha = 0.6;
  80073. laserPointer.material = laserPointerMaterial;
  80074. laserPointer.rotation.x = Math.PI / 2;
  80075. laserPointer.parent = controllerMesh;
  80076. laserPointer.position.z = -0.5;
  80077. laserPointer.isVisible = false;
  80078. if (webVRController.hand === "left") {
  80079. this._leftLaserPointer = laserPointer;
  80080. this._interactionsEnabledOnLeftController = true;
  80081. if (!this._rightLaserPointer) {
  80082. this._leftLaserPointer.isVisible = true;
  80083. }
  80084. }
  80085. else {
  80086. this._rightLaserPointer = laserPointer;
  80087. this._interactionsEnabledOnRightController = true;
  80088. if (!this._leftLaserPointer) {
  80089. this._rightLaserPointer.isVisible = true;
  80090. }
  80091. }
  80092. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80093. // Enabling / disabling laserPointer
  80094. if (_this._displayLaserPointer && stateObject.value === 1) {
  80095. laserPointer.isVisible = !laserPointer.isVisible;
  80096. // Laser pointer can only be active on left or right, not both at the same time
  80097. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  80098. _this._rightLaserPointer.isVisible = false;
  80099. }
  80100. else if (_this._leftLaserPointer) {
  80101. _this._leftLaserPointer.isVisible = false;
  80102. }
  80103. }
  80104. });
  80105. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80106. if (!_this._pointerDownOnMeshAsked) {
  80107. if (stateObject.value > _this._padSensibilityUp) {
  80108. _this._selectionPointerDown();
  80109. }
  80110. }
  80111. else if (stateObject.value < _this._padSensibilityDown) {
  80112. _this._selectionPointerUp();
  80113. }
  80114. });
  80115. }
  80116. };
  80117. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  80118. if (webVRController === void 0) { webVRController = null; }
  80119. if (!this._teleportationRequestInitiated) {
  80120. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  80121. if (webVRController) {
  80122. // If laser pointer wasn't enabled yet
  80123. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  80124. this._leftLaserPointer.isVisible = true;
  80125. if (this._rightLaserPointer) {
  80126. this._rightLaserPointer.isVisible = false;
  80127. }
  80128. }
  80129. else if (this._displayLaserPointer && this._rightLaserPointer) {
  80130. this._rightLaserPointer.isVisible = true;
  80131. if (this._leftLaserPointer) {
  80132. this._leftLaserPointer.isVisible = false;
  80133. }
  80134. }
  80135. }
  80136. this._teleportationRequestInitiated = true;
  80137. }
  80138. }
  80139. else {
  80140. // Listening to the proper controller values changes to confirm teleportation
  80141. if (webVRController == null
  80142. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  80143. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  80144. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80145. if (this._teleportationAllowed) {
  80146. this._teleportationAllowed = false;
  80147. this._teleportCamera();
  80148. }
  80149. this._teleportationRequestInitiated = false;
  80150. }
  80151. }
  80152. }
  80153. };
  80154. VRExperienceHelper.prototype._selectionPointerDown = function () {
  80155. this._pointerDownOnMeshAsked = true;
  80156. if (this._currentMeshSelected && this._currentHit) {
  80157. this._scene.simulatePointerDown(this._currentHit);
  80158. }
  80159. };
  80160. VRExperienceHelper.prototype._selectionPointerUp = function () {
  80161. if (this._currentMeshSelected && this._currentHit) {
  80162. this._scene.simulatePointerUp(this._currentHit);
  80163. }
  80164. this._pointerDownOnMeshAsked = false;
  80165. };
  80166. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  80167. // Only rotate when user is not currently selecting a teleportation location
  80168. if (this._teleportationRequestInitiated) {
  80169. return;
  80170. }
  80171. if (!this._rotationLeftAsked) {
  80172. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  80173. this._rotationLeftAsked = true;
  80174. if (this._rotationAllowed) {
  80175. this._rotateCamera(false);
  80176. }
  80177. }
  80178. }
  80179. else {
  80180. if (stateObject.x > -this._padSensibilityDown) {
  80181. this._rotationLeftAsked = false;
  80182. }
  80183. }
  80184. if (!this._rotationRightAsked) {
  80185. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  80186. this._rotationRightAsked = true;
  80187. if (this._rotationAllowed) {
  80188. this._rotateCamera(true);
  80189. }
  80190. }
  80191. }
  80192. else {
  80193. if (stateObject.x < this._padSensibilityDown) {
  80194. this._rotationRightAsked = false;
  80195. }
  80196. }
  80197. };
  80198. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  80199. // Only teleport backwards when user is not currently selecting a teleportation location
  80200. if (this._teleportationRequestInitiated) {
  80201. return;
  80202. }
  80203. // Teleport backwards
  80204. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  80205. if (!this._teleportationBackRequestInitiated) {
  80206. if (!this.currentVRCamera) {
  80207. return;
  80208. }
  80209. // Get rotation and position of the current camera
  80210. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80211. var position = this.currentVRCamera.position;
  80212. // If the camera has device position, use that instead
  80213. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80214. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80215. position = this.currentVRCamera.devicePosition;
  80216. }
  80217. // Get matrix with only the y rotation of the device rotation
  80218. rotation.toEulerAnglesToRef(this._workingVector);
  80219. this._workingVector.z = 0;
  80220. this._workingVector.x = 0;
  80221. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80222. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80223. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80224. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80225. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80226. var ray = new BABYLON.Ray(position, this._workingVector);
  80227. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80228. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80229. this._teleportCamera(hit.pickedPoint);
  80230. }
  80231. this._teleportationBackRequestInitiated = true;
  80232. }
  80233. }
  80234. else {
  80235. this._teleportationBackRequestInitiated = false;
  80236. }
  80237. };
  80238. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  80239. var _this = this;
  80240. var controllerMesh = webVRController.mesh;
  80241. if (controllerMesh) {
  80242. if (webVRController.hand === "left") {
  80243. if (!this._interactionsEnabledOnLeftController) {
  80244. this._enableInteractionOnController(webVRController);
  80245. }
  80246. this._teleportationEnabledOnLeftController = true;
  80247. }
  80248. else {
  80249. if (!this._interactionsEnabledOnRightController) {
  80250. this._enableInteractionOnController(webVRController);
  80251. }
  80252. this._teleportationEnabledOnRightController = true;
  80253. }
  80254. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80255. this._dpadPressed = false;
  80256. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80257. _this._dpadPressed = stateObject.pressed;
  80258. if (!_this._dpadPressed) {
  80259. _this._rotationLeftAsked = false;
  80260. _this._rotationRightAsked = false;
  80261. _this._teleportationBackRequestInitiated = false;
  80262. }
  80263. });
  80264. }
  80265. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80266. if (_this.teleportationEnabled) {
  80267. _this._checkTeleportBackwards(stateObject);
  80268. _this._checkTeleportWithRay(stateObject, webVRController);
  80269. }
  80270. _this._checkRotate(stateObject);
  80271. });
  80272. }
  80273. };
  80274. // Gaze support used to point to teleport or to interact with an object
  80275. VRExperienceHelper.prototype._createGazeTracker = function () {
  80276. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  80277. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80278. this._gazeTracker.isPickable = false;
  80279. this._gazeTracker.isVisible = false;
  80280. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  80281. targetMat.specularColor = BABYLON.Color3.Black();
  80282. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80283. targetMat.backFaceCulling = false;
  80284. this._gazeTracker.material = targetMat;
  80285. };
  80286. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80287. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80288. this._teleportationTarget.isPickable = false;
  80289. var length = 512;
  80290. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80291. dynamicTexture.hasAlpha = true;
  80292. var context = dynamicTexture.getContext();
  80293. var centerX = length / 2;
  80294. var centerY = length / 2;
  80295. var radius = 200;
  80296. context.beginPath();
  80297. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80298. context.fillStyle = this._teleportationFillColor;
  80299. context.fill();
  80300. context.lineWidth = 10;
  80301. context.strokeStyle = this._teleportationBorderColor;
  80302. context.stroke();
  80303. context.closePath();
  80304. dynamicTexture.update();
  80305. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  80306. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  80307. this._teleportationTarget.material = teleportationCircleMaterial;
  80308. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  80309. torus.isPickable = false;
  80310. torus.parent = this._teleportationTarget;
  80311. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80312. var keys = [];
  80313. keys.push({
  80314. frame: 0,
  80315. value: 0
  80316. });
  80317. keys.push({
  80318. frame: 30,
  80319. value: 0.4
  80320. });
  80321. keys.push({
  80322. frame: 60,
  80323. value: 0
  80324. });
  80325. animationInnerCircle.setKeys(keys);
  80326. var easingFunction = new BABYLON.SineEase();
  80327. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80328. animationInnerCircle.setEasingFunction(easingFunction);
  80329. torus.animations = [];
  80330. torus.animations.push(animationInnerCircle);
  80331. this._scene.beginAnimation(torus, 0, 60, true);
  80332. this._hideTeleportationTarget();
  80333. };
  80334. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  80335. if (this._teleportationInitialized) {
  80336. this._teleportationTarget.isVisible = true;
  80337. if (this._isDefaultTeleportationTarget) {
  80338. this._teleportationTarget.getChildren()[0].isVisible = true;
  80339. }
  80340. }
  80341. };
  80342. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  80343. if (this._teleportationInitialized) {
  80344. this._teleportationTarget.isVisible = false;
  80345. if (this._isDefaultTeleportationTarget) {
  80346. this._teleportationTarget.getChildren()[0].isVisible = false;
  80347. }
  80348. }
  80349. };
  80350. VRExperienceHelper.prototype._rotateCamera = function (right) {
  80351. var _this = this;
  80352. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80353. return;
  80354. }
  80355. if (right) {
  80356. this._rotationAngle++;
  80357. }
  80358. else {
  80359. this._rotationAngle--;
  80360. }
  80361. this.currentVRCamera.animations = [];
  80362. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  80363. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80364. var animationRotationKeys = [];
  80365. animationRotationKeys.push({
  80366. frame: 0,
  80367. value: this.currentVRCamera.rotationQuaternion
  80368. });
  80369. animationRotationKeys.push({
  80370. frame: 6,
  80371. value: target
  80372. });
  80373. animationRotation.setKeys(animationRotationKeys);
  80374. animationRotation.setEasingFunction(this._circleEase);
  80375. this.currentVRCamera.animations.push(animationRotation);
  80376. this._postProcessMove.animations = [];
  80377. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80378. var vignetteWeightKeys = [];
  80379. vignetteWeightKeys.push({
  80380. frame: 0,
  80381. value: 0
  80382. });
  80383. vignetteWeightKeys.push({
  80384. frame: 3,
  80385. value: 4
  80386. });
  80387. vignetteWeightKeys.push({
  80388. frame: 6,
  80389. value: 0
  80390. });
  80391. animationPP.setKeys(vignetteWeightKeys);
  80392. animationPP.setEasingFunction(this._circleEase);
  80393. this._postProcessMove.animations.push(animationPP);
  80394. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80395. var vignetteStretchKeys = [];
  80396. vignetteStretchKeys.push({
  80397. frame: 0,
  80398. value: 0
  80399. });
  80400. vignetteStretchKeys.push({
  80401. frame: 3,
  80402. value: 10
  80403. });
  80404. vignetteStretchKeys.push({
  80405. frame: 6,
  80406. value: 0
  80407. });
  80408. animationPP2.setKeys(vignetteStretchKeys);
  80409. animationPP2.setEasingFunction(this._circleEase);
  80410. this._postProcessMove.animations.push(animationPP2);
  80411. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80412. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80413. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80414. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  80415. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80416. });
  80417. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  80418. };
  80419. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  80420. if (hit.pickedPoint) {
  80421. this._teleportationAllowed = true;
  80422. if (this._teleportationRequestInitiated) {
  80423. this._displayTeleportationTarget();
  80424. }
  80425. else {
  80426. this._hideTeleportationTarget();
  80427. }
  80428. this._haloCenter.copyFrom(hit.pickedPoint);
  80429. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  80430. var pickNormal = hit.getNormal(true, false);
  80431. if (pickNormal) {
  80432. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80433. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80434. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  80435. }
  80436. this._teleportationTarget.position.y += 0.1;
  80437. }
  80438. };
  80439. VRExperienceHelper.prototype._teleportCamera = function (location) {
  80440. var _this = this;
  80441. if (location === void 0) { location = null; }
  80442. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80443. return;
  80444. }
  80445. if (!location) {
  80446. location = this._haloCenter;
  80447. }
  80448. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  80449. // offset of the headset from the anchor.
  80450. if (this.webVRCamera.leftCamera) {
  80451. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  80452. this._workingVector.subtractInPlace(this.webVRCamera.position);
  80453. location.subtractToRef(this._workingVector, this._workingVector);
  80454. }
  80455. else {
  80456. this._workingVector.copyFrom(location);
  80457. }
  80458. // Add height to account for user's height offset
  80459. if (this.isInVRMode) {
  80460. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  80461. }
  80462. else {
  80463. this._workingVector.y += this._defaultHeight;
  80464. }
  80465. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  80466. // Create animation from the camera's position to the new location
  80467. this.currentVRCamera.animations = [];
  80468. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80469. var animationCameraTeleportationKeys = [{
  80470. frame: 0,
  80471. value: this.currentVRCamera.position
  80472. },
  80473. {
  80474. frame: 11,
  80475. value: this._workingVector
  80476. }
  80477. ];
  80478. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  80479. animationCameraTeleportation.setEasingFunction(this._circleEase);
  80480. this.currentVRCamera.animations.push(animationCameraTeleportation);
  80481. this._postProcessMove.animations = [];
  80482. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80483. var vignetteWeightKeys = [];
  80484. vignetteWeightKeys.push({
  80485. frame: 0,
  80486. value: 0
  80487. });
  80488. vignetteWeightKeys.push({
  80489. frame: 5,
  80490. value: 8
  80491. });
  80492. vignetteWeightKeys.push({
  80493. frame: 11,
  80494. value: 0
  80495. });
  80496. animationPP.setKeys(vignetteWeightKeys);
  80497. this._postProcessMove.animations.push(animationPP);
  80498. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80499. var vignetteStretchKeys = [];
  80500. vignetteStretchKeys.push({
  80501. frame: 0,
  80502. value: 0
  80503. });
  80504. vignetteStretchKeys.push({
  80505. frame: 5,
  80506. value: 10
  80507. });
  80508. vignetteStretchKeys.push({
  80509. frame: 11,
  80510. value: 0
  80511. });
  80512. animationPP2.setKeys(vignetteStretchKeys);
  80513. this._postProcessMove.animations.push(animationPP2);
  80514. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80515. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80516. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80517. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  80518. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80519. });
  80520. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  80521. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  80522. });
  80523. };
  80524. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  80525. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80526. return;
  80527. }
  80528. var ray;
  80529. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  80530. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  80531. }
  80532. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  80533. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  80534. }
  80535. else {
  80536. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  80537. }
  80538. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80539. // Moving the gazeTracker on the mesh face targetted
  80540. if (hit && hit.pickedPoint) {
  80541. if (this._displayGaze) {
  80542. var multiplier = 1;
  80543. this._gazeTracker.isVisible = true;
  80544. if (this._isActionableMesh) {
  80545. multiplier = 3;
  80546. }
  80547. this._gazeTracker.scaling.x = hit.distance * multiplier;
  80548. this._gazeTracker.scaling.y = hit.distance * multiplier;
  80549. this._gazeTracker.scaling.z = hit.distance * multiplier;
  80550. var pickNormal = hit.getNormal();
  80551. // To avoid z-fighting
  80552. var deltaFighting = 0.002;
  80553. if (pickNormal) {
  80554. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80555. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80556. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  80557. }
  80558. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  80559. if (this._gazeTracker.position.x < 0) {
  80560. this._gazeTracker.position.x += deltaFighting;
  80561. }
  80562. else {
  80563. this._gazeTracker.position.x -= deltaFighting;
  80564. }
  80565. if (this._gazeTracker.position.y < 0) {
  80566. this._gazeTracker.position.y += deltaFighting;
  80567. }
  80568. else {
  80569. this._gazeTracker.position.y -= deltaFighting;
  80570. }
  80571. if (this._gazeTracker.position.z < 0) {
  80572. this._gazeTracker.position.z += deltaFighting;
  80573. }
  80574. else {
  80575. this._gazeTracker.position.z -= deltaFighting;
  80576. }
  80577. }
  80578. // Changing the size of the laser pointer based on the distance from the targetted point
  80579. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  80580. this._rightLaserPointer.scaling.y = hit.distance;
  80581. this._rightLaserPointer.position.z = -hit.distance / 2;
  80582. }
  80583. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  80584. this._leftLaserPointer.scaling.y = hit.distance;
  80585. this._leftLaserPointer.position.z = -hit.distance / 2;
  80586. }
  80587. }
  80588. else {
  80589. this._gazeTracker.isVisible = false;
  80590. }
  80591. if (hit && hit.pickedMesh) {
  80592. this._currentHit = hit;
  80593. if (this._pointerDownOnMeshAsked) {
  80594. this._scene.simulatePointerMove(this._currentHit);
  80595. }
  80596. // The object selected is the floor, we're in a teleportation scenario
  80597. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  80598. // Moving the teleportation area to this targetted point
  80599. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  80600. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  80601. this._notifySelectedMeshUnselected();
  80602. }
  80603. this._currentMeshSelected = null;
  80604. this._moveTeleportationSelectorTo(hit);
  80605. return;
  80606. }
  80607. // If not, we're in a selection scenario
  80608. this._hideTeleportationTarget();
  80609. this._teleportationAllowed = false;
  80610. if (hit.pickedMesh !== this._currentMeshSelected) {
  80611. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  80612. this.onNewMeshPicked.notifyObservers(hit);
  80613. this._currentMeshSelected = hit.pickedMesh;
  80614. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  80615. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  80616. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  80617. this._isActionableMesh = true;
  80618. }
  80619. else {
  80620. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80621. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80622. this._isActionableMesh = false;
  80623. }
  80624. try {
  80625. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  80626. }
  80627. catch (err) {
  80628. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  80629. }
  80630. }
  80631. else {
  80632. this._notifySelectedMeshUnselected();
  80633. this._currentMeshSelected = null;
  80634. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80635. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80636. }
  80637. }
  80638. }
  80639. else {
  80640. this._currentHit = null;
  80641. this._notifySelectedMeshUnselected();
  80642. this._currentMeshSelected = null;
  80643. this._teleportationAllowed = false;
  80644. this._hideTeleportationTarget();
  80645. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80646. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  80647. }
  80648. };
  80649. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  80650. if (this._currentMeshSelected) {
  80651. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  80652. }
  80653. };
  80654. /**
  80655. * Sets the color of the laser ray from the vr controllers.
  80656. * @param color new color for the ray.
  80657. */
  80658. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  80659. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  80660. this._leftLaserPointer.material.emissiveColor = color;
  80661. }
  80662. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  80663. this._rightLaserPointer.material.emissiveColor = color;
  80664. }
  80665. };
  80666. /**
  80667. * Sets the color of the ray from the vr headsets gaze.
  80668. * @param color new color for the ray.
  80669. */
  80670. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  80671. if (this._gazeTracker.material) {
  80672. this._gazeTracker.material.emissiveColor = color;
  80673. }
  80674. };
  80675. /**
  80676. * Exits VR and disposes of the vr experience helper
  80677. */
  80678. VRExperienceHelper.prototype.dispose = function () {
  80679. if (this.isInVRMode) {
  80680. this.exitVR();
  80681. }
  80682. if (this._passProcessMove) {
  80683. this._passProcessMove.dispose();
  80684. }
  80685. if (this._postProcessMove) {
  80686. this._postProcessMove.dispose();
  80687. }
  80688. if (this._webVRCamera) {
  80689. this._webVRCamera.dispose();
  80690. }
  80691. if (this._vrDeviceOrientationCamera) {
  80692. this._vrDeviceOrientationCamera.dispose();
  80693. }
  80694. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  80695. document.body.removeChild(this._btnVR);
  80696. }
  80697. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  80698. this._deviceOrientationCamera.dispose();
  80699. }
  80700. if (this._gazeTracker) {
  80701. this._gazeTracker.dispose();
  80702. }
  80703. if (this._teleportationTarget) {
  80704. this._teleportationTarget.dispose();
  80705. }
  80706. this._floorMeshesCollection = [];
  80707. document.removeEventListener("keydown", this._onKeyDown);
  80708. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80709. window.removeEventListener("resize", this._onResize);
  80710. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  80711. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  80712. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  80713. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  80714. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  80715. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  80716. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  80717. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80718. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  80719. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  80720. this._scene.unregisterBeforeRender(this.beforeRender);
  80721. };
  80722. /**
  80723. * Gets the name of the VRExperienceHelper class
  80724. * @returns "VRExperienceHelper"
  80725. */
  80726. VRExperienceHelper.prototype.getClassName = function () {
  80727. return "VRExperienceHelper";
  80728. };
  80729. return VRExperienceHelper;
  80730. }());
  80731. BABYLON.VRExperienceHelper = VRExperienceHelper;
  80732. })(BABYLON || (BABYLON = {}));
  80733. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  80734. // Mainly based on these 2 articles :
  80735. // 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
  80736. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  80737. var BABYLON;
  80738. (function (BABYLON) {
  80739. var JoystickAxis;
  80740. (function (JoystickAxis) {
  80741. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  80742. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  80743. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  80744. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  80745. var VirtualJoystick = /** @class */ (function () {
  80746. function VirtualJoystick(leftJoystick) {
  80747. var _this = this;
  80748. if (leftJoystick) {
  80749. this._leftJoystick = true;
  80750. }
  80751. else {
  80752. this._leftJoystick = false;
  80753. }
  80754. VirtualJoystick._globalJoystickIndex++;
  80755. // By default left & right arrow keys are moving the X
  80756. // and up & down keys are moving the Y
  80757. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80758. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80759. this.reverseLeftRight = false;
  80760. this.reverseUpDown = false;
  80761. // collections of pointers
  80762. this._touches = new BABYLON.StringDictionary();
  80763. this.deltaPosition = BABYLON.Vector3.Zero();
  80764. this._joystickSensibility = 25;
  80765. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80766. this._onResize = function (evt) {
  80767. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80768. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80769. if (VirtualJoystick.vjCanvas) {
  80770. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  80771. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  80772. }
  80773. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  80774. };
  80775. // injecting a canvas element on top of the canvas 3D game
  80776. if (!VirtualJoystick.vjCanvas) {
  80777. window.addEventListener("resize", this._onResize, false);
  80778. VirtualJoystick.vjCanvas = document.createElement("canvas");
  80779. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  80780. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  80781. VirtualJoystick.vjCanvas.width = window.innerWidth;
  80782. VirtualJoystick.vjCanvas.height = window.innerHeight;
  80783. VirtualJoystick.vjCanvas.style.width = "100%";
  80784. VirtualJoystick.vjCanvas.style.height = "100%";
  80785. VirtualJoystick.vjCanvas.style.position = "absolute";
  80786. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  80787. VirtualJoystick.vjCanvas.style.top = "0px";
  80788. VirtualJoystick.vjCanvas.style.left = "0px";
  80789. VirtualJoystick.vjCanvas.style.zIndex = "5";
  80790. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  80791. // Support for jQuery PEP polyfill
  80792. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  80793. var context = VirtualJoystick.vjCanvas.getContext('2d');
  80794. if (!context) {
  80795. throw new Error("Unable to create canvas for virtual joystick");
  80796. }
  80797. VirtualJoystick.vjCanvasContext = context;
  80798. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  80799. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80800. document.body.appendChild(VirtualJoystick.vjCanvas);
  80801. }
  80802. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  80803. this.pressed = false;
  80804. // default joystick color
  80805. this._joystickColor = "cyan";
  80806. this._joystickPointerID = -1;
  80807. // current joystick position
  80808. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  80809. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  80810. // origin joystick position
  80811. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  80812. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  80813. this._onPointerDownHandlerRef = function (evt) {
  80814. _this._onPointerDown(evt);
  80815. };
  80816. this._onPointerMoveHandlerRef = function (evt) {
  80817. _this._onPointerMove(evt);
  80818. };
  80819. this._onPointerUpHandlerRef = function (evt) {
  80820. _this._onPointerUp(evt);
  80821. };
  80822. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  80823. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  80824. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  80825. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  80826. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  80827. evt.preventDefault(); // Disables system menu
  80828. }, false);
  80829. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  80830. }
  80831. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  80832. this._joystickSensibility = newJoystickSensibility;
  80833. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  80834. };
  80835. VirtualJoystick.prototype._onPointerDown = function (e) {
  80836. var positionOnScreenCondition;
  80837. e.preventDefault();
  80838. if (this._leftJoystick === true) {
  80839. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  80840. }
  80841. else {
  80842. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  80843. }
  80844. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  80845. // First contact will be dedicated to the virtual joystick
  80846. this._joystickPointerID = e.pointerId;
  80847. this._joystickPointerStartPos.x = e.clientX;
  80848. this._joystickPointerStartPos.y = e.clientY;
  80849. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  80850. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  80851. this._deltaJoystickVector.x = 0;
  80852. this._deltaJoystickVector.y = 0;
  80853. this.pressed = true;
  80854. this._touches.add(e.pointerId.toString(), e);
  80855. }
  80856. else {
  80857. // You can only trigger the action buttons with a joystick declared
  80858. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  80859. this._action();
  80860. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  80861. }
  80862. }
  80863. };
  80864. VirtualJoystick.prototype._onPointerMove = function (e) {
  80865. // If the current pointer is the one associated to the joystick (first touch contact)
  80866. if (this._joystickPointerID == e.pointerId) {
  80867. this._joystickPointerPos.x = e.clientX;
  80868. this._joystickPointerPos.y = e.clientY;
  80869. this._deltaJoystickVector = this._joystickPointerPos.clone();
  80870. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  80871. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  80872. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  80873. switch (this._axisTargetedByLeftAndRight) {
  80874. case JoystickAxis.X:
  80875. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  80876. break;
  80877. case JoystickAxis.Y:
  80878. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  80879. break;
  80880. case JoystickAxis.Z:
  80881. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  80882. break;
  80883. }
  80884. var directionUpDown = this.reverseUpDown ? 1 : -1;
  80885. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  80886. switch (this._axisTargetedByUpAndDown) {
  80887. case JoystickAxis.X:
  80888. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  80889. break;
  80890. case JoystickAxis.Y:
  80891. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  80892. break;
  80893. case JoystickAxis.Z:
  80894. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  80895. break;
  80896. }
  80897. }
  80898. else {
  80899. var data = this._touches.get(e.pointerId.toString());
  80900. if (data) {
  80901. data.x = e.clientX;
  80902. data.y = e.clientY;
  80903. }
  80904. }
  80905. };
  80906. VirtualJoystick.prototype._onPointerUp = function (e) {
  80907. if (this._joystickPointerID == e.pointerId) {
  80908. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  80909. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  80910. this._joystickPointerID = -1;
  80911. this.pressed = false;
  80912. }
  80913. else {
  80914. var touch = this._touches.get(e.pointerId.toString());
  80915. if (touch) {
  80916. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80917. }
  80918. }
  80919. this._deltaJoystickVector.x = 0;
  80920. this._deltaJoystickVector.y = 0;
  80921. this._touches.remove(e.pointerId.toString());
  80922. };
  80923. /**
  80924. * Change the color of the virtual joystick
  80925. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  80926. */
  80927. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  80928. this._joystickColor = newColor;
  80929. };
  80930. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  80931. this._action = action;
  80932. };
  80933. // Define which axis you'd like to control for left & right
  80934. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  80935. switch (axis) {
  80936. case JoystickAxis.X:
  80937. case JoystickAxis.Y:
  80938. case JoystickAxis.Z:
  80939. this._axisTargetedByLeftAndRight = axis;
  80940. break;
  80941. default:
  80942. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  80943. break;
  80944. }
  80945. };
  80946. // Define which axis you'd like to control for up & down
  80947. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  80948. switch (axis) {
  80949. case JoystickAxis.X:
  80950. case JoystickAxis.Y:
  80951. case JoystickAxis.Z:
  80952. this._axisTargetedByUpAndDown = axis;
  80953. break;
  80954. default:
  80955. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  80956. break;
  80957. }
  80958. };
  80959. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  80960. var _this = this;
  80961. if (this.pressed) {
  80962. this._touches.forEach(function (key, touch) {
  80963. if (touch.pointerId === _this._joystickPointerID) {
  80964. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  80965. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  80966. VirtualJoystick.vjCanvasContext.beginPath();
  80967. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80968. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80969. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  80970. VirtualJoystick.vjCanvasContext.stroke();
  80971. VirtualJoystick.vjCanvasContext.closePath();
  80972. VirtualJoystick.vjCanvasContext.beginPath();
  80973. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80974. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  80975. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  80976. VirtualJoystick.vjCanvasContext.stroke();
  80977. VirtualJoystick.vjCanvasContext.closePath();
  80978. VirtualJoystick.vjCanvasContext.beginPath();
  80979. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  80980. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  80981. VirtualJoystick.vjCanvasContext.stroke();
  80982. VirtualJoystick.vjCanvasContext.closePath();
  80983. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  80984. }
  80985. else {
  80986. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  80987. VirtualJoystick.vjCanvasContext.beginPath();
  80988. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  80989. VirtualJoystick.vjCanvasContext.beginPath();
  80990. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  80991. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  80992. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  80993. VirtualJoystick.vjCanvasContext.stroke();
  80994. VirtualJoystick.vjCanvasContext.closePath();
  80995. touch.prevX = touch.x;
  80996. touch.prevY = touch.y;
  80997. }
  80998. ;
  80999. });
  81000. }
  81001. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81002. };
  81003. VirtualJoystick.prototype.releaseCanvas = function () {
  81004. if (VirtualJoystick.vjCanvas) {
  81005. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81006. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81007. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81008. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81009. window.removeEventListener("resize", this._onResize);
  81010. document.body.removeChild(VirtualJoystick.vjCanvas);
  81011. VirtualJoystick.vjCanvas = null;
  81012. }
  81013. };
  81014. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81015. VirtualJoystick._globalJoystickIndex = 0;
  81016. return VirtualJoystick;
  81017. }());
  81018. BABYLON.VirtualJoystick = VirtualJoystick;
  81019. })(BABYLON || (BABYLON = {}));
  81020. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81021. var BABYLON;
  81022. (function (BABYLON) {
  81023. // We're mainly based on the logic defined into the FreeCamera code
  81024. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81025. __extends(VirtualJoysticksCamera, _super);
  81026. function VirtualJoysticksCamera(name, position, scene) {
  81027. var _this = _super.call(this, name, position, scene) || this;
  81028. _this.inputs.addVirtualJoystick();
  81029. return _this;
  81030. }
  81031. VirtualJoysticksCamera.prototype.getClassName = function () {
  81032. return "VirtualJoysticksCamera";
  81033. };
  81034. return VirtualJoysticksCamera;
  81035. }(BABYLON.FreeCamera));
  81036. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81037. })(BABYLON || (BABYLON = {}));
  81038. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81039. var BABYLON;
  81040. (function (BABYLON) {
  81041. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81042. function FreeCameraVirtualJoystickInput() {
  81043. }
  81044. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81045. return this._leftjoystick;
  81046. };
  81047. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81048. return this._rightjoystick;
  81049. };
  81050. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81051. if (this._leftjoystick) {
  81052. var camera = this.camera;
  81053. var speed = camera._computeLocalCameraSpeed() * 50;
  81054. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81055. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81056. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81057. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81058. if (!this._leftjoystick.pressed) {
  81059. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81060. }
  81061. if (!this._rightjoystick.pressed) {
  81062. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81063. }
  81064. }
  81065. };
  81066. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81067. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81068. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81069. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81070. this._leftjoystick.setJoystickSensibility(0.15);
  81071. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81072. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81073. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81074. this._rightjoystick.reverseUpDown = true;
  81075. this._rightjoystick.setJoystickSensibility(0.05);
  81076. this._rightjoystick.setJoystickColor("yellow");
  81077. };
  81078. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81079. this._leftjoystick.releaseCanvas();
  81080. this._rightjoystick.releaseCanvas();
  81081. };
  81082. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81083. return "FreeCameraVirtualJoystickInput";
  81084. };
  81085. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81086. return "virtualJoystick";
  81087. };
  81088. return FreeCameraVirtualJoystickInput;
  81089. }());
  81090. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81091. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81092. })(BABYLON || (BABYLON = {}));
  81093. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81094. var BABYLON;
  81095. (function (BABYLON) {
  81096. var SimplificationSettings = /** @class */ (function () {
  81097. function SimplificationSettings(quality, distance, optimizeMesh) {
  81098. this.quality = quality;
  81099. this.distance = distance;
  81100. this.optimizeMesh = optimizeMesh;
  81101. }
  81102. return SimplificationSettings;
  81103. }());
  81104. BABYLON.SimplificationSettings = SimplificationSettings;
  81105. var SimplificationQueue = /** @class */ (function () {
  81106. function SimplificationQueue() {
  81107. this.running = false;
  81108. this._simplificationArray = [];
  81109. }
  81110. SimplificationQueue.prototype.addTask = function (task) {
  81111. this._simplificationArray.push(task);
  81112. };
  81113. SimplificationQueue.prototype.executeNext = function () {
  81114. var task = this._simplificationArray.pop();
  81115. if (task) {
  81116. this.running = true;
  81117. this.runSimplification(task);
  81118. }
  81119. else {
  81120. this.running = false;
  81121. }
  81122. };
  81123. SimplificationQueue.prototype.runSimplification = function (task) {
  81124. var _this = this;
  81125. if (task.parallelProcessing) {
  81126. //parallel simplifier
  81127. task.settings.forEach(function (setting) {
  81128. var simplifier = _this.getSimplifier(task);
  81129. simplifier.simplify(setting, function (newMesh) {
  81130. task.mesh.addLODLevel(setting.distance, newMesh);
  81131. newMesh.isVisible = true;
  81132. //check if it is the last
  81133. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81134. //all done, run the success callback.
  81135. task.successCallback();
  81136. }
  81137. _this.executeNext();
  81138. });
  81139. });
  81140. }
  81141. else {
  81142. //single simplifier.
  81143. var simplifier = this.getSimplifier(task);
  81144. var runDecimation = function (setting, callback) {
  81145. simplifier.simplify(setting, function (newMesh) {
  81146. task.mesh.addLODLevel(setting.distance, newMesh);
  81147. newMesh.isVisible = true;
  81148. //run the next quality level
  81149. callback();
  81150. });
  81151. };
  81152. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81153. runDecimation(task.settings[loop.index], function () {
  81154. loop.executeNext();
  81155. });
  81156. }, function () {
  81157. //execution ended, run the success callback.
  81158. if (task.successCallback) {
  81159. task.successCallback();
  81160. }
  81161. _this.executeNext();
  81162. });
  81163. }
  81164. };
  81165. SimplificationQueue.prototype.getSimplifier = function (task) {
  81166. switch (task.simplificationType) {
  81167. case SimplificationType.QUADRATIC:
  81168. default:
  81169. return new QuadraticErrorSimplification(task.mesh);
  81170. }
  81171. };
  81172. return SimplificationQueue;
  81173. }());
  81174. BABYLON.SimplificationQueue = SimplificationQueue;
  81175. /**
  81176. * The implemented types of simplification.
  81177. * At the moment only Quadratic Error Decimation is implemented.
  81178. */
  81179. var SimplificationType;
  81180. (function (SimplificationType) {
  81181. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81182. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81183. var DecimationTriangle = /** @class */ (function () {
  81184. function DecimationTriangle(vertices) {
  81185. this.vertices = vertices;
  81186. this.error = new Array(4);
  81187. this.deleted = false;
  81188. this.isDirty = false;
  81189. this.deletePending = false;
  81190. this.borderFactor = 0;
  81191. }
  81192. return DecimationTriangle;
  81193. }());
  81194. BABYLON.DecimationTriangle = DecimationTriangle;
  81195. var DecimationVertex = /** @class */ (function () {
  81196. function DecimationVertex(position, id) {
  81197. this.position = position;
  81198. this.id = id;
  81199. this.isBorder = true;
  81200. this.q = new QuadraticMatrix();
  81201. this.triangleCount = 0;
  81202. this.triangleStart = 0;
  81203. this.originalOffsets = [];
  81204. }
  81205. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81206. this.position.copyFrom(newPosition);
  81207. };
  81208. return DecimationVertex;
  81209. }());
  81210. BABYLON.DecimationVertex = DecimationVertex;
  81211. var QuadraticMatrix = /** @class */ (function () {
  81212. function QuadraticMatrix(data) {
  81213. this.data = new Array(10);
  81214. for (var i = 0; i < 10; ++i) {
  81215. if (data && data[i]) {
  81216. this.data[i] = data[i];
  81217. }
  81218. else {
  81219. this.data[i] = 0;
  81220. }
  81221. }
  81222. }
  81223. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81224. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81225. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81226. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81227. return det;
  81228. };
  81229. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81230. for (var i = 0; i < 10; ++i) {
  81231. this.data[i] += matrix.data[i];
  81232. }
  81233. };
  81234. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81235. for (var i = 0; i < 10; ++i) {
  81236. this.data[i] += data[i];
  81237. }
  81238. };
  81239. QuadraticMatrix.prototype.add = function (matrix) {
  81240. var m = new QuadraticMatrix();
  81241. for (var i = 0; i < 10; ++i) {
  81242. m.data[i] = this.data[i] + matrix.data[i];
  81243. }
  81244. return m;
  81245. };
  81246. QuadraticMatrix.FromData = function (a, b, c, d) {
  81247. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81248. };
  81249. //returning an array to avoid garbage collection
  81250. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81251. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81252. };
  81253. return QuadraticMatrix;
  81254. }());
  81255. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81256. var Reference = /** @class */ (function () {
  81257. function Reference(vertexId, triangleId) {
  81258. this.vertexId = vertexId;
  81259. this.triangleId = triangleId;
  81260. }
  81261. return Reference;
  81262. }());
  81263. BABYLON.Reference = Reference;
  81264. /**
  81265. * An implementation of the Quadratic Error simplification algorithm.
  81266. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81267. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81268. * @author RaananW
  81269. */
  81270. var QuadraticErrorSimplification = /** @class */ (function () {
  81271. function QuadraticErrorSimplification(_mesh) {
  81272. this._mesh = _mesh;
  81273. this.syncIterations = 5000;
  81274. this.aggressiveness = 7;
  81275. this.decimationIterations = 100;
  81276. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81277. }
  81278. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81279. var _this = this;
  81280. this.initDecimatedMesh();
  81281. //iterating through the submeshes array, one after the other.
  81282. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81283. _this.initWithMesh(loop.index, function () {
  81284. _this.runDecimation(settings, loop.index, function () {
  81285. loop.executeNext();
  81286. });
  81287. }, settings.optimizeMesh);
  81288. }, function () {
  81289. setTimeout(function () {
  81290. successCallback(_this._reconstructedMesh);
  81291. }, 0);
  81292. });
  81293. };
  81294. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81295. var _this = this;
  81296. var targetCount = ~~(this.triangles.length * settings.quality);
  81297. var deletedTriangles = 0;
  81298. var triangleCount = this.triangles.length;
  81299. var iterationFunction = function (iteration, callback) {
  81300. setTimeout(function () {
  81301. if (iteration % 5 === 0) {
  81302. _this.updateMesh(iteration === 0);
  81303. }
  81304. for (var i = 0; i < _this.triangles.length; ++i) {
  81305. _this.triangles[i].isDirty = false;
  81306. }
  81307. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81308. var trianglesIterator = function (i) {
  81309. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  81310. var t = _this.triangles[tIdx];
  81311. if (!t)
  81312. return;
  81313. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  81314. return;
  81315. }
  81316. for (var j = 0; j < 3; ++j) {
  81317. if (t.error[j] < threshold) {
  81318. var deleted0 = [];
  81319. var deleted1 = [];
  81320. var v0 = t.vertices[j];
  81321. var v1 = t.vertices[(j + 1) % 3];
  81322. if (v0.isBorder || v1.isBorder)
  81323. continue;
  81324. var p = BABYLON.Vector3.Zero();
  81325. var n = BABYLON.Vector3.Zero();
  81326. var uv = BABYLON.Vector2.Zero();
  81327. var color = new BABYLON.Color4(0, 0, 0, 1);
  81328. _this.calculateError(v0, v1, p, n, uv, color);
  81329. var delTr = new Array();
  81330. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  81331. continue;
  81332. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  81333. continue;
  81334. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  81335. continue;
  81336. var uniqueArray = new Array();
  81337. delTr.forEach(function (deletedT) {
  81338. if (uniqueArray.indexOf(deletedT) === -1) {
  81339. deletedT.deletePending = true;
  81340. uniqueArray.push(deletedT);
  81341. }
  81342. });
  81343. if (uniqueArray.length % 2 !== 0) {
  81344. continue;
  81345. }
  81346. v0.q = v1.q.add(v0.q);
  81347. v0.updatePosition(p);
  81348. var tStart = _this.references.length;
  81349. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  81350. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  81351. var tCount = _this.references.length - tStart;
  81352. if (tCount <= v0.triangleCount) {
  81353. if (tCount) {
  81354. for (var c = 0; c < tCount; c++) {
  81355. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  81356. }
  81357. }
  81358. }
  81359. else {
  81360. v0.triangleStart = tStart;
  81361. }
  81362. v0.triangleCount = tCount;
  81363. break;
  81364. }
  81365. }
  81366. };
  81367. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  81368. }, 0);
  81369. };
  81370. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  81371. if (triangleCount - deletedTriangles <= targetCount)
  81372. loop.breakLoop();
  81373. else {
  81374. iterationFunction(loop.index, function () {
  81375. loop.executeNext();
  81376. });
  81377. }
  81378. }, function () {
  81379. setTimeout(function () {
  81380. //reconstruct this part of the mesh
  81381. _this.reconstructMesh(submeshIndex);
  81382. successCallback();
  81383. }, 0);
  81384. });
  81385. };
  81386. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  81387. var _this = this;
  81388. this.vertices = [];
  81389. this.triangles = [];
  81390. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81391. var indices = this._mesh.getIndices();
  81392. var submesh = this._mesh.subMeshes[submeshIndex];
  81393. var findInVertices = function (positionToSearch) {
  81394. if (optimizeMesh) {
  81395. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  81396. if (_this.vertices[ii].position.equals(positionToSearch)) {
  81397. return _this.vertices[ii];
  81398. }
  81399. }
  81400. }
  81401. return null;
  81402. };
  81403. var vertexReferences = [];
  81404. var vertexInit = function (i) {
  81405. if (!positionData) {
  81406. return;
  81407. }
  81408. var offset = i + submesh.verticesStart;
  81409. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  81410. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  81411. vertex.originalOffsets.push(offset);
  81412. if (vertex.id === _this.vertices.length) {
  81413. _this.vertices.push(vertex);
  81414. }
  81415. vertexReferences.push(vertex.id);
  81416. };
  81417. //var totalVertices = mesh.getTotalVertices();
  81418. var totalVertices = submesh.verticesCount;
  81419. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  81420. var indicesInit = function (i) {
  81421. if (!indices) {
  81422. return;
  81423. }
  81424. var offset = (submesh.indexStart / 3) + i;
  81425. var pos = (offset * 3);
  81426. var i0 = indices[pos + 0];
  81427. var i1 = indices[pos + 1];
  81428. var i2 = indices[pos + 2];
  81429. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  81430. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  81431. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  81432. var triangle = new DecimationTriangle([v0, v1, v2]);
  81433. triangle.originalOffset = pos;
  81434. _this.triangles.push(triangle);
  81435. };
  81436. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  81437. _this.init(callback);
  81438. });
  81439. });
  81440. };
  81441. QuadraticErrorSimplification.prototype.init = function (callback) {
  81442. var _this = this;
  81443. var triangleInit1 = function (i) {
  81444. var t = _this.triangles[i];
  81445. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  81446. for (var j = 0; j < 3; j++) {
  81447. 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))));
  81448. }
  81449. };
  81450. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  81451. var triangleInit2 = function (i) {
  81452. var t = _this.triangles[i];
  81453. for (var j = 0; j < 3; ++j) {
  81454. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  81455. }
  81456. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81457. };
  81458. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  81459. callback();
  81460. });
  81461. });
  81462. };
  81463. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  81464. var newTriangles = [];
  81465. var i;
  81466. for (i = 0; i < this.vertices.length; ++i) {
  81467. this.vertices[i].triangleCount = 0;
  81468. }
  81469. var t;
  81470. var j;
  81471. for (i = 0; i < this.triangles.length; ++i) {
  81472. if (!this.triangles[i].deleted) {
  81473. t = this.triangles[i];
  81474. for (j = 0; j < 3; ++j) {
  81475. t.vertices[j].triangleCount = 1;
  81476. }
  81477. newTriangles.push(t);
  81478. }
  81479. }
  81480. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  81481. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  81482. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  81483. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  81484. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  81485. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81486. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  81487. var vertexCount = 0;
  81488. for (i = 0; i < this.vertices.length; ++i) {
  81489. var vertex = this.vertices[i];
  81490. vertex.id = vertexCount;
  81491. if (vertex.triangleCount) {
  81492. vertex.originalOffsets.forEach(function (originalOffset) {
  81493. if (!normalData) {
  81494. return;
  81495. }
  81496. newPositionData.push(vertex.position.x);
  81497. newPositionData.push(vertex.position.y);
  81498. newPositionData.push(vertex.position.z);
  81499. newNormalData.push(normalData[originalOffset * 3]);
  81500. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  81501. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  81502. if (uvs && uvs.length) {
  81503. newUVsData.push(uvs[(originalOffset * 2)]);
  81504. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  81505. }
  81506. else if (colorsData && colorsData.length) {
  81507. newColorsData.push(colorsData[(originalOffset * 4)]);
  81508. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  81509. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  81510. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  81511. }
  81512. ++vertexCount;
  81513. });
  81514. }
  81515. }
  81516. var startingIndex = this._reconstructedMesh.getTotalIndices();
  81517. var startingVertex = this._reconstructedMesh.getTotalVertices();
  81518. var submeshesArray = this._reconstructedMesh.subMeshes;
  81519. this._reconstructedMesh.subMeshes = [];
  81520. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  81521. var originalIndices = this._mesh.getIndices();
  81522. for (i = 0; i < newTriangles.length; ++i) {
  81523. t = newTriangles[i]; //now get the new referencing point for each vertex
  81524. [0, 1, 2].forEach(function (idx) {
  81525. var id = originalIndices[t.originalOffset + idx];
  81526. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  81527. if (offset < 0)
  81528. offset = 0;
  81529. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  81530. });
  81531. }
  81532. //overwriting the old vertex buffers and indices.
  81533. this._reconstructedMesh.setIndices(newIndicesArray);
  81534. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  81535. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  81536. if (newUVsData.length > 0)
  81537. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  81538. if (newColorsData.length > 0)
  81539. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  81540. //create submesh
  81541. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  81542. if (submeshIndex > 0) {
  81543. this._reconstructedMesh.subMeshes = [];
  81544. submeshesArray.forEach(function (submesh) {
  81545. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  81546. });
  81547. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  81548. }
  81549. };
  81550. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  81551. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  81552. this._reconstructedMesh.material = this._mesh.material;
  81553. this._reconstructedMesh.parent = this._mesh.parent;
  81554. this._reconstructedMesh.isVisible = false;
  81555. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  81556. };
  81557. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  81558. for (var i = 0; i < vertex1.triangleCount; ++i) {
  81559. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  81560. if (t.deleted)
  81561. continue;
  81562. var s = this.references[vertex1.triangleStart + i].vertexId;
  81563. var v1 = t.vertices[(s + 1) % 3];
  81564. var v2 = t.vertices[(s + 2) % 3];
  81565. if ((v1 === vertex2 || v2 === vertex2)) {
  81566. deletedArray[i] = true;
  81567. delTr.push(t);
  81568. continue;
  81569. }
  81570. var d1 = v1.position.subtract(point);
  81571. d1 = d1.normalize();
  81572. var d2 = v2.position.subtract(point);
  81573. d2 = d2.normalize();
  81574. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  81575. return true;
  81576. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  81577. deletedArray[i] = false;
  81578. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  81579. return true;
  81580. }
  81581. return false;
  81582. };
  81583. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  81584. var newDeleted = deletedTriangles;
  81585. for (var i = 0; i < vertex.triangleCount; ++i) {
  81586. var ref = this.references[vertex.triangleStart + i];
  81587. var t = this.triangles[ref.triangleId];
  81588. if (t.deleted)
  81589. continue;
  81590. if (deletedArray[i] && t.deletePending) {
  81591. t.deleted = true;
  81592. newDeleted++;
  81593. continue;
  81594. }
  81595. t.vertices[ref.vertexId] = origVertex;
  81596. t.isDirty = true;
  81597. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  81598. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  81599. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  81600. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  81601. this.references.push(ref);
  81602. }
  81603. return newDeleted;
  81604. };
  81605. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  81606. for (var i = 0; i < this.vertices.length; ++i) {
  81607. var vCount = [];
  81608. var vId = [];
  81609. var v = this.vertices[i];
  81610. var j;
  81611. for (j = 0; j < v.triangleCount; ++j) {
  81612. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  81613. for (var ii = 0; ii < 3; ii++) {
  81614. var ofs = 0;
  81615. var vv = triangle.vertices[ii];
  81616. while (ofs < vCount.length) {
  81617. if (vId[ofs] === vv.id)
  81618. break;
  81619. ++ofs;
  81620. }
  81621. if (ofs === vCount.length) {
  81622. vCount.push(1);
  81623. vId.push(vv.id);
  81624. }
  81625. else {
  81626. vCount[ofs]++;
  81627. }
  81628. }
  81629. }
  81630. for (j = 0; j < vCount.length; ++j) {
  81631. if (vCount[j] === 1) {
  81632. this.vertices[vId[j]].isBorder = true;
  81633. }
  81634. else {
  81635. this.vertices[vId[j]].isBorder = false;
  81636. }
  81637. }
  81638. }
  81639. };
  81640. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  81641. if (identifyBorders === void 0) { identifyBorders = false; }
  81642. var i;
  81643. if (!identifyBorders) {
  81644. var newTrianglesVector = [];
  81645. for (i = 0; i < this.triangles.length; ++i) {
  81646. if (!this.triangles[i].deleted) {
  81647. newTrianglesVector.push(this.triangles[i]);
  81648. }
  81649. }
  81650. this.triangles = newTrianglesVector;
  81651. }
  81652. for (i = 0; i < this.vertices.length; ++i) {
  81653. this.vertices[i].triangleCount = 0;
  81654. this.vertices[i].triangleStart = 0;
  81655. }
  81656. var t;
  81657. var j;
  81658. var v;
  81659. for (i = 0; i < this.triangles.length; ++i) {
  81660. t = this.triangles[i];
  81661. for (j = 0; j < 3; ++j) {
  81662. v = t.vertices[j];
  81663. v.triangleCount++;
  81664. }
  81665. }
  81666. var tStart = 0;
  81667. for (i = 0; i < this.vertices.length; ++i) {
  81668. this.vertices[i].triangleStart = tStart;
  81669. tStart += this.vertices[i].triangleCount;
  81670. this.vertices[i].triangleCount = 0;
  81671. }
  81672. var newReferences = new Array(this.triangles.length * 3);
  81673. for (i = 0; i < this.triangles.length; ++i) {
  81674. t = this.triangles[i];
  81675. for (j = 0; j < 3; ++j) {
  81676. v = t.vertices[j];
  81677. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  81678. v.triangleCount++;
  81679. }
  81680. }
  81681. this.references = newReferences;
  81682. if (identifyBorders) {
  81683. this.identifyBorder();
  81684. }
  81685. };
  81686. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  81687. var x = point.x;
  81688. var y = point.y;
  81689. var z = point.z;
  81690. 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
  81691. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  81692. };
  81693. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  81694. var q = vertex1.q.add(vertex2.q);
  81695. var border = vertex1.isBorder && vertex2.isBorder;
  81696. var error = 0;
  81697. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  81698. if (qDet !== 0 && !border) {
  81699. if (!pointResult) {
  81700. pointResult = BABYLON.Vector3.Zero();
  81701. }
  81702. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  81703. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  81704. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  81705. error = this.vertexError(q, pointResult);
  81706. }
  81707. else {
  81708. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  81709. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  81710. var error1 = this.vertexError(q, vertex1.position);
  81711. var error2 = this.vertexError(q, vertex2.position);
  81712. var error3 = this.vertexError(q, p3);
  81713. error = Math.min(error1, error2, error3);
  81714. if (error === error1) {
  81715. if (pointResult) {
  81716. pointResult.copyFrom(vertex1.position);
  81717. }
  81718. }
  81719. else if (error === error2) {
  81720. if (pointResult) {
  81721. pointResult.copyFrom(vertex2.position);
  81722. }
  81723. }
  81724. else {
  81725. if (pointResult) {
  81726. pointResult.copyFrom(p3);
  81727. }
  81728. }
  81729. }
  81730. return error;
  81731. };
  81732. return QuadraticErrorSimplification;
  81733. }());
  81734. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  81735. })(BABYLON || (BABYLON = {}));
  81736. //# sourceMappingURL=babylon.meshSimplification.js.map
  81737. var BABYLON;
  81738. (function (BABYLON) {
  81739. var MeshLODLevel = /** @class */ (function () {
  81740. function MeshLODLevel(distance, mesh) {
  81741. this.distance = distance;
  81742. this.mesh = mesh;
  81743. }
  81744. return MeshLODLevel;
  81745. }());
  81746. BABYLON.MeshLODLevel = MeshLODLevel;
  81747. })(BABYLON || (BABYLON = {}));
  81748. //# sourceMappingURL=babylon.meshLODLevel.js.map
  81749. var BABYLON;
  81750. (function (BABYLON) {
  81751. /**
  81752. * Defines the root class used to create scene optimization to use with SceneOptimizer
  81753. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81754. */
  81755. var SceneOptimization = /** @class */ (function () {
  81756. /**
  81757. * Creates the SceneOptimization object
  81758. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81759. * @param desc defines the description associated with the optimization
  81760. */
  81761. function SceneOptimization(
  81762. /**
  81763. * Defines the priority of this optimization (0 by default which means first in the list)
  81764. */
  81765. priority) {
  81766. if (priority === void 0) { priority = 0; }
  81767. this.priority = priority;
  81768. }
  81769. /**
  81770. * Gets a string describing the action executed by the current optimization
  81771. * @returns description string
  81772. */
  81773. SceneOptimization.prototype.getDescription = function () {
  81774. return "";
  81775. };
  81776. /**
  81777. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81778. * @param scene defines the current scene where to apply this optimization
  81779. * @param optimizer defines the current optimizer
  81780. * @returns true if everything that can be done was applied
  81781. */
  81782. SceneOptimization.prototype.apply = function (scene, optimizer) {
  81783. return true;
  81784. };
  81785. ;
  81786. return SceneOptimization;
  81787. }());
  81788. BABYLON.SceneOptimization = SceneOptimization;
  81789. /**
  81790. * Defines an optimization used to reduce the size of render target textures
  81791. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81792. */
  81793. var TextureOptimization = /** @class */ (function (_super) {
  81794. __extends(TextureOptimization, _super);
  81795. /**
  81796. * Creates the TextureOptimization object
  81797. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81798. * @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
  81799. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81800. */
  81801. function TextureOptimization(
  81802. /**
  81803. * Defines the priority of this optimization (0 by default which means first in the list)
  81804. */
  81805. priority,
  81806. /**
  81807. * 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
  81808. */
  81809. maximumSize,
  81810. /**
  81811. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  81812. */
  81813. step) {
  81814. if (priority === void 0) { priority = 0; }
  81815. if (maximumSize === void 0) { maximumSize = 1024; }
  81816. if (step === void 0) { step = 0.5; }
  81817. var _this = _super.call(this, priority) || this;
  81818. _this.priority = priority;
  81819. _this.maximumSize = maximumSize;
  81820. _this.step = step;
  81821. return _this;
  81822. }
  81823. /**
  81824. * Gets a string describing the action executed by the current optimization
  81825. * @returns description string
  81826. */
  81827. TextureOptimization.prototype.getDescription = function () {
  81828. return "Reducing render target texture size to " + this.maximumSize;
  81829. };
  81830. /**
  81831. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81832. * @param scene defines the current scene where to apply this optimization
  81833. * @param optimizer defines the current optimizer
  81834. * @returns true if everything that can be done was applied
  81835. */
  81836. TextureOptimization.prototype.apply = function (scene, optimizer) {
  81837. var allDone = true;
  81838. for (var index = 0; index < scene.textures.length; index++) {
  81839. var texture = scene.textures[index];
  81840. if (!texture.canRescale || texture.getContext) {
  81841. continue;
  81842. }
  81843. var currentSize = texture.getSize();
  81844. var maxDimension = Math.max(currentSize.width, currentSize.height);
  81845. if (maxDimension > this.maximumSize) {
  81846. texture.scale(this.step);
  81847. allDone = false;
  81848. }
  81849. }
  81850. return allDone;
  81851. };
  81852. return TextureOptimization;
  81853. }(SceneOptimization));
  81854. BABYLON.TextureOptimization = TextureOptimization;
  81855. /**
  81856. * Defines an optimization used to increase or decrease the rendering resolution
  81857. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81858. */
  81859. var HardwareScalingOptimization = /** @class */ (function (_super) {
  81860. __extends(HardwareScalingOptimization, _super);
  81861. /**
  81862. * Creates the HardwareScalingOptimization object
  81863. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  81864. * @param maximumScale defines the maximum scale to use (2 by default)
  81865. * @param step defines the step to use between two passes (0.5 by default)
  81866. */
  81867. function HardwareScalingOptimization(
  81868. /**
  81869. * Defines the priority of this optimization (0 by default which means first in the list)
  81870. */
  81871. priority,
  81872. /**
  81873. * Defines the maximum scale to use (2 by default)
  81874. */
  81875. maximumScale,
  81876. /**
  81877. * Defines the step to use between two passes (0.5 by default)
  81878. */
  81879. step) {
  81880. if (priority === void 0) { priority = 0; }
  81881. if (maximumScale === void 0) { maximumScale = 2; }
  81882. if (step === void 0) { step = 0.25; }
  81883. var _this = _super.call(this, priority) || this;
  81884. _this.priority = priority;
  81885. _this.maximumScale = maximumScale;
  81886. _this.step = step;
  81887. _this._currentScale = -1;
  81888. _this._directionOffset = 1;
  81889. return _this;
  81890. }
  81891. /**
  81892. * Gets a string describing the action executed by the current optimization
  81893. * @return description string
  81894. */
  81895. HardwareScalingOptimization.prototype.getDescription = function () {
  81896. return "Setting hardware scaling level to " + this._currentScale;
  81897. };
  81898. /**
  81899. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81900. * @param scene defines the current scene where to apply this optimization
  81901. * @param optimizer defines the current optimizer
  81902. * @returns true if everything that can be done was applied
  81903. */
  81904. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  81905. if (this._currentScale === -1) {
  81906. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  81907. if (this._currentScale > this.maximumScale) {
  81908. this._directionOffset = -1;
  81909. }
  81910. }
  81911. this._currentScale += this._directionOffset * this.step;
  81912. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  81913. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  81914. };
  81915. ;
  81916. return HardwareScalingOptimization;
  81917. }(SceneOptimization));
  81918. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  81919. /**
  81920. * Defines an optimization used to remove shadows
  81921. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81922. */
  81923. var ShadowsOptimization = /** @class */ (function (_super) {
  81924. __extends(ShadowsOptimization, _super);
  81925. function ShadowsOptimization() {
  81926. return _super !== null && _super.apply(this, arguments) || this;
  81927. }
  81928. /**
  81929. * Gets a string describing the action executed by the current optimization
  81930. * @return description string
  81931. */
  81932. ShadowsOptimization.prototype.getDescription = function () {
  81933. return "Turning shadows on/off";
  81934. };
  81935. /**
  81936. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81937. * @param scene defines the current scene where to apply this optimization
  81938. * @param optimizer defines the current optimizer
  81939. * @returns true if everything that can be done was applied
  81940. */
  81941. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  81942. scene.shadowsEnabled = optimizer.isInImprovementMode;
  81943. return true;
  81944. };
  81945. ;
  81946. return ShadowsOptimization;
  81947. }(SceneOptimization));
  81948. BABYLON.ShadowsOptimization = ShadowsOptimization;
  81949. /**
  81950. * Defines an optimization used to turn post-processes off
  81951. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81952. */
  81953. var PostProcessesOptimization = /** @class */ (function (_super) {
  81954. __extends(PostProcessesOptimization, _super);
  81955. function PostProcessesOptimization() {
  81956. return _super !== null && _super.apply(this, arguments) || this;
  81957. }
  81958. /**
  81959. * Gets a string describing the action executed by the current optimization
  81960. * @return description string
  81961. */
  81962. PostProcessesOptimization.prototype.getDescription = function () {
  81963. return "Turning post-processes on/off";
  81964. };
  81965. /**
  81966. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81967. * @param scene defines the current scene where to apply this optimization
  81968. * @param optimizer defines the current optimizer
  81969. * @returns true if everything that can be done was applied
  81970. */
  81971. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  81972. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  81973. return true;
  81974. };
  81975. ;
  81976. return PostProcessesOptimization;
  81977. }(SceneOptimization));
  81978. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  81979. /**
  81980. * Defines an optimization used to turn lens flares off
  81981. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  81982. */
  81983. var LensFlaresOptimization = /** @class */ (function (_super) {
  81984. __extends(LensFlaresOptimization, _super);
  81985. function LensFlaresOptimization() {
  81986. return _super !== null && _super.apply(this, arguments) || this;
  81987. }
  81988. /**
  81989. * Gets a string describing the action executed by the current optimization
  81990. * @return description string
  81991. */
  81992. LensFlaresOptimization.prototype.getDescription = function () {
  81993. return "Turning lens flares on/off";
  81994. };
  81995. /**
  81996. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  81997. * @param scene defines the current scene where to apply this optimization
  81998. * @param optimizer defines the current optimizer
  81999. * @returns true if everything that can be done was applied
  82000. */
  82001. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82002. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82003. return true;
  82004. };
  82005. ;
  82006. return LensFlaresOptimization;
  82007. }(SceneOptimization));
  82008. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82009. /**
  82010. * Defines an optimization based on user defined callback.
  82011. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82012. */
  82013. var CustomOptimization = /** @class */ (function (_super) {
  82014. __extends(CustomOptimization, _super);
  82015. function CustomOptimization() {
  82016. return _super !== null && _super.apply(this, arguments) || this;
  82017. }
  82018. /**
  82019. * Gets a string describing the action executed by the current optimization
  82020. * @returns description string
  82021. */
  82022. CustomOptimization.prototype.getDescription = function () {
  82023. if (this.onGetDescription) {
  82024. return this.onGetDescription();
  82025. }
  82026. return "Running user defined callback";
  82027. };
  82028. /**
  82029. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82030. * @param scene defines the current scene where to apply this optimization
  82031. * @param optimizer defines the current optimizer
  82032. * @returns true if everything that can be done was applied
  82033. */
  82034. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82035. if (this.onApply) {
  82036. return this.onApply(scene, optimizer);
  82037. }
  82038. return true;
  82039. };
  82040. ;
  82041. return CustomOptimization;
  82042. }(SceneOptimization));
  82043. BABYLON.CustomOptimization = CustomOptimization;
  82044. /**
  82045. * Defines an optimization used to turn particles off
  82046. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82047. */
  82048. var ParticlesOptimization = /** @class */ (function (_super) {
  82049. __extends(ParticlesOptimization, _super);
  82050. function ParticlesOptimization() {
  82051. return _super !== null && _super.apply(this, arguments) || this;
  82052. }
  82053. /**
  82054. * Gets a string describing the action executed by the current optimization
  82055. * @return description string
  82056. */
  82057. ParticlesOptimization.prototype.getDescription = function () {
  82058. return "Turning particles on/off";
  82059. };
  82060. /**
  82061. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82062. * @param scene defines the current scene where to apply this optimization
  82063. * @param optimizer defines the current optimizer
  82064. * @returns true if everything that can be done was applied
  82065. */
  82066. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82067. scene.particlesEnabled = optimizer.isInImprovementMode;
  82068. return true;
  82069. };
  82070. ;
  82071. return ParticlesOptimization;
  82072. }(SceneOptimization));
  82073. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82074. /**
  82075. * Defines an optimization used to turn render targets off
  82076. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82077. */
  82078. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82079. __extends(RenderTargetsOptimization, _super);
  82080. function RenderTargetsOptimization() {
  82081. return _super !== null && _super.apply(this, arguments) || this;
  82082. }
  82083. /**
  82084. * Gets a string describing the action executed by the current optimization
  82085. * @return description string
  82086. */
  82087. RenderTargetsOptimization.prototype.getDescription = function () {
  82088. return "Turning render targets off";
  82089. };
  82090. /**
  82091. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82092. * @param scene defines the current scene where to apply this optimization
  82093. * @param optimizer defines the current optimizer
  82094. * @returns true if everything that can be done was applied
  82095. */
  82096. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82097. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82098. return true;
  82099. };
  82100. ;
  82101. return RenderTargetsOptimization;
  82102. }(SceneOptimization));
  82103. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82104. /**
  82105. * Defines an optimization used to merge meshes with compatible materials
  82106. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82107. */
  82108. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82109. __extends(MergeMeshesOptimization, _super);
  82110. function MergeMeshesOptimization() {
  82111. var _this = _super !== null && _super.apply(this, arguments) || this;
  82112. _this._canBeMerged = function (abstractMesh) {
  82113. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82114. return false;
  82115. }
  82116. var mesh = abstractMesh;
  82117. if (!mesh.isVisible || !mesh.isEnabled()) {
  82118. return false;
  82119. }
  82120. if (mesh.instances.length > 0) {
  82121. return false;
  82122. }
  82123. if (mesh.skeleton || mesh.hasLODLevels) {
  82124. return false;
  82125. }
  82126. if (mesh.parent) {
  82127. return false;
  82128. }
  82129. return true;
  82130. };
  82131. return _this;
  82132. }
  82133. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82134. /**
  82135. * Gets or sets a boolean which defines if optimization octree has to be updated
  82136. */
  82137. get: function () {
  82138. return MergeMeshesOptimization._UpdateSelectionTree;
  82139. },
  82140. /**
  82141. * Gets or sets a boolean which defines if optimization octree has to be updated
  82142. */
  82143. set: function (value) {
  82144. MergeMeshesOptimization._UpdateSelectionTree = value;
  82145. },
  82146. enumerable: true,
  82147. configurable: true
  82148. });
  82149. /**
  82150. * Gets a string describing the action executed by the current optimization
  82151. * @return description string
  82152. */
  82153. MergeMeshesOptimization.prototype.getDescription = function () {
  82154. return "Merging similar meshes together";
  82155. };
  82156. /**
  82157. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82158. * @param scene defines the current scene where to apply this optimization
  82159. * @param optimizer defines the current optimizer
  82160. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82161. * @returns true if everything that can be done was applied
  82162. */
  82163. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82164. var globalPool = scene.meshes.slice(0);
  82165. var globalLength = globalPool.length;
  82166. for (var index = 0; index < globalLength; index++) {
  82167. var currentPool = new Array();
  82168. var current = globalPool[index];
  82169. // Checks
  82170. if (!this._canBeMerged(current)) {
  82171. continue;
  82172. }
  82173. currentPool.push(current);
  82174. // Find compatible meshes
  82175. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82176. var otherMesh = globalPool[subIndex];
  82177. if (!this._canBeMerged(otherMesh)) {
  82178. continue;
  82179. }
  82180. if (otherMesh.material !== current.material) {
  82181. continue;
  82182. }
  82183. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82184. continue;
  82185. }
  82186. currentPool.push(otherMesh);
  82187. globalLength--;
  82188. globalPool.splice(subIndex, 1);
  82189. subIndex--;
  82190. }
  82191. if (currentPool.length < 2) {
  82192. continue;
  82193. }
  82194. // Merge meshes
  82195. BABYLON.Mesh.MergeMeshes(currentPool);
  82196. }
  82197. if (updateSelectionTree != undefined) {
  82198. if (updateSelectionTree) {
  82199. scene.createOrUpdateSelectionOctree();
  82200. }
  82201. }
  82202. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82203. scene.createOrUpdateSelectionOctree();
  82204. }
  82205. return true;
  82206. };
  82207. ;
  82208. MergeMeshesOptimization._UpdateSelectionTree = false;
  82209. return MergeMeshesOptimization;
  82210. }(SceneOptimization));
  82211. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82212. /**
  82213. * Defines a list of options used by SceneOptimizer
  82214. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82215. */
  82216. var SceneOptimizerOptions = /** @class */ (function () {
  82217. /**
  82218. * Creates a new list of options used by SceneOptimizer
  82219. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82220. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82221. */
  82222. function SceneOptimizerOptions(
  82223. /**
  82224. * Defines the target frame rate to reach (60 by default)
  82225. */
  82226. targetFrameRate,
  82227. /**
  82228. * Defines the interval between two checkes (2000ms by default)
  82229. */
  82230. trackerDuration) {
  82231. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82232. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82233. this.targetFrameRate = targetFrameRate;
  82234. this.trackerDuration = trackerDuration;
  82235. /**
  82236. * Gets the list of optimizations to apply
  82237. */
  82238. this.optimizations = new Array();
  82239. }
  82240. /**
  82241. * Add a new optimization
  82242. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82243. * @returns the current SceneOptimizerOptions
  82244. */
  82245. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82246. this.optimizations.push(optimization);
  82247. return this;
  82248. };
  82249. /**
  82250. * Add a new custom optimization
  82251. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82252. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82253. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82254. * @returns the current SceneOptimizerOptions
  82255. */
  82256. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82257. if (priority === void 0) { priority = 0; }
  82258. var optimization = new CustomOptimization(priority);
  82259. optimization.onApply = onApply;
  82260. optimization.onGetDescription = onGetDescription;
  82261. this.optimizations.push(optimization);
  82262. return this;
  82263. };
  82264. /**
  82265. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82266. * @param targetFrameRate defines the target frame rate (60 by default)
  82267. * @returns a SceneOptimizerOptions object
  82268. */
  82269. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82270. var result = new SceneOptimizerOptions(targetFrameRate);
  82271. var priority = 0;
  82272. result.addOptimization(new MergeMeshesOptimization(priority));
  82273. result.addOptimization(new ShadowsOptimization(priority));
  82274. result.addOptimization(new LensFlaresOptimization(priority));
  82275. // Next priority
  82276. priority++;
  82277. result.addOptimization(new PostProcessesOptimization(priority));
  82278. result.addOptimization(new ParticlesOptimization(priority));
  82279. // Next priority
  82280. priority++;
  82281. result.addOptimization(new TextureOptimization(priority, 1024));
  82282. return result;
  82283. };
  82284. /**
  82285. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82286. * @param targetFrameRate defines the target frame rate (60 by default)
  82287. * @returns a SceneOptimizerOptions object
  82288. */
  82289. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82290. var result = new SceneOptimizerOptions(targetFrameRate);
  82291. var priority = 0;
  82292. result.addOptimization(new MergeMeshesOptimization(priority));
  82293. result.addOptimization(new ShadowsOptimization(priority));
  82294. result.addOptimization(new LensFlaresOptimization(priority));
  82295. // Next priority
  82296. priority++;
  82297. result.addOptimization(new PostProcessesOptimization(priority));
  82298. result.addOptimization(new ParticlesOptimization(priority));
  82299. // Next priority
  82300. priority++;
  82301. result.addOptimization(new TextureOptimization(priority, 512));
  82302. // Next priority
  82303. priority++;
  82304. result.addOptimization(new RenderTargetsOptimization(priority));
  82305. // Next priority
  82306. priority++;
  82307. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82308. return result;
  82309. };
  82310. /**
  82311. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  82312. * @param targetFrameRate defines the target frame rate (60 by default)
  82313. * @returns a SceneOptimizerOptions object
  82314. */
  82315. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  82316. var result = new SceneOptimizerOptions(targetFrameRate);
  82317. var priority = 0;
  82318. result.addOptimization(new MergeMeshesOptimization(priority));
  82319. result.addOptimization(new ShadowsOptimization(priority));
  82320. result.addOptimization(new LensFlaresOptimization(priority));
  82321. // Next priority
  82322. priority++;
  82323. result.addOptimization(new PostProcessesOptimization(priority));
  82324. result.addOptimization(new ParticlesOptimization(priority));
  82325. // Next priority
  82326. priority++;
  82327. result.addOptimization(new TextureOptimization(priority, 256));
  82328. // Next priority
  82329. priority++;
  82330. result.addOptimization(new RenderTargetsOptimization(priority));
  82331. // Next priority
  82332. priority++;
  82333. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  82334. return result;
  82335. };
  82336. return SceneOptimizerOptions;
  82337. }());
  82338. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  82339. /**
  82340. * Class used to run optimizations in order to reach a target frame rate
  82341. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82342. */
  82343. var SceneOptimizer = /** @class */ (function () {
  82344. /**
  82345. * Creates a new SceneOptimizer
  82346. * @param scene defines the scene to work on
  82347. * @param options defines the options to use with the SceneOptimizer
  82348. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  82349. * @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)
  82350. */
  82351. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  82352. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  82353. if (improvementMode === void 0) { improvementMode = false; }
  82354. var _this = this;
  82355. this._isRunning = false;
  82356. this._currentPriorityLevel = 0;
  82357. this._targetFrameRate = 60;
  82358. this._trackerDuration = 2000;
  82359. this._currentFrameRate = 0;
  82360. this._improvementMode = false;
  82361. /**
  82362. * Defines an observable called when the optimizer reaches the target frame rate
  82363. */
  82364. this.onSuccessObservable = new BABYLON.Observable();
  82365. /**
  82366. * Defines an observable called when the optimizer enables an optimization
  82367. */
  82368. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  82369. /**
  82370. * Defines an observable called when the optimizer is not able to reach the target frame rate
  82371. */
  82372. this.onFailureObservable = new BABYLON.Observable();
  82373. if (!options) {
  82374. this._options = new SceneOptimizerOptions();
  82375. }
  82376. else {
  82377. this._options = options;
  82378. }
  82379. if (this._options.targetFrameRate) {
  82380. this._targetFrameRate = this._options.targetFrameRate;
  82381. }
  82382. if (this._options.trackerDuration) {
  82383. this._trackerDuration = this._options.trackerDuration;
  82384. }
  82385. if (autoGeneratePriorities) {
  82386. var priority = 0;
  82387. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  82388. var optim = _a[_i];
  82389. optim.priority = priority++;
  82390. }
  82391. }
  82392. this._improvementMode = improvementMode;
  82393. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82394. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  82395. _this._sceneDisposeObserver = null;
  82396. _this.dispose();
  82397. });
  82398. }
  82399. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  82400. /**
  82401. * Gets a boolean indicating if the optimizer is in improvement mode
  82402. */
  82403. get: function () {
  82404. return this._improvementMode;
  82405. },
  82406. enumerable: true,
  82407. configurable: true
  82408. });
  82409. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  82410. /**
  82411. * Gets the current priority level (0 at start)
  82412. */
  82413. get: function () {
  82414. return this._currentPriorityLevel;
  82415. },
  82416. enumerable: true,
  82417. configurable: true
  82418. });
  82419. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  82420. /**
  82421. * Gets the current frame rate checked by the SceneOptimizer
  82422. */
  82423. get: function () {
  82424. return this._currentFrameRate;
  82425. },
  82426. enumerable: true,
  82427. configurable: true
  82428. });
  82429. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  82430. /**
  82431. * Gets or sets the current target frame rate (60 by default)
  82432. */
  82433. get: function () {
  82434. return this._targetFrameRate;
  82435. },
  82436. /**
  82437. * Gets or sets the current target frame rate (60 by default)
  82438. */
  82439. set: function (value) {
  82440. this._targetFrameRate = value;
  82441. },
  82442. enumerable: true,
  82443. configurable: true
  82444. });
  82445. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  82446. /**
  82447. * Gets or sets the current interval between two checks (every 2000ms by default)
  82448. */
  82449. get: function () {
  82450. return this._trackerDuration;
  82451. },
  82452. /**
  82453. * Gets or sets the current interval between two checks (every 2000ms by default)
  82454. */
  82455. set: function (value) {
  82456. this._trackerDuration = value;
  82457. },
  82458. enumerable: true,
  82459. configurable: true
  82460. });
  82461. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  82462. /**
  82463. * Gets the list of active optimizations
  82464. */
  82465. get: function () {
  82466. return this._options.optimizations;
  82467. },
  82468. enumerable: true,
  82469. configurable: true
  82470. });
  82471. /**
  82472. * Stops the current optimizer
  82473. */
  82474. SceneOptimizer.prototype.stop = function () {
  82475. this._isRunning = false;
  82476. };
  82477. /**
  82478. * Reset the optimizer to initial step (current priority level = 0)
  82479. */
  82480. SceneOptimizer.prototype.reset = function () {
  82481. this._currentPriorityLevel = 0;
  82482. };
  82483. /**
  82484. * Start the optimizer. By default it will try to reach a specific framerate
  82485. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  82486. */
  82487. SceneOptimizer.prototype.start = function () {
  82488. var _this = this;
  82489. if (this._isRunning) {
  82490. return;
  82491. }
  82492. this._isRunning = true;
  82493. // Let's wait for the scene to be ready before running our check
  82494. this._scene.executeWhenReady(function () {
  82495. setTimeout(function () {
  82496. _this._checkCurrentState();
  82497. }, _this._trackerDuration);
  82498. });
  82499. };
  82500. SceneOptimizer.prototype._checkCurrentState = function () {
  82501. var _this = this;
  82502. if (!this._isRunning) {
  82503. return;
  82504. }
  82505. var scene = this._scene;
  82506. var options = this._options;
  82507. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  82508. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  82509. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  82510. this._isRunning = false;
  82511. this.onSuccessObservable.notifyObservers(this);
  82512. return;
  82513. }
  82514. // Apply current level of optimizations
  82515. var allDone = true;
  82516. var noOptimizationApplied = true;
  82517. for (var index = 0; index < options.optimizations.length; index++) {
  82518. var optimization = options.optimizations[index];
  82519. if (optimization.priority === this._currentPriorityLevel) {
  82520. noOptimizationApplied = false;
  82521. allDone = allDone && optimization.apply(scene, this);
  82522. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  82523. }
  82524. }
  82525. // If no optimization was applied, this is a failure :(
  82526. if (noOptimizationApplied) {
  82527. this._isRunning = false;
  82528. this.onFailureObservable.notifyObservers(this);
  82529. return;
  82530. }
  82531. // If all optimizations were done, move to next level
  82532. if (allDone) {
  82533. this._currentPriorityLevel++;
  82534. }
  82535. // Let's the system running for a specific amount of time before checking FPS
  82536. scene.executeWhenReady(function () {
  82537. setTimeout(function () {
  82538. _this._checkCurrentState();
  82539. }, _this._trackerDuration);
  82540. });
  82541. };
  82542. /**
  82543. * Release all resources
  82544. */
  82545. SceneOptimizer.prototype.dispose = function () {
  82546. this.stop();
  82547. this.onSuccessObservable.clear();
  82548. this.onFailureObservable.clear();
  82549. this.onNewOptimizationAppliedObservable.clear();
  82550. if (this._sceneDisposeObserver) {
  82551. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  82552. }
  82553. };
  82554. /**
  82555. * Helper function to create a SceneOptimizer with one single line of code
  82556. * @param scene defines the scene to work on
  82557. * @param options defines the options to use with the SceneOptimizer
  82558. * @param onSuccess defines a callback to call on success
  82559. * @param onFailure defines a callback to call on failure
  82560. * @returns the new SceneOptimizer object
  82561. */
  82562. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  82563. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  82564. if (onSuccess) {
  82565. optimizer.onSuccessObservable.add(function () {
  82566. onSuccess();
  82567. });
  82568. }
  82569. if (onFailure) {
  82570. optimizer.onFailureObservable.add(function () {
  82571. onFailure();
  82572. });
  82573. }
  82574. optimizer.start();
  82575. return optimizer;
  82576. };
  82577. return SceneOptimizer;
  82578. }());
  82579. BABYLON.SceneOptimizer = SceneOptimizer;
  82580. })(BABYLON || (BABYLON = {}));
  82581. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  82582. var BABYLON;
  82583. (function (BABYLON) {
  82584. var OutlineRenderer = /** @class */ (function () {
  82585. function OutlineRenderer(scene) {
  82586. this.zOffset = 1;
  82587. this._scene = scene;
  82588. }
  82589. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  82590. var _this = this;
  82591. if (useOverlay === void 0) { useOverlay = false; }
  82592. var scene = this._scene;
  82593. var engine = this._scene.getEngine();
  82594. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  82595. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  82596. return;
  82597. }
  82598. var mesh = subMesh.getRenderingMesh();
  82599. var material = subMesh.getMaterial();
  82600. if (!material || !scene.activeCamera) {
  82601. return;
  82602. }
  82603. engine.enableEffect(this._effect);
  82604. // Logarithmic depth
  82605. if (material.useLogarithmicDepth) {
  82606. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  82607. }
  82608. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  82609. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  82610. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  82611. // Bones
  82612. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  82613. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  82614. }
  82615. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  82616. // Alpha test
  82617. if (material && material.needAlphaTesting()) {
  82618. var alphaTexture = material.getAlphaTestTexture();
  82619. if (alphaTexture) {
  82620. this._effect.setTexture("diffuseSampler", alphaTexture);
  82621. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  82622. }
  82623. }
  82624. engine.setZOffset(-this.zOffset);
  82625. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  82626. engine.setZOffset(0);
  82627. };
  82628. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  82629. var defines = [];
  82630. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  82631. var mesh = subMesh.getMesh();
  82632. var material = subMesh.getMaterial();
  82633. if (material) {
  82634. // Alpha test
  82635. if (material.needAlphaTesting()) {
  82636. defines.push("#define ALPHATEST");
  82637. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  82638. attribs.push(BABYLON.VertexBuffer.UVKind);
  82639. defines.push("#define UV1");
  82640. }
  82641. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  82642. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  82643. defines.push("#define UV2");
  82644. }
  82645. }
  82646. //Logarithmic depth
  82647. if (material.useLogarithmicDepth) {
  82648. defines.push("#define LOGARITHMICDEPTH");
  82649. }
  82650. }
  82651. // Bones
  82652. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  82653. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  82654. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  82655. if (mesh.numBoneInfluencers > 4) {
  82656. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  82657. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  82658. }
  82659. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  82660. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  82661. }
  82662. else {
  82663. defines.push("#define NUM_BONE_INFLUENCERS 0");
  82664. }
  82665. // Instances
  82666. if (useInstances) {
  82667. defines.push("#define INSTANCES");
  82668. attribs.push("world0");
  82669. attribs.push("world1");
  82670. attribs.push("world2");
  82671. attribs.push("world3");
  82672. }
  82673. // Get correct effect
  82674. var join = defines.join("\n");
  82675. if (this._cachedDefines !== join) {
  82676. this._cachedDefines = join;
  82677. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  82678. }
  82679. return this._effect.isReady();
  82680. };
  82681. return OutlineRenderer;
  82682. }());
  82683. BABYLON.OutlineRenderer = OutlineRenderer;
  82684. })(BABYLON || (BABYLON = {}));
  82685. //# sourceMappingURL=babylon.outlineRenderer.js.map
  82686. var BABYLON;
  82687. (function (BABYLON) {
  82688. var FaceAdjacencies = /** @class */ (function () {
  82689. function FaceAdjacencies() {
  82690. this.edges = new Array();
  82691. this.edgesConnectedCount = 0;
  82692. }
  82693. return FaceAdjacencies;
  82694. }());
  82695. var EdgesRenderer = /** @class */ (function () {
  82696. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  82697. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  82698. if (epsilon === void 0) { epsilon = 0.95; }
  82699. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  82700. this.edgesWidthScalerForOrthographic = 1000.0;
  82701. this.edgesWidthScalerForPerspective = 50.0;
  82702. this._linesPositions = new Array();
  82703. this._linesNormals = new Array();
  82704. this._linesIndices = new Array();
  82705. this._buffers = {};
  82706. this._checkVerticesInsteadOfIndices = false;
  82707. this._source = source;
  82708. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  82709. this._epsilon = epsilon;
  82710. this._prepareRessources();
  82711. this._generateEdgesLines();
  82712. }
  82713. EdgesRenderer.prototype._prepareRessources = function () {
  82714. if (this._lineShader) {
  82715. return;
  82716. }
  82717. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  82718. attributes: ["position", "normal"],
  82719. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  82720. });
  82721. this._lineShader.disableDepthWrite = true;
  82722. this._lineShader.backFaceCulling = false;
  82723. };
  82724. EdgesRenderer.prototype._rebuild = function () {
  82725. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82726. if (buffer) {
  82727. buffer._rebuild();
  82728. }
  82729. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82730. if (buffer) {
  82731. buffer._rebuild();
  82732. }
  82733. var scene = this._source.getScene();
  82734. var engine = scene.getEngine();
  82735. this._ib = engine.createIndexBuffer(this._linesIndices);
  82736. };
  82737. EdgesRenderer.prototype.dispose = function () {
  82738. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  82739. if (buffer) {
  82740. buffer.dispose();
  82741. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  82742. }
  82743. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  82744. if (buffer) {
  82745. buffer.dispose();
  82746. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  82747. }
  82748. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  82749. this._lineShader.dispose();
  82750. };
  82751. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  82752. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  82753. return 0;
  82754. }
  82755. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  82756. return 1;
  82757. }
  82758. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  82759. return 2;
  82760. }
  82761. return -1;
  82762. };
  82763. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  82764. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  82765. return 0;
  82766. }
  82767. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  82768. return 1;
  82769. }
  82770. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  82771. return 2;
  82772. }
  82773. return -1;
  82774. };
  82775. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  82776. var needToCreateLine;
  82777. if (edge === undefined) {
  82778. needToCreateLine = true;
  82779. }
  82780. else {
  82781. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  82782. needToCreateLine = dotProduct < this._epsilon;
  82783. }
  82784. if (needToCreateLine) {
  82785. var offset = this._linesPositions.length / 3;
  82786. var normal = p0.subtract(p1);
  82787. normal.normalize();
  82788. // Positions
  82789. this._linesPositions.push(p0.x);
  82790. this._linesPositions.push(p0.y);
  82791. this._linesPositions.push(p0.z);
  82792. this._linesPositions.push(p0.x);
  82793. this._linesPositions.push(p0.y);
  82794. this._linesPositions.push(p0.z);
  82795. this._linesPositions.push(p1.x);
  82796. this._linesPositions.push(p1.y);
  82797. this._linesPositions.push(p1.z);
  82798. this._linesPositions.push(p1.x);
  82799. this._linesPositions.push(p1.y);
  82800. this._linesPositions.push(p1.z);
  82801. // Normals
  82802. this._linesNormals.push(p1.x);
  82803. this._linesNormals.push(p1.y);
  82804. this._linesNormals.push(p1.z);
  82805. this._linesNormals.push(-1);
  82806. this._linesNormals.push(p1.x);
  82807. this._linesNormals.push(p1.y);
  82808. this._linesNormals.push(p1.z);
  82809. this._linesNormals.push(1);
  82810. this._linesNormals.push(p0.x);
  82811. this._linesNormals.push(p0.y);
  82812. this._linesNormals.push(p0.z);
  82813. this._linesNormals.push(-1);
  82814. this._linesNormals.push(p0.x);
  82815. this._linesNormals.push(p0.y);
  82816. this._linesNormals.push(p0.z);
  82817. this._linesNormals.push(1);
  82818. // Indices
  82819. this._linesIndices.push(offset);
  82820. this._linesIndices.push(offset + 1);
  82821. this._linesIndices.push(offset + 2);
  82822. this._linesIndices.push(offset);
  82823. this._linesIndices.push(offset + 2);
  82824. this._linesIndices.push(offset + 3);
  82825. }
  82826. };
  82827. EdgesRenderer.prototype._generateEdgesLines = function () {
  82828. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  82829. var indices = this._source.getIndices();
  82830. if (!indices || !positions) {
  82831. return;
  82832. }
  82833. // First let's find adjacencies
  82834. var adjacencies = new Array();
  82835. var faceNormals = new Array();
  82836. var index;
  82837. var faceAdjacencies;
  82838. // Prepare faces
  82839. for (index = 0; index < indices.length; index += 3) {
  82840. faceAdjacencies = new FaceAdjacencies();
  82841. var p0Index = indices[index];
  82842. var p1Index = indices[index + 1];
  82843. var p2Index = indices[index + 2];
  82844. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  82845. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  82846. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  82847. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  82848. faceNormal.normalize();
  82849. faceNormals.push(faceNormal);
  82850. adjacencies.push(faceAdjacencies);
  82851. }
  82852. // Scan
  82853. for (index = 0; index < adjacencies.length; index++) {
  82854. faceAdjacencies = adjacencies[index];
  82855. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  82856. var otherFaceAdjacencies = adjacencies[otherIndex];
  82857. if (faceAdjacencies.edgesConnectedCount === 3) {
  82858. break;
  82859. }
  82860. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  82861. continue;
  82862. }
  82863. var otherP0 = indices[otherIndex * 3];
  82864. var otherP1 = indices[otherIndex * 3 + 1];
  82865. var otherP2 = indices[otherIndex * 3 + 2];
  82866. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  82867. var otherEdgeIndex = 0;
  82868. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  82869. continue;
  82870. }
  82871. switch (edgeIndex) {
  82872. case 0:
  82873. if (this._checkVerticesInsteadOfIndices) {
  82874. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82875. }
  82876. else {
  82877. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  82878. }
  82879. break;
  82880. case 1:
  82881. if (this._checkVerticesInsteadOfIndices) {
  82882. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82883. }
  82884. else {
  82885. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  82886. }
  82887. break;
  82888. case 2:
  82889. if (this._checkVerticesInsteadOfIndices) {
  82890. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  82891. }
  82892. else {
  82893. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  82894. }
  82895. break;
  82896. }
  82897. if (otherEdgeIndex === -1) {
  82898. continue;
  82899. }
  82900. faceAdjacencies.edges[edgeIndex] = otherIndex;
  82901. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  82902. faceAdjacencies.edgesConnectedCount++;
  82903. otherFaceAdjacencies.edgesConnectedCount++;
  82904. if (faceAdjacencies.edgesConnectedCount === 3) {
  82905. break;
  82906. }
  82907. }
  82908. }
  82909. }
  82910. // Create lines
  82911. for (index = 0; index < adjacencies.length; index++) {
  82912. // 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
  82913. var current = adjacencies[index];
  82914. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  82915. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  82916. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  82917. }
  82918. // Merge into a single mesh
  82919. var engine = this._source.getScene().getEngine();
  82920. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  82921. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  82922. this._ib = engine.createIndexBuffer(this._linesIndices);
  82923. this._indicesCount = this._linesIndices.length;
  82924. };
  82925. EdgesRenderer.prototype.render = function () {
  82926. var scene = this._source.getScene();
  82927. if (!this._lineShader.isReady() || !scene.activeCamera) {
  82928. return;
  82929. }
  82930. var engine = scene.getEngine();
  82931. this._lineShader._preBind();
  82932. // VBOs
  82933. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  82934. scene.resetCachedMaterial();
  82935. this._lineShader.setColor4("color", this._source.edgesColor);
  82936. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  82937. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  82938. }
  82939. else {
  82940. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  82941. }
  82942. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  82943. this._lineShader.bind(this._source.getWorldMatrix());
  82944. // Draw order
  82945. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  82946. this._lineShader.unbind();
  82947. engine.setDepthWrite(true);
  82948. };
  82949. return EdgesRenderer;
  82950. }());
  82951. BABYLON.EdgesRenderer = EdgesRenderer;
  82952. })(BABYLON || (BABYLON = {}));
  82953. //# sourceMappingURL=babylon.edgesRenderer.js.map
  82954. var __assign = (this && this.__assign) || Object.assign || function(t) {
  82955. for (var s, i = 1, n = arguments.length; i < n; i++) {
  82956. s = arguments[i];
  82957. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  82958. t[p] = s[p];
  82959. }
  82960. return t;
  82961. };
  82962. var BABYLON;
  82963. (function (BABYLON) {
  82964. /**
  82965. * The effect layer Helps adding post process effect blended with the main pass.
  82966. *
  82967. * This can be for instance use to generate glow or higlight effects on the scene.
  82968. *
  82969. * The effect layer class can not be used directly and is intented to inherited from to be
  82970. * customized per effects.
  82971. */
  82972. var EffectLayer = /** @class */ (function () {
  82973. /**
  82974. * Instantiates a new effect Layer and references it in the scene.
  82975. * @param name The name of the layer
  82976. * @param scene The scene to use the layer in
  82977. */
  82978. function EffectLayer(
  82979. /** The Friendly of the effect in the scene */
  82980. name, scene) {
  82981. this.name = name;
  82982. this._vertexBuffers = {};
  82983. this._maxSize = 0;
  82984. this._mainTextureDesiredSize = { width: 0, height: 0 };
  82985. this._shouldRender = true;
  82986. this._postProcesses = [];
  82987. this._textures = [];
  82988. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  82989. /**
  82990. * The clear color of the texture used to generate the glow map.
  82991. */
  82992. this.neutralColor = new BABYLON.Color4();
  82993. /**
  82994. * Specifies wether the highlight layer is enabled or not.
  82995. */
  82996. this.isEnabled = true;
  82997. /**
  82998. * An event triggered when the effect layer has been disposed.
  82999. */
  83000. this.onDisposeObservable = new BABYLON.Observable();
  83001. /**
  83002. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83003. */
  83004. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83005. /**
  83006. * An event triggered when the generated texture is being merged in the scene.
  83007. */
  83008. this.onBeforeComposeObservable = new BABYLON.Observable();
  83009. /**
  83010. * An event triggered when the generated texture has been merged in the scene.
  83011. */
  83012. this.onAfterComposeObservable = new BABYLON.Observable();
  83013. /**
  83014. * An event triggered when the efffect layer changes its size.
  83015. */
  83016. this.onSizeChangedObservable = new BABYLON.Observable();
  83017. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83018. this._engine = scene.getEngine();
  83019. this._maxSize = this._engine.getCaps().maxTextureSize;
  83020. this._scene.effectLayers.push(this);
  83021. // Generate Buffers
  83022. this._generateIndexBuffer();
  83023. this._genrateVertexBuffer();
  83024. }
  83025. Object.defineProperty(EffectLayer.prototype, "camera", {
  83026. /**
  83027. * Gets the camera attached to the layer.
  83028. */
  83029. get: function () {
  83030. return this._effectLayerOptions.camera;
  83031. },
  83032. enumerable: true,
  83033. configurable: true
  83034. });
  83035. /**
  83036. * Initializes the effect layer with the required options.
  83037. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83038. */
  83039. EffectLayer.prototype._init = function (options) {
  83040. // Adapt options
  83041. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83042. this._setMainTextureSize();
  83043. this._createMainTexture();
  83044. this._createTextureAndPostProcesses();
  83045. this._mergeEffect = this._createMergeEffect();
  83046. };
  83047. /**
  83048. * Generates the index buffer of the full screen quad blending to the main canvas.
  83049. */
  83050. EffectLayer.prototype._generateIndexBuffer = function () {
  83051. // Indices
  83052. var indices = [];
  83053. indices.push(0);
  83054. indices.push(1);
  83055. indices.push(2);
  83056. indices.push(0);
  83057. indices.push(2);
  83058. indices.push(3);
  83059. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83060. };
  83061. /**
  83062. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83063. */
  83064. EffectLayer.prototype._genrateVertexBuffer = function () {
  83065. // VBO
  83066. var vertices = [];
  83067. vertices.push(1, 1);
  83068. vertices.push(-1, 1);
  83069. vertices.push(-1, -1);
  83070. vertices.push(1, -1);
  83071. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83072. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83073. };
  83074. /**
  83075. * Sets the main texture desired size which is the closest power of two
  83076. * of the engine canvas size.
  83077. */
  83078. EffectLayer.prototype._setMainTextureSize = function () {
  83079. if (this._effectLayerOptions.mainTextureFixedSize) {
  83080. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83081. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83082. }
  83083. else {
  83084. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83085. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83086. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83087. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83088. }
  83089. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83090. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83091. };
  83092. /**
  83093. * Creates the main texture for the effect layer.
  83094. */
  83095. EffectLayer.prototype._createMainTexture = function () {
  83096. var _this = this;
  83097. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83098. width: this._mainTextureDesiredSize.width,
  83099. height: this._mainTextureDesiredSize.height
  83100. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83101. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83102. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83103. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83104. this._mainTexture.anisotropicFilteringLevel = 1;
  83105. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83106. this._mainTexture.renderParticles = false;
  83107. this._mainTexture.renderList = null;
  83108. this._mainTexture.ignoreCameraViewport = true;
  83109. // Custom render function
  83110. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83111. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83112. var index;
  83113. var engine = _this._scene.getEngine();
  83114. if (depthOnlySubMeshes.length) {
  83115. engine.setColorWrite(false);
  83116. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83117. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83118. }
  83119. engine.setColorWrite(true);
  83120. }
  83121. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83122. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83123. }
  83124. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83125. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83126. }
  83127. for (index = 0; index < transparentSubMeshes.length; index++) {
  83128. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83129. }
  83130. };
  83131. this._mainTexture.onClearObservable.add(function (engine) {
  83132. engine.clear(_this.neutralColor, true, true, true);
  83133. });
  83134. };
  83135. /**
  83136. * Checks for the readiness of the element composing the layer.
  83137. * @param subMesh the mesh to check for
  83138. * @param useInstances specify wether or not to use instances to render the mesh
  83139. * @param emissiveTexture the associated emissive texture used to generate the glow
  83140. * @return true if ready otherwise, false
  83141. */
  83142. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83143. var material = subMesh.getMaterial();
  83144. if (!material) {
  83145. return false;
  83146. }
  83147. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83148. return false;
  83149. }
  83150. var defines = [];
  83151. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83152. var mesh = subMesh.getMesh();
  83153. var uv1 = false;
  83154. var uv2 = false;
  83155. // Alpha test
  83156. if (material && material.needAlphaTesting()) {
  83157. var alphaTexture = material.getAlphaTestTexture();
  83158. if (alphaTexture) {
  83159. defines.push("#define ALPHATEST");
  83160. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83161. alphaTexture.coordinatesIndex === 1) {
  83162. defines.push("#define DIFFUSEUV2");
  83163. uv2 = true;
  83164. }
  83165. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83166. defines.push("#define DIFFUSEUV1");
  83167. uv1 = true;
  83168. }
  83169. }
  83170. }
  83171. // Emissive
  83172. if (emissiveTexture) {
  83173. defines.push("#define EMISSIVE");
  83174. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83175. emissiveTexture.coordinatesIndex === 1) {
  83176. defines.push("#define EMISSIVEUV2");
  83177. uv2 = true;
  83178. }
  83179. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83180. defines.push("#define EMISSIVEUV1");
  83181. uv1 = true;
  83182. }
  83183. }
  83184. if (uv1) {
  83185. attribs.push(BABYLON.VertexBuffer.UVKind);
  83186. defines.push("#define UV1");
  83187. }
  83188. if (uv2) {
  83189. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83190. defines.push("#define UV2");
  83191. }
  83192. // Bones
  83193. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83194. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83195. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83196. if (mesh.numBoneInfluencers > 4) {
  83197. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83198. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83199. }
  83200. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83201. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83202. }
  83203. else {
  83204. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83205. }
  83206. // Instances
  83207. if (useInstances) {
  83208. defines.push("#define INSTANCES");
  83209. attribs.push("world0");
  83210. attribs.push("world1");
  83211. attribs.push("world2");
  83212. attribs.push("world3");
  83213. }
  83214. // Get correct effect
  83215. var join = defines.join("\n");
  83216. if (this._cachedDefines !== join) {
  83217. this._cachedDefines = join;
  83218. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83219. }
  83220. return this._effectLayerMapGenerationEffect.isReady();
  83221. };
  83222. /**
  83223. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83224. */
  83225. EffectLayer.prototype.render = function () {
  83226. var currentEffect = this._mergeEffect;
  83227. // Check
  83228. if (!currentEffect.isReady())
  83229. return;
  83230. for (var i = 0; i < this._postProcesses.length; i++) {
  83231. if (!this._postProcesses[i].isReady()) {
  83232. return;
  83233. }
  83234. }
  83235. var engine = this._scene.getEngine();
  83236. this.onBeforeComposeObservable.notifyObservers(this);
  83237. // Render
  83238. engine.enableEffect(currentEffect);
  83239. engine.setState(false);
  83240. // VBOs
  83241. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83242. // Cache
  83243. var previousAlphaMode = engine.getAlphaMode();
  83244. // Go Blend.
  83245. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83246. // Blends the map on the main canvas.
  83247. this._internalRender(currentEffect);
  83248. // Restore Alpha
  83249. engine.setAlphaMode(previousAlphaMode);
  83250. this.onAfterComposeObservable.notifyObservers(this);
  83251. // Handle size changes.
  83252. var size = this._mainTexture.getSize();
  83253. this._setMainTextureSize();
  83254. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83255. // Recreate RTT and post processes on size change.
  83256. this.onSizeChangedObservable.notifyObservers(this);
  83257. this._disposeTextureAndPostProcesses();
  83258. this._createMainTexture();
  83259. this._createTextureAndPostProcesses();
  83260. }
  83261. };
  83262. /**
  83263. * Determine if a given mesh will be used in the current effect.
  83264. * @param mesh mesh to test
  83265. * @returns true if the mesh will be used
  83266. */
  83267. EffectLayer.prototype.hasMesh = function (mesh) {
  83268. return true;
  83269. };
  83270. /**
  83271. * Returns true if the layer contains information to display, otherwise false.
  83272. * @returns true if the glow layer should be rendered
  83273. */
  83274. EffectLayer.prototype.shouldRender = function () {
  83275. return this.isEnabled && this._shouldRender;
  83276. };
  83277. /**
  83278. * Returns true if the mesh should render, otherwise false.
  83279. * @param mesh The mesh to render
  83280. * @returns true if it should render otherwise false
  83281. */
  83282. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83283. return true;
  83284. };
  83285. /**
  83286. * Returns true if the mesh should render, otherwise false.
  83287. * @param mesh The mesh to render
  83288. * @returns true if it should render otherwise false
  83289. */
  83290. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83291. return true;
  83292. };
  83293. /**
  83294. * Renders the submesh passed in parameter to the generation map.
  83295. */
  83296. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83297. var _this = this;
  83298. if (!this.shouldRender()) {
  83299. return;
  83300. }
  83301. var material = subMesh.getMaterial();
  83302. var mesh = subMesh.getRenderingMesh();
  83303. var scene = this._scene;
  83304. var engine = scene.getEngine();
  83305. if (!material) {
  83306. return;
  83307. }
  83308. // Do not block in blend mode.
  83309. if (material.needAlphaBlendingForMesh(mesh)) {
  83310. return;
  83311. }
  83312. // Culling
  83313. engine.setState(material.backFaceCulling);
  83314. // Managing instances
  83315. var batch = mesh._getInstancesRenderList(subMesh._id);
  83316. if (batch.mustReturn) {
  83317. return;
  83318. }
  83319. // Early Exit per mesh
  83320. if (!this._shouldRenderMesh(mesh)) {
  83321. return;
  83322. }
  83323. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83324. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  83325. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  83326. engine.enableEffect(this._effectLayerMapGenerationEffect);
  83327. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  83328. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  83329. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  83330. // Alpha test
  83331. if (material && material.needAlphaTesting()) {
  83332. var alphaTexture = material.getAlphaTestTexture();
  83333. if (alphaTexture) {
  83334. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  83335. var textureMatrix = alphaTexture.getTextureMatrix();
  83336. if (textureMatrix) {
  83337. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  83338. }
  83339. }
  83340. }
  83341. // Glow emissive only
  83342. if (this._emissiveTextureAndColor.texture) {
  83343. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  83344. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  83345. }
  83346. // Bones
  83347. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83348. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83349. }
  83350. // Draw
  83351. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  83352. }
  83353. else {
  83354. // Need to reset refresh rate of the shadowMap
  83355. this._mainTexture.resetRefreshCounter();
  83356. }
  83357. };
  83358. /**
  83359. * Rebuild the required buffers.
  83360. * @ignore Internal use only.
  83361. */
  83362. EffectLayer.prototype._rebuild = function () {
  83363. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83364. if (vb) {
  83365. vb._rebuild();
  83366. }
  83367. this._generateIndexBuffer();
  83368. };
  83369. /**
  83370. * Dispose only the render target textures and post process.
  83371. */
  83372. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  83373. this._mainTexture.dispose();
  83374. for (var i = 0; i < this._postProcesses.length; i++) {
  83375. if (this._postProcesses[i]) {
  83376. this._postProcesses[i].dispose();
  83377. }
  83378. }
  83379. this._postProcesses = [];
  83380. for (var i = 0; i < this._textures.length; i++) {
  83381. if (this._textures[i]) {
  83382. this._textures[i].dispose();
  83383. }
  83384. }
  83385. this._textures = [];
  83386. };
  83387. /**
  83388. * Dispose the highlight layer and free resources.
  83389. */
  83390. EffectLayer.prototype.dispose = function () {
  83391. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83392. if (vertexBuffer) {
  83393. vertexBuffer.dispose();
  83394. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83395. }
  83396. if (this._indexBuffer) {
  83397. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83398. this._indexBuffer = null;
  83399. }
  83400. // Clean textures and post processes
  83401. this._disposeTextureAndPostProcesses();
  83402. // Remove from scene
  83403. var index = this._scene.effectLayers.indexOf(this, 0);
  83404. if (index > -1) {
  83405. this._scene.effectLayers.splice(index, 1);
  83406. }
  83407. // Callback
  83408. this.onDisposeObservable.notifyObservers(this);
  83409. this.onDisposeObservable.clear();
  83410. this.onBeforeRenderMainTextureObservable.clear();
  83411. this.onBeforeComposeObservable.clear();
  83412. this.onAfterComposeObservable.clear();
  83413. this.onSizeChangedObservable.clear();
  83414. };
  83415. return EffectLayer;
  83416. }());
  83417. BABYLON.EffectLayer = EffectLayer;
  83418. })(BABYLON || (BABYLON = {}));
  83419. //# sourceMappingURL=babylon.effectLayer.js.map
  83420. var BABYLON;
  83421. (function (BABYLON) {
  83422. /**
  83423. * Special Glow Blur post process only blurring the alpha channel
  83424. * It enforces keeping the most luminous color in the color channel.
  83425. */
  83426. var GlowBlurPostProcess = /** @class */ (function (_super) {
  83427. __extends(GlowBlurPostProcess, _super);
  83428. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  83429. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83430. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  83431. _this.direction = direction;
  83432. _this.kernel = kernel;
  83433. _this.onApplyObservable.add(function (effect) {
  83434. effect.setFloat2("screenSize", _this.width, _this.height);
  83435. effect.setVector2("direction", _this.direction);
  83436. effect.setFloat("blurWidth", _this.kernel);
  83437. });
  83438. return _this;
  83439. }
  83440. return GlowBlurPostProcess;
  83441. }(BABYLON.PostProcess));
  83442. /**
  83443. * The highlight layer Helps adding a glow effect around a mesh.
  83444. *
  83445. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83446. * glowy meshes to your scene.
  83447. *
  83448. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  83449. */
  83450. var HighlightLayer = /** @class */ (function (_super) {
  83451. __extends(HighlightLayer, _super);
  83452. /**
  83453. * Instantiates a new highlight Layer and references it to the scene..
  83454. * @param name The name of the layer
  83455. * @param scene The scene to use the layer in
  83456. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  83457. */
  83458. function HighlightLayer(name, scene, options) {
  83459. var _this = _super.call(this, name, scene) || this;
  83460. _this.name = name;
  83461. /**
  83462. * Specifies whether or not the inner glow is ACTIVE in the layer.
  83463. */
  83464. _this.innerGlow = true;
  83465. /**
  83466. * Specifies whether or not the outer glow is ACTIVE in the layer.
  83467. */
  83468. _this.outerGlow = true;
  83469. /**
  83470. * An event triggered when the highlight layer is being blurred.
  83471. */
  83472. _this.onBeforeBlurObservable = new BABYLON.Observable();
  83473. /**
  83474. * An event triggered when the highlight layer has been blurred.
  83475. */
  83476. _this.onAfterBlurObservable = new BABYLON.Observable();
  83477. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  83478. _this._meshes = {};
  83479. _this._excludedMeshes = {};
  83480. _this.neutralColor = HighlightLayer.NeutralColor;
  83481. // Warn on stencil
  83482. if (!_this._engine.isStencilEnable) {
  83483. 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 }");
  83484. }
  83485. // Adapt options
  83486. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83487. // Initialize the layer
  83488. _this._init({
  83489. alphaBlendingMode: _this._options.alphaBlendingMode,
  83490. camera: _this._options.camera,
  83491. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83492. mainTextureRatio: _this._options.mainTextureRatio
  83493. });
  83494. // Do not render as long as no meshes have been added
  83495. _this._shouldRender = false;
  83496. return _this;
  83497. }
  83498. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  83499. /**
  83500. * Gets the horizontal size of the blur.
  83501. */
  83502. get: function () {
  83503. return this._horizontalBlurPostprocess.kernel;
  83504. },
  83505. /**
  83506. * Specifies the horizontal size of the blur.
  83507. */
  83508. set: function (value) {
  83509. this._horizontalBlurPostprocess.kernel = value;
  83510. },
  83511. enumerable: true,
  83512. configurable: true
  83513. });
  83514. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  83515. /**
  83516. * Gets the vertical size of the blur.
  83517. */
  83518. get: function () {
  83519. return this._verticalBlurPostprocess.kernel;
  83520. },
  83521. /**
  83522. * Specifies the vertical size of the blur.
  83523. */
  83524. set: function (value) {
  83525. this._verticalBlurPostprocess.kernel = value;
  83526. },
  83527. enumerable: true,
  83528. configurable: true
  83529. });
  83530. /**
  83531. * Get the effect name of the layer.
  83532. * @return The effect name
  83533. */
  83534. HighlightLayer.prototype.getEffectName = function () {
  83535. return HighlightLayer.EffectName;
  83536. };
  83537. /**
  83538. * Create the merge effect. This is the shader use to blit the information back
  83539. * to the main canvas at the end of the scene rendering.
  83540. */
  83541. HighlightLayer.prototype._createMergeEffect = function () {
  83542. // Effect
  83543. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  83544. };
  83545. /**
  83546. * Creates the render target textures and post processes used in the highlight layer.
  83547. */
  83548. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  83549. var _this = this;
  83550. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  83551. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  83552. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83553. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83554. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  83555. width: blurTextureWidth,
  83556. height: blurTextureHeight
  83557. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83558. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83559. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83560. this._blurTexture.anisotropicFilteringLevel = 16;
  83561. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83562. this._blurTexture.renderParticles = false;
  83563. this._blurTexture.ignoreCameraViewport = true;
  83564. this._textures = [this._blurTexture];
  83565. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  83566. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83567. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  83568. effect.setTexture("textureSampler", _this._mainTexture);
  83569. });
  83570. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83571. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83572. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83573. });
  83574. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  83575. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  83576. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  83577. });
  83578. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83579. }
  83580. else {
  83581. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  83582. width: blurTextureWidth,
  83583. height: blurTextureHeight
  83584. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83585. this._horizontalBlurPostprocess.width = blurTextureWidth;
  83586. this._horizontalBlurPostprocess.height = blurTextureHeight;
  83587. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  83588. effect.setTexture("textureSampler", _this._mainTexture);
  83589. });
  83590. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  83591. width: blurTextureWidth,
  83592. height: blurTextureHeight
  83593. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  83594. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  83595. }
  83596. this._mainTexture.onAfterUnbindObservable.add(function () {
  83597. _this.onBeforeBlurObservable.notifyObservers(_this);
  83598. var internalTexture = _this._blurTexture.getInternalTexture();
  83599. if (internalTexture) {
  83600. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  83601. }
  83602. _this.onAfterBlurObservable.notifyObservers(_this);
  83603. });
  83604. // Prevent autoClear.
  83605. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  83606. };
  83607. /**
  83608. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  83609. */
  83610. HighlightLayer.prototype.needStencil = function () {
  83611. return true;
  83612. };
  83613. /**
  83614. * Checks for the readiness of the element composing the layer.
  83615. * @param subMesh the mesh to check for
  83616. * @param useInstances specify wether or not to use instances to render the mesh
  83617. * @param emissiveTexture the associated emissive texture used to generate the glow
  83618. * @return true if ready otherwise, false
  83619. */
  83620. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  83621. var material = subMesh.getMaterial();
  83622. var mesh = subMesh.getRenderingMesh();
  83623. if (!material || !mesh || !this._meshes) {
  83624. return false;
  83625. }
  83626. var emissiveTexture = null;
  83627. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83628. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83629. emissiveTexture = material.emissiveTexture;
  83630. }
  83631. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  83632. };
  83633. /**
  83634. * Implementation specific of rendering the generating effect on the main canvas.
  83635. * @param effect The effect used to render through
  83636. */
  83637. HighlightLayer.prototype._internalRender = function (effect) {
  83638. // Texture
  83639. effect.setTexture("textureSampler", this._blurTexture);
  83640. // Cache
  83641. var engine = this._engine;
  83642. var previousStencilBuffer = engine.getStencilBuffer();
  83643. var previousStencilFunction = engine.getStencilFunction();
  83644. var previousStencilMask = engine.getStencilMask();
  83645. var previousStencilOperationPass = engine.getStencilOperationPass();
  83646. var previousStencilOperationFail = engine.getStencilOperationFail();
  83647. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  83648. var previousStencilReference = engine.getStencilFunctionReference();
  83649. // Stencil operations
  83650. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  83651. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  83652. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  83653. // Draw order
  83654. engine.setStencilMask(0x00);
  83655. engine.setStencilBuffer(true);
  83656. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  83657. // 2 passes inner outer
  83658. if (this.outerGlow) {
  83659. effect.setFloat("offset", 0);
  83660. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  83661. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83662. }
  83663. if (this.innerGlow) {
  83664. effect.setFloat("offset", 1);
  83665. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  83666. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83667. }
  83668. // Restore Cache
  83669. engine.setStencilFunction(previousStencilFunction);
  83670. engine.setStencilMask(previousStencilMask);
  83671. engine.setStencilBuffer(previousStencilBuffer);
  83672. engine.setStencilOperationPass(previousStencilOperationPass);
  83673. engine.setStencilOperationFail(previousStencilOperationFail);
  83674. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  83675. engine.setStencilFunctionReference(previousStencilReference);
  83676. };
  83677. /**
  83678. * Returns true if the layer contains information to display, otherwise false.
  83679. */
  83680. HighlightLayer.prototype.shouldRender = function () {
  83681. if (_super.prototype.shouldRender.call(this)) {
  83682. return this._meshes ? true : false;
  83683. }
  83684. return false;
  83685. };
  83686. /**
  83687. * Returns true if the mesh should render, otherwise false.
  83688. * @param mesh The mesh to render
  83689. * @returns true if it should render otherwise false
  83690. */
  83691. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  83692. // Excluded Mesh
  83693. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  83694. return false;
  83695. }
  83696. ;
  83697. return true;
  83698. };
  83699. /**
  83700. * Sets the required values for both the emissive texture and and the main color.
  83701. */
  83702. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  83703. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  83704. if (highlightLayerMesh) {
  83705. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  83706. }
  83707. else {
  83708. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  83709. }
  83710. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  83711. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  83712. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  83713. }
  83714. else {
  83715. this._emissiveTextureAndColor.texture = null;
  83716. }
  83717. };
  83718. /**
  83719. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  83720. * @param mesh The mesh to exclude from the highlight layer
  83721. */
  83722. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  83723. if (!this._excludedMeshes) {
  83724. return;
  83725. }
  83726. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83727. if (!meshExcluded) {
  83728. this._excludedMeshes[mesh.uniqueId] = {
  83729. mesh: mesh,
  83730. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  83731. mesh.getEngine().setStencilBuffer(false);
  83732. }),
  83733. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  83734. mesh.getEngine().setStencilBuffer(true);
  83735. }),
  83736. };
  83737. }
  83738. };
  83739. /**
  83740. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  83741. * @param mesh The mesh to highlight
  83742. */
  83743. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  83744. if (!this._excludedMeshes) {
  83745. return;
  83746. }
  83747. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  83748. if (meshExcluded) {
  83749. if (meshExcluded.beforeRender) {
  83750. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  83751. }
  83752. if (meshExcluded.afterRender) {
  83753. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  83754. }
  83755. }
  83756. this._excludedMeshes[mesh.uniqueId] = null;
  83757. };
  83758. /**
  83759. * Determine if a given mesh will be highlighted by the current HighlightLayer
  83760. * @param mesh mesh to test
  83761. * @returns true if the mesh will be highlighted by the current HighlightLayer
  83762. */
  83763. HighlightLayer.prototype.hasMesh = function (mesh) {
  83764. if (!this._meshes) {
  83765. return false;
  83766. }
  83767. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  83768. };
  83769. /**
  83770. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  83771. * @param mesh The mesh to highlight
  83772. * @param color The color of the highlight
  83773. * @param glowEmissiveOnly Extract the glow from the emissive texture
  83774. */
  83775. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  83776. var _this = this;
  83777. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  83778. if (!this._meshes) {
  83779. return;
  83780. }
  83781. var meshHighlight = this._meshes[mesh.uniqueId];
  83782. if (meshHighlight) {
  83783. meshHighlight.color = color;
  83784. }
  83785. else {
  83786. this._meshes[mesh.uniqueId] = {
  83787. mesh: mesh,
  83788. color: color,
  83789. // Lambda required for capture due to Observable this context
  83790. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  83791. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  83792. _this._defaultStencilReference(mesh);
  83793. }
  83794. else {
  83795. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  83796. }
  83797. }),
  83798. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  83799. glowEmissiveOnly: glowEmissiveOnly
  83800. };
  83801. }
  83802. this._shouldRender = true;
  83803. };
  83804. /**
  83805. * Remove a mesh from the highlight layer in order to make it stop glowing.
  83806. * @param mesh The mesh to highlight
  83807. */
  83808. HighlightLayer.prototype.removeMesh = function (mesh) {
  83809. if (!this._meshes) {
  83810. return;
  83811. }
  83812. var meshHighlight = this._meshes[mesh.uniqueId];
  83813. if (meshHighlight) {
  83814. if (meshHighlight.observerHighlight) {
  83815. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83816. }
  83817. if (meshHighlight.observerDefault) {
  83818. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83819. }
  83820. delete this._meshes[mesh.uniqueId];
  83821. }
  83822. this._shouldRender = false;
  83823. for (var meshHighlightToCheck in this._meshes) {
  83824. if (this._meshes[meshHighlightToCheck]) {
  83825. this._shouldRender = true;
  83826. break;
  83827. }
  83828. }
  83829. };
  83830. /**
  83831. * Force the stencil to the normal expected value for none glowing parts
  83832. */
  83833. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  83834. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  83835. };
  83836. /**
  83837. * Free any resources and references associated to a mesh.
  83838. * Internal use
  83839. * @param mesh The mesh to free.
  83840. */
  83841. HighlightLayer.prototype._disposeMesh = function (mesh) {
  83842. this.removeMesh(mesh);
  83843. this.removeExcludedMesh(mesh);
  83844. };
  83845. /**
  83846. * Dispose the highlight layer and free resources.
  83847. */
  83848. HighlightLayer.prototype.dispose = function () {
  83849. if (this._meshes) {
  83850. // Clean mesh references
  83851. for (var id in this._meshes) {
  83852. var meshHighlight = this._meshes[id];
  83853. if (meshHighlight && meshHighlight.mesh) {
  83854. if (meshHighlight.observerHighlight) {
  83855. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  83856. }
  83857. if (meshHighlight.observerDefault) {
  83858. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  83859. }
  83860. }
  83861. }
  83862. this._meshes = null;
  83863. }
  83864. if (this._excludedMeshes) {
  83865. for (var id in this._excludedMeshes) {
  83866. var meshHighlight = this._excludedMeshes[id];
  83867. if (meshHighlight) {
  83868. if (meshHighlight.beforeRender) {
  83869. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  83870. }
  83871. if (meshHighlight.afterRender) {
  83872. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  83873. }
  83874. }
  83875. }
  83876. this._excludedMeshes = null;
  83877. }
  83878. _super.prototype.dispose.call(this);
  83879. };
  83880. /**
  83881. * Effect Name of the highlight layer.
  83882. */
  83883. HighlightLayer.EffectName = "HighlightLayer";
  83884. /**
  83885. * The neutral color used during the preparation of the glow effect.
  83886. * This is black by default as the blend operation is a blend operation.
  83887. */
  83888. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  83889. /**
  83890. * Stencil value used for glowing meshes.
  83891. */
  83892. HighlightLayer.GlowingMeshStencilReference = 0x02;
  83893. /**
  83894. * Stencil value used for the other meshes in the scene.
  83895. */
  83896. HighlightLayer.NormalMeshStencilReference = 0x01;
  83897. return HighlightLayer;
  83898. }(BABYLON.EffectLayer));
  83899. BABYLON.HighlightLayer = HighlightLayer;
  83900. })(BABYLON || (BABYLON = {}));
  83901. //# sourceMappingURL=babylon.highlightLayer.js.map
  83902. var BABYLON;
  83903. (function (BABYLON) {
  83904. /**
  83905. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  83906. *
  83907. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83908. * glowy meshes to your scene.
  83909. *
  83910. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  83911. */
  83912. var GlowLayer = /** @class */ (function (_super) {
  83913. __extends(GlowLayer, _super);
  83914. /**
  83915. * Instantiates a new glow Layer and references it to the scene.
  83916. * @param name The name of the layer
  83917. * @param scene The scene to use the layer in
  83918. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  83919. */
  83920. function GlowLayer(name, scene, options) {
  83921. var _this = _super.call(this, name, scene) || this;
  83922. _this.name = name;
  83923. _this._intensity = 1.0;
  83924. _this._includedOnlyMeshes = [];
  83925. _this._excludedMeshes = [];
  83926. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  83927. // Adapt options
  83928. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  83929. // Initialize the layer
  83930. _this._init({
  83931. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  83932. camera: _this._options.camera,
  83933. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  83934. mainTextureRatio: _this._options.mainTextureRatio
  83935. });
  83936. return _this;
  83937. }
  83938. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  83939. /**
  83940. * Gets the kernel size of the blur.
  83941. */
  83942. get: function () {
  83943. return this._horizontalBlurPostprocess1.kernel;
  83944. },
  83945. /**
  83946. * Sets the kernel size of the blur.
  83947. */
  83948. set: function (value) {
  83949. this._horizontalBlurPostprocess1.kernel = value;
  83950. this._verticalBlurPostprocess1.kernel = value;
  83951. this._horizontalBlurPostprocess2.kernel = value;
  83952. this._verticalBlurPostprocess2.kernel = value;
  83953. },
  83954. enumerable: true,
  83955. configurable: true
  83956. });
  83957. Object.defineProperty(GlowLayer.prototype, "intensity", {
  83958. /**
  83959. * Gets the glow intensity.
  83960. */
  83961. get: function () {
  83962. return this._intensity;
  83963. },
  83964. /**
  83965. * Sets the glow intensity.
  83966. */
  83967. set: function (value) {
  83968. this._intensity = value;
  83969. },
  83970. enumerable: true,
  83971. configurable: true
  83972. });
  83973. /**
  83974. * Get the effect name of the layer.
  83975. * @return The effect name
  83976. */
  83977. GlowLayer.prototype.getEffectName = function () {
  83978. return GlowLayer.EffectName;
  83979. };
  83980. /**
  83981. * Create the merge effect. This is the shader use to blit the information back
  83982. * to the main canvas at the end of the scene rendering.
  83983. */
  83984. GlowLayer.prototype._createMergeEffect = function () {
  83985. // Effect
  83986. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  83987. };
  83988. /**
  83989. * Creates the render target textures and post processes used in the glow layer.
  83990. */
  83991. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  83992. var _this = this;
  83993. var blurTextureWidth = this._mainTextureDesiredSize.width;
  83994. var blurTextureHeight = this._mainTextureDesiredSize.height;
  83995. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  83996. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  83997. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  83998. width: blurTextureWidth,
  83999. height: blurTextureHeight
  84000. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84001. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84002. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84003. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84004. this._blurTexture1.renderParticles = false;
  84005. this._blurTexture1.ignoreCameraViewport = true;
  84006. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84007. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84008. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84009. width: blurTextureWidth2,
  84010. height: blurTextureHeight2
  84011. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84012. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84013. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84014. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84015. this._blurTexture2.renderParticles = false;
  84016. this._blurTexture2.ignoreCameraViewport = true;
  84017. this._textures = [this._blurTexture1, this._blurTexture2];
  84018. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84019. width: blurTextureWidth,
  84020. height: blurTextureHeight
  84021. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84022. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84023. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84024. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84025. effect.setTexture("textureSampler", _this._mainTexture);
  84026. });
  84027. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84028. width: blurTextureWidth,
  84029. height: blurTextureHeight
  84030. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84031. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84032. width: blurTextureWidth2,
  84033. height: blurTextureHeight2
  84034. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84035. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84036. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84037. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84038. effect.setTexture("textureSampler", _this._blurTexture1);
  84039. });
  84040. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84041. width: blurTextureWidth2,
  84042. height: blurTextureHeight2
  84043. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84044. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84045. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84046. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84047. this._mainTexture.samples = this._options.mainTextureSamples;
  84048. this._mainTexture.onAfterUnbindObservable.add(function () {
  84049. var internalTexture = _this._blurTexture1.getInternalTexture();
  84050. if (internalTexture) {
  84051. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84052. internalTexture = _this._blurTexture2.getInternalTexture();
  84053. if (internalTexture) {
  84054. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84055. }
  84056. }
  84057. });
  84058. // Prevent autoClear.
  84059. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84060. };
  84061. /**
  84062. * Checks for the readiness of the element composing the layer.
  84063. * @param subMesh the mesh to check for
  84064. * @param useInstances specify wether or not to use instances to render the mesh
  84065. * @param emissiveTexture the associated emissive texture used to generate the glow
  84066. * @return true if ready otherwise, false
  84067. */
  84068. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84069. var material = subMesh.getMaterial();
  84070. var mesh = subMesh.getRenderingMesh();
  84071. if (!material || !mesh) {
  84072. return false;
  84073. }
  84074. var emissiveTexture = material.emissiveTexture;
  84075. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84076. };
  84077. /**
  84078. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84079. */
  84080. GlowLayer.prototype.needStencil = function () {
  84081. return false;
  84082. };
  84083. /**
  84084. * Implementation specific of rendering the generating effect on the main canvas.
  84085. * @param effect The effect used to render through
  84086. */
  84087. GlowLayer.prototype._internalRender = function (effect) {
  84088. // Texture
  84089. effect.setTexture("textureSampler", this._blurTexture1);
  84090. effect.setTexture("textureSampler2", this._blurTexture2);
  84091. effect.setFloat("offset", this._intensity);
  84092. // Cache
  84093. var engine = this._engine;
  84094. var previousStencilBuffer = engine.getStencilBuffer();
  84095. // Draw order
  84096. engine.setStencilBuffer(false);
  84097. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84098. // Draw order
  84099. engine.setStencilBuffer(previousStencilBuffer);
  84100. };
  84101. /**
  84102. * Sets the required values for both the emissive texture and and the main color.
  84103. */
  84104. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84105. var textureLevel = 1.0;
  84106. if (this.customEmissiveTextureSelector) {
  84107. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84108. }
  84109. else {
  84110. if (material) {
  84111. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84112. if (this._emissiveTextureAndColor.texture) {
  84113. textureLevel = this._emissiveTextureAndColor.texture.level;
  84114. }
  84115. }
  84116. else {
  84117. this._emissiveTextureAndColor.texture = null;
  84118. }
  84119. }
  84120. if (this.customEmissiveColorSelector) {
  84121. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84122. }
  84123. else {
  84124. if (material.emissiveColor) {
  84125. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84126. }
  84127. else {
  84128. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84129. }
  84130. }
  84131. };
  84132. /**
  84133. * Returns true if the mesh should render, otherwise false.
  84134. * @param mesh The mesh to render
  84135. * @returns true if it should render otherwise false
  84136. */
  84137. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84138. return this.hasMesh(mesh);
  84139. };
  84140. /**
  84141. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84142. * @param mesh The mesh to exclude from the glow layer
  84143. */
  84144. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84145. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84146. this._excludedMeshes.push(mesh.uniqueId);
  84147. }
  84148. };
  84149. /**
  84150. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84151. * @param mesh The mesh to remove
  84152. */
  84153. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84154. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84155. if (index !== -1) {
  84156. this._excludedMeshes.splice(index, 1);
  84157. }
  84158. };
  84159. /**
  84160. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84161. * @param mesh The mesh to include in the glow layer
  84162. */
  84163. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84164. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84165. this._includedOnlyMeshes.push(mesh.uniqueId);
  84166. }
  84167. };
  84168. /**
  84169. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84170. * @param mesh The mesh to remove
  84171. */
  84172. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84173. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84174. if (index !== -1) {
  84175. this._includedOnlyMeshes.splice(index, 1);
  84176. }
  84177. };
  84178. /**
  84179. * Determine if a given mesh will be used in the glow layer
  84180. * @param mesh The mesh to test
  84181. * @returns true if the mesh will be highlighted by the current glow layer
  84182. */
  84183. GlowLayer.prototype.hasMesh = function (mesh) {
  84184. // Included Mesh
  84185. if (this._includedOnlyMeshes.length) {
  84186. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84187. }
  84188. ;
  84189. // Excluded Mesh
  84190. if (this._excludedMeshes.length) {
  84191. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84192. }
  84193. ;
  84194. return true;
  84195. };
  84196. /**
  84197. * Free any resources and references associated to a mesh.
  84198. * Internal use
  84199. * @param mesh The mesh to free.
  84200. */
  84201. GlowLayer.prototype._disposeMesh = function (mesh) {
  84202. this.removeIncludedOnlyMesh(mesh);
  84203. this.removeExcludedMesh(mesh);
  84204. };
  84205. /**
  84206. * Effect Name of the layer.
  84207. */
  84208. GlowLayer.EffectName = "GlowLayer";
  84209. /**
  84210. * The default blur kernel size used for the glow.
  84211. */
  84212. GlowLayer.DefaultBlurKernelSize = 32;
  84213. /**
  84214. * The default texture size ratio used for the glow.
  84215. */
  84216. GlowLayer.DefaultTextureRatio = 0.5;
  84217. return GlowLayer;
  84218. }(BABYLON.EffectLayer));
  84219. BABYLON.GlowLayer = GlowLayer;
  84220. })(BABYLON || (BABYLON = {}));
  84221. //# sourceMappingURL=babylon.glowLayer.js.map
  84222. var BABYLON;
  84223. (function (BABYLON) {
  84224. /**
  84225. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84226. */
  84227. var AssetTaskState;
  84228. (function (AssetTaskState) {
  84229. /**
  84230. * Initialization
  84231. */
  84232. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84233. /**
  84234. * Running
  84235. */
  84236. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84237. /**
  84238. * Done
  84239. */
  84240. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84241. /**
  84242. * Error
  84243. */
  84244. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84245. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84246. /**
  84247. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84248. */
  84249. var AbstractAssetTask = /** @class */ (function () {
  84250. /**
  84251. * Creates a new {BABYLON.AssetsManager}
  84252. * @param name defines the name of the task
  84253. */
  84254. function AbstractAssetTask(
  84255. /**
  84256. * Task name
  84257. */ name) {
  84258. this.name = name;
  84259. this._isCompleted = false;
  84260. this._taskState = AssetTaskState.INIT;
  84261. }
  84262. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84263. /**
  84264. * Get if the task is completed
  84265. */
  84266. get: function () {
  84267. return this._isCompleted;
  84268. },
  84269. enumerable: true,
  84270. configurable: true
  84271. });
  84272. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84273. /**
  84274. * Gets the current state of the task
  84275. */
  84276. get: function () {
  84277. return this._taskState;
  84278. },
  84279. enumerable: true,
  84280. configurable: true
  84281. });
  84282. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84283. /**
  84284. * Gets the current error object (if task is in error)
  84285. */
  84286. get: function () {
  84287. return this._errorObject;
  84288. },
  84289. enumerable: true,
  84290. configurable: true
  84291. });
  84292. /**
  84293. * Internal only
  84294. * @ignore
  84295. */
  84296. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84297. if (this._errorObject) {
  84298. return;
  84299. }
  84300. this._errorObject = {
  84301. message: message,
  84302. exception: exception
  84303. };
  84304. };
  84305. /**
  84306. * Execute the current task
  84307. * @param scene defines the scene where you want your assets to be loaded
  84308. * @param onSuccess is a callback called when the task is successfully executed
  84309. * @param onError is a callback called if an error occurs
  84310. */
  84311. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84312. var _this = this;
  84313. this._taskState = AssetTaskState.RUNNING;
  84314. this.runTask(scene, function () {
  84315. _this.onDoneCallback(onSuccess, onError);
  84316. }, function (msg, exception) {
  84317. _this.onErrorCallback(onError, msg, exception);
  84318. });
  84319. };
  84320. /**
  84321. * Execute the current task
  84322. * @param scene defines the scene where you want your assets to be loaded
  84323. * @param onSuccess is a callback called when the task is successfully executed
  84324. * @param onError is a callback called if an error occurs
  84325. */
  84326. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84327. throw new Error("runTask is not implemented");
  84328. };
  84329. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  84330. this._taskState = AssetTaskState.ERROR;
  84331. this._errorObject = {
  84332. message: message,
  84333. exception: exception
  84334. };
  84335. if (this.onError) {
  84336. this.onError(this, message, exception);
  84337. }
  84338. onError();
  84339. };
  84340. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  84341. try {
  84342. this._taskState = AssetTaskState.DONE;
  84343. this._isCompleted = true;
  84344. if (this.onSuccess) {
  84345. this.onSuccess(this);
  84346. }
  84347. onSuccess();
  84348. }
  84349. catch (e) {
  84350. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  84351. }
  84352. };
  84353. return AbstractAssetTask;
  84354. }());
  84355. BABYLON.AbstractAssetTask = AbstractAssetTask;
  84356. /**
  84357. * Class used to share progress information about assets loading
  84358. */
  84359. var AssetsProgressEvent = /** @class */ (function () {
  84360. /**
  84361. * Creates a {BABYLON.AssetsProgressEvent}
  84362. * @param remainingCount defines the number of remaining tasks to process
  84363. * @param totalCount defines the total number of tasks
  84364. * @param task defines the task that was just processed
  84365. */
  84366. function AssetsProgressEvent(remainingCount, totalCount, task) {
  84367. this.remainingCount = remainingCount;
  84368. this.totalCount = totalCount;
  84369. this.task = task;
  84370. }
  84371. return AssetsProgressEvent;
  84372. }());
  84373. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  84374. /**
  84375. * Define a task used by {BABYLON.AssetsManager} to load meshes
  84376. */
  84377. var MeshAssetTask = /** @class */ (function (_super) {
  84378. __extends(MeshAssetTask, _super);
  84379. /**
  84380. * Creates a new {BABYLON.MeshAssetTask}
  84381. * @param name defines the name of the task
  84382. * @param meshesNames defines the list of mesh's names you want to load
  84383. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  84384. * @param sceneFilename defines the filename of the scene to load from
  84385. */
  84386. function MeshAssetTask(
  84387. /**
  84388. * Defines the name of the task
  84389. */
  84390. name,
  84391. /**
  84392. * Defines the list of mesh's names you want to load
  84393. */
  84394. meshesNames,
  84395. /**
  84396. * Defines the root url to use as a base to load your meshes and associated resources
  84397. */
  84398. rootUrl,
  84399. /**
  84400. * Defines the filename of the scene to load from
  84401. */
  84402. sceneFilename) {
  84403. var _this = _super.call(this, name) || this;
  84404. _this.name = name;
  84405. _this.meshesNames = meshesNames;
  84406. _this.rootUrl = rootUrl;
  84407. _this.sceneFilename = sceneFilename;
  84408. return _this;
  84409. }
  84410. /**
  84411. * Execute the current task
  84412. * @param scene defines the scene where you want your assets to be loaded
  84413. * @param onSuccess is a callback called when the task is successfully executed
  84414. * @param onError is a callback called if an error occurs
  84415. */
  84416. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84417. var _this = this;
  84418. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  84419. _this.loadedMeshes = meshes;
  84420. _this.loadedParticleSystems = particleSystems;
  84421. _this.loadedSkeletons = skeletons;
  84422. onSuccess();
  84423. }, null, function (scene, message, exception) {
  84424. onError(message, exception);
  84425. });
  84426. };
  84427. return MeshAssetTask;
  84428. }(AbstractAssetTask));
  84429. BABYLON.MeshAssetTask = MeshAssetTask;
  84430. /**
  84431. * Define a task used by {BABYLON.AssetsManager} to load text content
  84432. */
  84433. var TextFileAssetTask = /** @class */ (function (_super) {
  84434. __extends(TextFileAssetTask, _super);
  84435. /**
  84436. * Creates a new TextFileAssetTask object
  84437. * @param name defines the name of the task
  84438. * @param url defines the location of the file to load
  84439. */
  84440. function TextFileAssetTask(
  84441. /**
  84442. * Defines the name of the task
  84443. */
  84444. name,
  84445. /**
  84446. * Defines the location of the file to load
  84447. */
  84448. url) {
  84449. var _this = _super.call(this, name) || this;
  84450. _this.name = name;
  84451. _this.url = url;
  84452. return _this;
  84453. }
  84454. /**
  84455. * Execute the current task
  84456. * @param scene defines the scene where you want your assets to be loaded
  84457. * @param onSuccess is a callback called when the task is successfully executed
  84458. * @param onError is a callback called if an error occurs
  84459. */
  84460. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84461. var _this = this;
  84462. scene._loadFile(this.url, function (data) {
  84463. _this.text = data;
  84464. onSuccess();
  84465. }, undefined, false, false, function (request, exception) {
  84466. if (request) {
  84467. onError(request.status + " " + request.statusText, exception);
  84468. }
  84469. });
  84470. };
  84471. return TextFileAssetTask;
  84472. }(AbstractAssetTask));
  84473. BABYLON.TextFileAssetTask = TextFileAssetTask;
  84474. /**
  84475. * Define a task used by {BABYLON.AssetsManager} to load binary data
  84476. */
  84477. var BinaryFileAssetTask = /** @class */ (function (_super) {
  84478. __extends(BinaryFileAssetTask, _super);
  84479. /**
  84480. * Creates a new BinaryFileAssetTask object
  84481. * @param name defines the name of the new task
  84482. * @param url defines the location of the file to load
  84483. */
  84484. function BinaryFileAssetTask(
  84485. /**
  84486. * Defines the name of the task
  84487. */
  84488. name,
  84489. /**
  84490. * Defines the location of the file to load
  84491. */
  84492. url) {
  84493. var _this = _super.call(this, name) || this;
  84494. _this.name = name;
  84495. _this.url = url;
  84496. return _this;
  84497. }
  84498. /**
  84499. * Execute the current task
  84500. * @param scene defines the scene where you want your assets to be loaded
  84501. * @param onSuccess is a callback called when the task is successfully executed
  84502. * @param onError is a callback called if an error occurs
  84503. */
  84504. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84505. var _this = this;
  84506. scene._loadFile(this.url, function (data) {
  84507. _this.data = data;
  84508. onSuccess();
  84509. }, undefined, true, true, function (request, exception) {
  84510. if (request) {
  84511. onError(request.status + " " + request.statusText, exception);
  84512. }
  84513. });
  84514. };
  84515. return BinaryFileAssetTask;
  84516. }(AbstractAssetTask));
  84517. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  84518. /**
  84519. * Define a task used by {BABYLON.AssetsManager} to load images
  84520. */
  84521. var ImageAssetTask = /** @class */ (function (_super) {
  84522. __extends(ImageAssetTask, _super);
  84523. /**
  84524. * Creates a new ImageAssetTask
  84525. * @param name defines the name of the task
  84526. * @param url defines the location of the image to load
  84527. */
  84528. function ImageAssetTask(
  84529. /**
  84530. * Defines the name of the task
  84531. */
  84532. name,
  84533. /**
  84534. * Defines the location of the image to load
  84535. */
  84536. url) {
  84537. var _this = _super.call(this, name) || this;
  84538. _this.name = name;
  84539. _this.url = url;
  84540. return _this;
  84541. }
  84542. /**
  84543. * Execute the current task
  84544. * @param scene defines the scene where you want your assets to be loaded
  84545. * @param onSuccess is a callback called when the task is successfully executed
  84546. * @param onError is a callback called if an error occurs
  84547. */
  84548. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84549. var _this = this;
  84550. var img = new Image();
  84551. BABYLON.Tools.SetCorsBehavior(this.url, img);
  84552. img.onload = function () {
  84553. _this.image = img;
  84554. onSuccess();
  84555. };
  84556. img.onerror = function (err) {
  84557. onError("Error loading image", err);
  84558. };
  84559. img.src = this.url;
  84560. };
  84561. return ImageAssetTask;
  84562. }(AbstractAssetTask));
  84563. BABYLON.ImageAssetTask = ImageAssetTask;
  84564. /**
  84565. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  84566. */
  84567. var TextureAssetTask = /** @class */ (function (_super) {
  84568. __extends(TextureAssetTask, _super);
  84569. /**
  84570. * Creates a new TextureAssetTask object
  84571. * @param name defines the name of the task
  84572. * @param url defines the location of the file to load
  84573. * @param noMipmap defines if mipmap should not be generated (default is false)
  84574. * @param invertY defines if texture must be inverted on Y axis (default is false)
  84575. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84576. */
  84577. function TextureAssetTask(
  84578. /**
  84579. * Defines the name of the task
  84580. */
  84581. name,
  84582. /**
  84583. * Defines the location of the file to load
  84584. */
  84585. url,
  84586. /**
  84587. * Defines if mipmap should not be generated (default is false)
  84588. */
  84589. noMipmap,
  84590. /**
  84591. * Defines if texture must be inverted on Y axis (default is false)
  84592. */
  84593. invertY,
  84594. /**
  84595. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  84596. */
  84597. samplingMode) {
  84598. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84599. var _this = _super.call(this, name) || this;
  84600. _this.name = name;
  84601. _this.url = url;
  84602. _this.noMipmap = noMipmap;
  84603. _this.invertY = invertY;
  84604. _this.samplingMode = samplingMode;
  84605. return _this;
  84606. }
  84607. /**
  84608. * Execute the current task
  84609. * @param scene defines the scene where you want your assets to be loaded
  84610. * @param onSuccess is a callback called when the task is successfully executed
  84611. * @param onError is a callback called if an error occurs
  84612. */
  84613. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84614. var onload = function () {
  84615. onSuccess();
  84616. };
  84617. var onerror = function (message, exception) {
  84618. onError(message, exception);
  84619. };
  84620. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  84621. };
  84622. return TextureAssetTask;
  84623. }(AbstractAssetTask));
  84624. BABYLON.TextureAssetTask = TextureAssetTask;
  84625. /**
  84626. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  84627. */
  84628. var CubeTextureAssetTask = /** @class */ (function (_super) {
  84629. __extends(CubeTextureAssetTask, _super);
  84630. /**
  84631. * Creates a new CubeTextureAssetTask
  84632. * @param name defines the name of the task
  84633. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84634. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84635. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84636. * @param files defines the explicit list of files (undefined by default)
  84637. */
  84638. function CubeTextureAssetTask(
  84639. /**
  84640. * Defines the name of the task
  84641. */
  84642. name,
  84643. /**
  84644. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  84645. */
  84646. url,
  84647. /**
  84648. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  84649. */
  84650. extensions,
  84651. /**
  84652. * Defines if mipmaps should not be generated (default is false)
  84653. */
  84654. noMipmap,
  84655. /**
  84656. * Defines the explicit list of files (undefined by default)
  84657. */
  84658. files) {
  84659. var _this = _super.call(this, name) || this;
  84660. _this.name = name;
  84661. _this.url = url;
  84662. _this.extensions = extensions;
  84663. _this.noMipmap = noMipmap;
  84664. _this.files = files;
  84665. return _this;
  84666. }
  84667. /**
  84668. * Execute the current task
  84669. * @param scene defines the scene where you want your assets to be loaded
  84670. * @param onSuccess is a callback called when the task is successfully executed
  84671. * @param onError is a callback called if an error occurs
  84672. */
  84673. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84674. var onload = function () {
  84675. onSuccess();
  84676. };
  84677. var onerror = function (message, exception) {
  84678. onError(message, exception);
  84679. };
  84680. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  84681. };
  84682. return CubeTextureAssetTask;
  84683. }(AbstractAssetTask));
  84684. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  84685. /**
  84686. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  84687. */
  84688. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  84689. __extends(HDRCubeTextureAssetTask, _super);
  84690. /**
  84691. * Creates a new HDRCubeTextureAssetTask object
  84692. * @param name defines the name of the task
  84693. * @param url defines the location of the file to load
  84694. * @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.
  84695. * @param noMipmap defines if mipmaps should not be generated (default is false)
  84696. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84697. * @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)
  84698. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84699. */
  84700. function HDRCubeTextureAssetTask(
  84701. /**
  84702. * Defines the name of the task
  84703. */
  84704. name,
  84705. /**
  84706. * Defines the location of the file to load
  84707. */
  84708. url,
  84709. /**
  84710. * 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.
  84711. */
  84712. size,
  84713. /**
  84714. * Defines if mipmaps should not be generated (default is false)
  84715. */
  84716. noMipmap,
  84717. /**
  84718. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  84719. */
  84720. generateHarmonics,
  84721. /**
  84722. * 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)
  84723. */
  84724. useInGammaSpace,
  84725. /**
  84726. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  84727. */
  84728. usePMREMGenerator) {
  84729. if (noMipmap === void 0) { noMipmap = false; }
  84730. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84731. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84732. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84733. var _this = _super.call(this, name) || this;
  84734. _this.name = name;
  84735. _this.url = url;
  84736. _this.size = size;
  84737. _this.noMipmap = noMipmap;
  84738. _this.generateHarmonics = generateHarmonics;
  84739. _this.useInGammaSpace = useInGammaSpace;
  84740. _this.usePMREMGenerator = usePMREMGenerator;
  84741. return _this;
  84742. }
  84743. /**
  84744. * Execute the current task
  84745. * @param scene defines the scene where you want your assets to be loaded
  84746. * @param onSuccess is a callback called when the task is successfully executed
  84747. * @param onError is a callback called if an error occurs
  84748. */
  84749. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84750. var onload = function () {
  84751. onSuccess();
  84752. };
  84753. var onerror = function (message, exception) {
  84754. onError(message, exception);
  84755. };
  84756. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  84757. };
  84758. return HDRCubeTextureAssetTask;
  84759. }(AbstractAssetTask));
  84760. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  84761. /**
  84762. * This class can be used to easily import assets into a scene
  84763. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  84764. */
  84765. var AssetsManager = /** @class */ (function () {
  84766. /**
  84767. * Creates a new AssetsManager
  84768. * @param scene defines the scene to work on
  84769. */
  84770. function AssetsManager(scene) {
  84771. this._isLoading = false;
  84772. this._tasks = new Array();
  84773. this._waitingTasksCount = 0;
  84774. this._totalTasksCount = 0;
  84775. /**
  84776. * Observable called when all tasks are processed
  84777. */
  84778. this.onTaskSuccessObservable = new BABYLON.Observable();
  84779. /**
  84780. * Observable called when a task had an error
  84781. */
  84782. this.onTaskErrorObservable = new BABYLON.Observable();
  84783. /**
  84784. * Observable called when a task is successful
  84785. */
  84786. this.onTasksDoneObservable = new BABYLON.Observable();
  84787. /**
  84788. * Observable called when a task is done (whatever the result is)
  84789. */
  84790. this.onProgressObservable = new BABYLON.Observable();
  84791. /**
  84792. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  84793. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  84794. */
  84795. this.useDefaultLoadingScreen = true;
  84796. this._scene = scene;
  84797. }
  84798. /**
  84799. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  84800. * @param taskName defines the name of the new task
  84801. * @param meshesNames defines the name of meshes to load
  84802. * @param rootUrl defines the root url to use to locate files
  84803. * @param sceneFilename defines the filename of the scene file
  84804. * @returns a new {BABYLON.MeshAssetTask} object
  84805. */
  84806. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  84807. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  84808. this._tasks.push(task);
  84809. return task;
  84810. };
  84811. /**
  84812. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  84813. * @param taskName defines the name of the new task
  84814. * @param url defines the url of the file to load
  84815. * @returns a new {BABYLON.TextFileAssetTask} object
  84816. */
  84817. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  84818. var task = new TextFileAssetTask(taskName, url);
  84819. this._tasks.push(task);
  84820. return task;
  84821. };
  84822. /**
  84823. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  84824. * @param taskName defines the name of the new task
  84825. * @param url defines the url of the file to load
  84826. * @returns a new {BABYLON.BinaryFileAssetTask} object
  84827. */
  84828. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  84829. var task = new BinaryFileAssetTask(taskName, url);
  84830. this._tasks.push(task);
  84831. return task;
  84832. };
  84833. /**
  84834. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  84835. * @param taskName defines the name of the new task
  84836. * @param url defines the url of the file to load
  84837. * @returns a new {BABYLON.ImageAssetTask} object
  84838. */
  84839. AssetsManager.prototype.addImageTask = function (taskName, url) {
  84840. var task = new ImageAssetTask(taskName, url);
  84841. this._tasks.push(task);
  84842. return task;
  84843. };
  84844. /**
  84845. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  84846. * @param taskName defines the name of the new task
  84847. * @param url defines the url of the file to load
  84848. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84849. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  84850. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  84851. * @returns a new {BABYLON.TextureAssetTask} object
  84852. */
  84853. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  84854. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  84855. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  84856. this._tasks.push(task);
  84857. return task;
  84858. };
  84859. /**
  84860. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  84861. * @param taskName defines the name of the new task
  84862. * @param url defines the url of the file to load
  84863. * @param extensions defines the extension to use to load the cube map (can be null)
  84864. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84865. * @param files defines the list of files to load (can be null)
  84866. * @returns a new {BABYLON.CubeTextureAssetTask} object
  84867. */
  84868. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  84869. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  84870. this._tasks.push(task);
  84871. return task;
  84872. };
  84873. /**
  84874. *
  84875. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  84876. * @param taskName defines the name of the new task
  84877. * @param url defines the url of the file to load
  84878. * @param size defines the size you want for the cubemap (can be null)
  84879. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  84880. * @param generateHarmonics defines if you want to automatically generate (true by default)
  84881. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  84882. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  84883. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  84884. */
  84885. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  84886. if (noMipmap === void 0) { noMipmap = false; }
  84887. if (generateHarmonics === void 0) { generateHarmonics = true; }
  84888. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  84889. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  84890. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  84891. this._tasks.push(task);
  84892. return task;
  84893. };
  84894. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  84895. var _this = this;
  84896. this._waitingTasksCount--;
  84897. try {
  84898. if (task.taskState === AssetTaskState.DONE) {
  84899. // Let's remove successfull tasks
  84900. BABYLON.Tools.SetImmediate(function () {
  84901. var index = _this._tasks.indexOf(task);
  84902. if (index > -1) {
  84903. _this._tasks.splice(index, 1);
  84904. }
  84905. });
  84906. }
  84907. if (this.onProgress) {
  84908. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  84909. }
  84910. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  84911. }
  84912. catch (e) {
  84913. BABYLON.Tools.Error("Error running progress callbacks.");
  84914. console.log(e);
  84915. }
  84916. if (this._waitingTasksCount === 0) {
  84917. try {
  84918. if (this.onFinish) {
  84919. this.onFinish(this._tasks);
  84920. }
  84921. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84922. }
  84923. catch (e) {
  84924. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  84925. console.log(e);
  84926. }
  84927. this._isLoading = false;
  84928. this._scene.getEngine().hideLoadingUI();
  84929. }
  84930. };
  84931. AssetsManager.prototype._runTask = function (task) {
  84932. var _this = this;
  84933. var done = function () {
  84934. try {
  84935. if (_this.onTaskSuccess) {
  84936. _this.onTaskSuccess(task);
  84937. }
  84938. _this.onTaskSuccessObservable.notifyObservers(task);
  84939. _this._decreaseWaitingTasksCount(task);
  84940. }
  84941. catch (e) {
  84942. error("Error executing task success callbacks", e);
  84943. }
  84944. };
  84945. var error = function (message, exception) {
  84946. task._setErrorObject(message, exception);
  84947. if (_this.onTaskError) {
  84948. _this.onTaskError(task);
  84949. }
  84950. _this.onTaskErrorObservable.notifyObservers(task);
  84951. _this._decreaseWaitingTasksCount(task);
  84952. };
  84953. task.run(this._scene, done, error);
  84954. };
  84955. /**
  84956. * Reset the {BABYLON.AssetsManager} and remove all tasks
  84957. * @return the current instance of the {BABYLON.AssetsManager}
  84958. */
  84959. AssetsManager.prototype.reset = function () {
  84960. this._isLoading = false;
  84961. this._tasks = new Array();
  84962. return this;
  84963. };
  84964. /**
  84965. * Start the loading process
  84966. * @return the current instance of the {BABYLON.AssetsManager}
  84967. */
  84968. AssetsManager.prototype.load = function () {
  84969. if (this._isLoading) {
  84970. return this;
  84971. }
  84972. this._isLoading = true;
  84973. this._waitingTasksCount = this._tasks.length;
  84974. this._totalTasksCount = this._tasks.length;
  84975. if (this._waitingTasksCount === 0) {
  84976. this._isLoading = false;
  84977. if (this.onFinish) {
  84978. this.onFinish(this._tasks);
  84979. }
  84980. this.onTasksDoneObservable.notifyObservers(this._tasks);
  84981. return this;
  84982. }
  84983. if (this.useDefaultLoadingScreen) {
  84984. this._scene.getEngine().displayLoadingUI();
  84985. }
  84986. for (var index = 0; index < this._tasks.length; index++) {
  84987. var task = this._tasks[index];
  84988. this._runTask(task);
  84989. }
  84990. return this;
  84991. };
  84992. return AssetsManager;
  84993. }());
  84994. BABYLON.AssetsManager = AssetsManager;
  84995. })(BABYLON || (BABYLON = {}));
  84996. //# sourceMappingURL=babylon.assetsManager.js.map
  84997. var BABYLON;
  84998. (function (BABYLON) {
  84999. var serializedGeometries = [];
  85000. var serializeGeometry = function (geometry, serializationGeometries) {
  85001. if (serializedGeometries[geometry.id]) {
  85002. return;
  85003. }
  85004. if (geometry.doNotSerialize) {
  85005. return;
  85006. }
  85007. if (geometry instanceof BABYLON.BoxGeometry) {
  85008. serializationGeometries.boxes.push(geometry.serialize());
  85009. }
  85010. else if (geometry instanceof BABYLON.SphereGeometry) {
  85011. serializationGeometries.spheres.push(geometry.serialize());
  85012. }
  85013. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85014. serializationGeometries.cylinders.push(geometry.serialize());
  85015. }
  85016. else if (geometry instanceof BABYLON.TorusGeometry) {
  85017. serializationGeometries.toruses.push(geometry.serialize());
  85018. }
  85019. else if (geometry instanceof BABYLON.GroundGeometry) {
  85020. serializationGeometries.grounds.push(geometry.serialize());
  85021. }
  85022. else if (geometry instanceof BABYLON.Plane) {
  85023. serializationGeometries.planes.push(geometry.serialize());
  85024. }
  85025. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85026. serializationGeometries.torusKnots.push(geometry.serialize());
  85027. }
  85028. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85029. throw new Error("Unknown primitive type");
  85030. }
  85031. else {
  85032. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85033. }
  85034. serializedGeometries[geometry.id] = true;
  85035. };
  85036. var serializeMesh = function (mesh, serializationScene) {
  85037. var serializationObject = {};
  85038. // Geometry
  85039. var geometry = mesh._geometry;
  85040. if (geometry) {
  85041. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85042. // 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
  85043. serializeGeometry(geometry, serializationScene.geometries);
  85044. }
  85045. }
  85046. // Custom
  85047. if (mesh.serialize) {
  85048. mesh.serialize(serializationObject);
  85049. }
  85050. return serializationObject;
  85051. };
  85052. var finalizeSingleMesh = function (mesh, serializationObject) {
  85053. //only works if the mesh is already loaded
  85054. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85055. //serialize material
  85056. if (mesh.material) {
  85057. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85058. serializationObject.materials = serializationObject.materials || [];
  85059. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85060. serializationObject.materials.push(mesh.material.serialize());
  85061. }
  85062. }
  85063. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85064. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85065. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85066. serializationObject.multiMaterials.push(mesh.material.serialize());
  85067. }
  85068. }
  85069. }
  85070. //serialize geometry
  85071. var geometry = mesh._geometry;
  85072. if (geometry) {
  85073. if (!serializationObject.geometries) {
  85074. serializationObject.geometries = {};
  85075. serializationObject.geometries.boxes = [];
  85076. serializationObject.geometries.spheres = [];
  85077. serializationObject.geometries.cylinders = [];
  85078. serializationObject.geometries.toruses = [];
  85079. serializationObject.geometries.grounds = [];
  85080. serializationObject.geometries.planes = [];
  85081. serializationObject.geometries.torusKnots = [];
  85082. serializationObject.geometries.vertexData = [];
  85083. }
  85084. serializeGeometry(geometry, serializationObject.geometries);
  85085. }
  85086. // Skeletons
  85087. if (mesh.skeleton) {
  85088. serializationObject.skeletons = serializationObject.skeletons || [];
  85089. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85090. }
  85091. //serialize the actual mesh
  85092. serializationObject.meshes = serializationObject.meshes || [];
  85093. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85094. }
  85095. };
  85096. var SceneSerializer = /** @class */ (function () {
  85097. function SceneSerializer() {
  85098. }
  85099. SceneSerializer.ClearCache = function () {
  85100. serializedGeometries = [];
  85101. };
  85102. SceneSerializer.Serialize = function (scene) {
  85103. var serializationObject = {};
  85104. SceneSerializer.ClearCache();
  85105. // Scene
  85106. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85107. serializationObject.autoClear = scene.autoClear;
  85108. serializationObject.clearColor = scene.clearColor.asArray();
  85109. serializationObject.ambientColor = scene.ambientColor.asArray();
  85110. serializationObject.gravity = scene.gravity.asArray();
  85111. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85112. serializationObject.workerCollisions = scene.workerCollisions;
  85113. // Fog
  85114. if (scene.fogMode && scene.fogMode !== 0) {
  85115. serializationObject.fogMode = scene.fogMode;
  85116. serializationObject.fogColor = scene.fogColor.asArray();
  85117. serializationObject.fogStart = scene.fogStart;
  85118. serializationObject.fogEnd = scene.fogEnd;
  85119. serializationObject.fogDensity = scene.fogDensity;
  85120. }
  85121. //Physics
  85122. if (scene.isPhysicsEnabled()) {
  85123. var physicEngine = scene.getPhysicsEngine();
  85124. if (physicEngine) {
  85125. serializationObject.physicsEnabled = true;
  85126. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85127. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85128. }
  85129. }
  85130. // Metadata
  85131. if (scene.metadata) {
  85132. serializationObject.metadata = scene.metadata;
  85133. }
  85134. // Morph targets
  85135. serializationObject.morphTargetManagers = [];
  85136. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85137. var abstractMesh = _a[_i];
  85138. var manager = abstractMesh.morphTargetManager;
  85139. if (manager) {
  85140. serializationObject.morphTargetManagers.push(manager.serialize());
  85141. }
  85142. }
  85143. // Lights
  85144. serializationObject.lights = [];
  85145. var index;
  85146. var light;
  85147. for (index = 0; index < scene.lights.length; index++) {
  85148. light = scene.lights[index];
  85149. if (!light.doNotSerialize) {
  85150. serializationObject.lights.push(light.serialize());
  85151. }
  85152. }
  85153. // Cameras
  85154. serializationObject.cameras = [];
  85155. for (index = 0; index < scene.cameras.length; index++) {
  85156. var camera = scene.cameras[index];
  85157. if (!camera.doNotSerialize) {
  85158. serializationObject.cameras.push(camera.serialize());
  85159. }
  85160. }
  85161. if (scene.activeCamera) {
  85162. serializationObject.activeCameraID = scene.activeCamera.id;
  85163. }
  85164. // Animations
  85165. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85166. // Materials
  85167. serializationObject.materials = [];
  85168. serializationObject.multiMaterials = [];
  85169. var material;
  85170. for (index = 0; index < scene.materials.length; index++) {
  85171. material = scene.materials[index];
  85172. if (!material.doNotSerialize) {
  85173. serializationObject.materials.push(material.serialize());
  85174. }
  85175. }
  85176. // MultiMaterials
  85177. serializationObject.multiMaterials = [];
  85178. for (index = 0; index < scene.multiMaterials.length; index++) {
  85179. var multiMaterial = scene.multiMaterials[index];
  85180. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85181. }
  85182. // Environment texture
  85183. if (scene.environmentTexture) {
  85184. serializationObject.environmentTexture = scene.environmentTexture.name;
  85185. }
  85186. // Skeletons
  85187. serializationObject.skeletons = [];
  85188. for (index = 0; index < scene.skeletons.length; index++) {
  85189. var skeleton = scene.skeletons[index];
  85190. if (!skeleton.doNotSerialize) {
  85191. serializationObject.skeletons.push(skeleton.serialize());
  85192. }
  85193. }
  85194. // Transform nodes
  85195. serializationObject.transformNodes = [];
  85196. for (index = 0; index < scene.transformNodes.length; index++) {
  85197. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85198. }
  85199. // Geometries
  85200. serializationObject.geometries = {};
  85201. serializationObject.geometries.boxes = [];
  85202. serializationObject.geometries.spheres = [];
  85203. serializationObject.geometries.cylinders = [];
  85204. serializationObject.geometries.toruses = [];
  85205. serializationObject.geometries.grounds = [];
  85206. serializationObject.geometries.planes = [];
  85207. serializationObject.geometries.torusKnots = [];
  85208. serializationObject.geometries.vertexData = [];
  85209. serializedGeometries = [];
  85210. var geometries = scene.getGeometries();
  85211. for (index = 0; index < geometries.length; index++) {
  85212. var geometry = geometries[index];
  85213. if (geometry.isReady()) {
  85214. serializeGeometry(geometry, serializationObject.geometries);
  85215. }
  85216. }
  85217. // Meshes
  85218. serializationObject.meshes = [];
  85219. for (index = 0; index < scene.meshes.length; index++) {
  85220. var abstractMesh = scene.meshes[index];
  85221. if (abstractMesh instanceof BABYLON.Mesh) {
  85222. var mesh = abstractMesh;
  85223. if (!mesh.doNotSerialize) {
  85224. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85225. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85226. }
  85227. }
  85228. }
  85229. }
  85230. // Particles Systems
  85231. serializationObject.particleSystems = [];
  85232. for (index = 0; index < scene.particleSystems.length; index++) {
  85233. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85234. }
  85235. // Lens flares
  85236. serializationObject.lensFlareSystems = [];
  85237. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85238. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85239. }
  85240. // Shadows
  85241. serializationObject.shadowGenerators = [];
  85242. for (index = 0; index < scene.lights.length; index++) {
  85243. light = scene.lights[index];
  85244. var shadowGenerator = light.getShadowGenerator();
  85245. if (shadowGenerator) {
  85246. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85247. }
  85248. }
  85249. // Action Manager
  85250. if (scene.actionManager) {
  85251. serializationObject.actions = scene.actionManager.serialize("scene");
  85252. }
  85253. // Audio
  85254. serializationObject.sounds = [];
  85255. for (index = 0; index < scene.soundTracks.length; index++) {
  85256. var soundtrack = scene.soundTracks[index];
  85257. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85258. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85259. }
  85260. }
  85261. return serializationObject;
  85262. };
  85263. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85264. if (withParents === void 0) { withParents = false; }
  85265. if (withChildren === void 0) { withChildren = false; }
  85266. var serializationObject = {};
  85267. SceneSerializer.ClearCache();
  85268. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85269. if (withParents || withChildren) {
  85270. //deliberate for loop! not for each, appended should be processed as well.
  85271. for (var i = 0; i < toSerialize.length; ++i) {
  85272. if (withChildren) {
  85273. toSerialize[i].getDescendants().forEach(function (node) {
  85274. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85275. toSerialize.push(node);
  85276. }
  85277. });
  85278. }
  85279. //make sure the array doesn't contain the object already
  85280. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85281. toSerialize.push(toSerialize[i].parent);
  85282. }
  85283. }
  85284. }
  85285. toSerialize.forEach(function (mesh) {
  85286. finalizeSingleMesh(mesh, serializationObject);
  85287. });
  85288. return serializationObject;
  85289. };
  85290. return SceneSerializer;
  85291. }());
  85292. BABYLON.SceneSerializer = SceneSerializer;
  85293. })(BABYLON || (BABYLON = {}));
  85294. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85295. var BABYLON;
  85296. (function (BABYLON) {
  85297. var ReflectionProbe = /** @class */ (function () {
  85298. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85299. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85300. var _this = this;
  85301. this.name = name;
  85302. this._viewMatrix = BABYLON.Matrix.Identity();
  85303. this._target = BABYLON.Vector3.Zero();
  85304. this._add = BABYLON.Vector3.Zero();
  85305. this.invertYAxis = false;
  85306. this.position = BABYLON.Vector3.Zero();
  85307. this._scene = scene;
  85308. this._scene.reflectionProbes.push(this);
  85309. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  85310. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  85311. switch (faceIndex) {
  85312. case 0:
  85313. _this._add.copyFromFloats(1, 0, 0);
  85314. break;
  85315. case 1:
  85316. _this._add.copyFromFloats(-1, 0, 0);
  85317. break;
  85318. case 2:
  85319. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  85320. break;
  85321. case 3:
  85322. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  85323. break;
  85324. case 4:
  85325. _this._add.copyFromFloats(0, 0, 1);
  85326. break;
  85327. case 5:
  85328. _this._add.copyFromFloats(0, 0, -1);
  85329. break;
  85330. }
  85331. if (_this._attachedMesh) {
  85332. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  85333. }
  85334. _this.position.addToRef(_this._add, _this._target);
  85335. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  85336. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  85337. scene._forcedViewPosition = _this.position;
  85338. });
  85339. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  85340. scene._forcedViewPosition = null;
  85341. scene.updateTransformMatrix(true);
  85342. });
  85343. if (scene.activeCamera) {
  85344. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85345. }
  85346. }
  85347. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  85348. get: function () {
  85349. return this._renderTargetTexture.samples;
  85350. },
  85351. set: function (value) {
  85352. this._renderTargetTexture.samples = value;
  85353. },
  85354. enumerable: true,
  85355. configurable: true
  85356. });
  85357. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  85358. get: function () {
  85359. return this._renderTargetTexture.refreshRate;
  85360. },
  85361. set: function (value) {
  85362. this._renderTargetTexture.refreshRate = value;
  85363. },
  85364. enumerable: true,
  85365. configurable: true
  85366. });
  85367. ReflectionProbe.prototype.getScene = function () {
  85368. return this._scene;
  85369. };
  85370. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  85371. get: function () {
  85372. return this._renderTargetTexture;
  85373. },
  85374. enumerable: true,
  85375. configurable: true
  85376. });
  85377. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  85378. get: function () {
  85379. return this._renderTargetTexture.renderList;
  85380. },
  85381. enumerable: true,
  85382. configurable: true
  85383. });
  85384. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  85385. this._attachedMesh = mesh;
  85386. };
  85387. /**
  85388. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  85389. *
  85390. * @param renderingGroupId The rendering group id corresponding to its index
  85391. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  85392. */
  85393. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  85394. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  85395. };
  85396. ReflectionProbe.prototype.dispose = function () {
  85397. var index = this._scene.reflectionProbes.indexOf(this);
  85398. if (index !== -1) {
  85399. // Remove from the scene if found
  85400. this._scene.reflectionProbes.splice(index, 1);
  85401. }
  85402. if (this._renderTargetTexture) {
  85403. this._renderTargetTexture.dispose();
  85404. this._renderTargetTexture = null;
  85405. }
  85406. };
  85407. return ReflectionProbe;
  85408. }());
  85409. BABYLON.ReflectionProbe = ReflectionProbe;
  85410. })(BABYLON || (BABYLON = {}));
  85411. //# sourceMappingURL=babylon.reflectionProbe.js.map
  85412. var BABYLON;
  85413. (function (BABYLON) {
  85414. var Layer = /** @class */ (function () {
  85415. function Layer(name, imgUrl, scene, isBackground, color) {
  85416. this.name = name;
  85417. this.scale = new BABYLON.Vector2(1, 1);
  85418. this.offset = new BABYLON.Vector2(0, 0);
  85419. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  85420. this.layerMask = 0x0FFFFFFF;
  85421. this._vertexBuffers = {};
  85422. // Events
  85423. /**
  85424. * An event triggered when the layer is disposed.
  85425. * @type {BABYLON.Observable}
  85426. */
  85427. this.onDisposeObservable = new BABYLON.Observable();
  85428. /**
  85429. * An event triggered before rendering the scene
  85430. * @type {BABYLON.Observable}
  85431. */
  85432. this.onBeforeRenderObservable = new BABYLON.Observable();
  85433. /**
  85434. * An event triggered after rendering the scene
  85435. * @type {BABYLON.Observable}
  85436. */
  85437. this.onAfterRenderObservable = new BABYLON.Observable();
  85438. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  85439. this.isBackground = isBackground === undefined ? true : isBackground;
  85440. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  85441. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  85442. this._scene.layers.push(this);
  85443. var engine = this._scene.getEngine();
  85444. // VBO
  85445. var vertices = [];
  85446. vertices.push(1, 1);
  85447. vertices.push(-1, 1);
  85448. vertices.push(-1, -1);
  85449. vertices.push(1, -1);
  85450. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85451. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  85452. this._createIndexBuffer();
  85453. // Effects
  85454. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  85455. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  85456. }
  85457. Object.defineProperty(Layer.prototype, "onDispose", {
  85458. set: function (callback) {
  85459. if (this._onDisposeObserver) {
  85460. this.onDisposeObservable.remove(this._onDisposeObserver);
  85461. }
  85462. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  85463. },
  85464. enumerable: true,
  85465. configurable: true
  85466. });
  85467. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  85468. set: function (callback) {
  85469. if (this._onBeforeRenderObserver) {
  85470. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  85471. }
  85472. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  85473. },
  85474. enumerable: true,
  85475. configurable: true
  85476. });
  85477. Object.defineProperty(Layer.prototype, "onAfterRender", {
  85478. set: function (callback) {
  85479. if (this._onAfterRenderObserver) {
  85480. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  85481. }
  85482. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  85483. },
  85484. enumerable: true,
  85485. configurable: true
  85486. });
  85487. Layer.prototype._createIndexBuffer = function () {
  85488. var engine = this._scene.getEngine();
  85489. // Indices
  85490. var indices = [];
  85491. indices.push(0);
  85492. indices.push(1);
  85493. indices.push(2);
  85494. indices.push(0);
  85495. indices.push(2);
  85496. indices.push(3);
  85497. this._indexBuffer = engine.createIndexBuffer(indices);
  85498. };
  85499. Layer.prototype._rebuild = function () {
  85500. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85501. if (vb) {
  85502. vb._rebuild();
  85503. }
  85504. this._createIndexBuffer();
  85505. };
  85506. Layer.prototype.render = function () {
  85507. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  85508. // Check
  85509. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  85510. return;
  85511. var engine = this._scene.getEngine();
  85512. this.onBeforeRenderObservable.notifyObservers(this);
  85513. // Render
  85514. engine.enableEffect(currentEffect);
  85515. engine.setState(false);
  85516. // Texture
  85517. currentEffect.setTexture("textureSampler", this.texture);
  85518. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  85519. // Color
  85520. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  85521. // Scale / offset
  85522. currentEffect.setVector2("offset", this.offset);
  85523. currentEffect.setVector2("scale", this.scale);
  85524. // VBOs
  85525. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  85526. // Draw order
  85527. if (!this.alphaTest) {
  85528. engine.setAlphaMode(this.alphaBlendingMode);
  85529. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85530. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  85531. }
  85532. else {
  85533. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  85534. }
  85535. this.onAfterRenderObservable.notifyObservers(this);
  85536. };
  85537. Layer.prototype.dispose = function () {
  85538. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85539. if (vertexBuffer) {
  85540. vertexBuffer.dispose();
  85541. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85542. }
  85543. if (this._indexBuffer) {
  85544. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85545. this._indexBuffer = null;
  85546. }
  85547. if (this.texture) {
  85548. this.texture.dispose();
  85549. this.texture = null;
  85550. }
  85551. // Remove from scene
  85552. var index = this._scene.layers.indexOf(this);
  85553. this._scene.layers.splice(index, 1);
  85554. // Callback
  85555. this.onDisposeObservable.notifyObservers(this);
  85556. this.onDisposeObservable.clear();
  85557. this.onAfterRenderObservable.clear();
  85558. this.onBeforeRenderObservable.clear();
  85559. };
  85560. return Layer;
  85561. }());
  85562. BABYLON.Layer = Layer;
  85563. })(BABYLON || (BABYLON = {}));
  85564. //# sourceMappingURL=babylon.layer.js.map
  85565. var BABYLON;
  85566. (function (BABYLON) {
  85567. var TextureTools = /** @class */ (function () {
  85568. function TextureTools() {
  85569. }
  85570. /**
  85571. * Uses the GPU to create a copy texture rescaled at a given size
  85572. * @param texture Texture to copy from
  85573. * @param width Desired width
  85574. * @param height Desired height
  85575. * @return Generated texture
  85576. */
  85577. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  85578. if (useBilinearMode === void 0) { useBilinearMode = true; }
  85579. var scene = texture.getScene();
  85580. var engine = scene.getEngine();
  85581. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  85582. rtt.wrapU = texture.wrapU;
  85583. rtt.wrapV = texture.wrapV;
  85584. rtt.uOffset = texture.uOffset;
  85585. rtt.vOffset = texture.vOffset;
  85586. rtt.uScale = texture.uScale;
  85587. rtt.vScale = texture.vScale;
  85588. rtt.uAng = texture.uAng;
  85589. rtt.vAng = texture.vAng;
  85590. rtt.wAng = texture.wAng;
  85591. rtt.coordinatesIndex = texture.coordinatesIndex;
  85592. rtt.level = texture.level;
  85593. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  85594. rtt._texture.isReady = false;
  85595. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85596. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85597. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85598. passPostProcess.getEffect().executeWhenCompiled(function () {
  85599. passPostProcess.onApply = function (effect) {
  85600. effect.setTexture("textureSampler", texture);
  85601. };
  85602. var internalTexture = rtt.getInternalTexture();
  85603. if (internalTexture) {
  85604. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  85605. engine.unBindFramebuffer(internalTexture);
  85606. rtt.disposeFramebufferObjects();
  85607. passPostProcess.dispose();
  85608. internalTexture.isReady = true;
  85609. }
  85610. });
  85611. return rtt;
  85612. };
  85613. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  85614. if (!scene._environmentBRDFTexture) {
  85615. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  85616. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85617. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  85618. scene._environmentBRDFTexture = texture;
  85619. }
  85620. return scene._environmentBRDFTexture;
  85621. };
  85622. 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=";
  85623. return TextureTools;
  85624. }());
  85625. BABYLON.TextureTools = TextureTools;
  85626. })(BABYLON || (BABYLON = {}));
  85627. //# sourceMappingURL=babylon.textureTools.js.map
  85628. var BABYLON;
  85629. (function (BABYLON) {
  85630. var FramingBehavior = /** @class */ (function () {
  85631. function FramingBehavior() {
  85632. this._mode = FramingBehavior.FitFrustumSidesMode;
  85633. this._radiusScale = 1.0;
  85634. this._positionScale = 0.5;
  85635. this._defaultElevation = 0.3;
  85636. this._elevationReturnTime = 1500;
  85637. this._elevationReturnWaitTime = 1000;
  85638. this._zoomStopsAnimation = false;
  85639. this._framingTime = 1500;
  85640. this._isPointerDown = false;
  85641. this._lastInteractionTime = -Infinity;
  85642. // Framing control
  85643. this._animatables = new Array();
  85644. this._betaIsAnimating = false;
  85645. }
  85646. Object.defineProperty(FramingBehavior.prototype, "name", {
  85647. get: function () {
  85648. return "Framing";
  85649. },
  85650. enumerable: true,
  85651. configurable: true
  85652. });
  85653. Object.defineProperty(FramingBehavior.prototype, "mode", {
  85654. /**
  85655. * Gets current mode used by the behavior.
  85656. */
  85657. get: function () {
  85658. return this._mode;
  85659. },
  85660. /**
  85661. * Sets the current mode used by the behavior
  85662. */
  85663. set: function (mode) {
  85664. this._mode = mode;
  85665. },
  85666. enumerable: true,
  85667. configurable: true
  85668. });
  85669. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  85670. /**
  85671. * Gets the scale applied to the radius
  85672. */
  85673. get: function () {
  85674. return this._radiusScale;
  85675. },
  85676. /**
  85677. * Sets the scale applied to the radius (1 by default)
  85678. */
  85679. set: function (radius) {
  85680. this._radiusScale = radius;
  85681. },
  85682. enumerable: true,
  85683. configurable: true
  85684. });
  85685. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  85686. /**
  85687. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85688. */
  85689. get: function () {
  85690. return this._positionScale;
  85691. },
  85692. /**
  85693. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  85694. */
  85695. set: function (scale) {
  85696. this._positionScale = scale;
  85697. },
  85698. enumerable: true,
  85699. configurable: true
  85700. });
  85701. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  85702. /**
  85703. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85704. * behaviour is triggered, in radians.
  85705. */
  85706. get: function () {
  85707. return this._defaultElevation;
  85708. },
  85709. /**
  85710. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  85711. * behaviour is triggered, in radians.
  85712. */
  85713. set: function (elevation) {
  85714. this._defaultElevation = elevation;
  85715. },
  85716. enumerable: true,
  85717. configurable: true
  85718. });
  85719. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  85720. /**
  85721. * Gets the time (in milliseconds) taken to return to the default beta position.
  85722. * Negative value indicates camera should not return to default.
  85723. */
  85724. get: function () {
  85725. return this._elevationReturnTime;
  85726. },
  85727. /**
  85728. * Sets the time (in milliseconds) taken to return to the default beta position.
  85729. * Negative value indicates camera should not return to default.
  85730. */
  85731. set: function (speed) {
  85732. this._elevationReturnTime = speed;
  85733. },
  85734. enumerable: true,
  85735. configurable: true
  85736. });
  85737. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  85738. /**
  85739. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85740. */
  85741. get: function () {
  85742. return this._elevationReturnWaitTime;
  85743. },
  85744. /**
  85745. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  85746. */
  85747. set: function (time) {
  85748. this._elevationReturnWaitTime = time;
  85749. },
  85750. enumerable: true,
  85751. configurable: true
  85752. });
  85753. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  85754. /**
  85755. * Gets the flag that indicates if user zooming should stop animation.
  85756. */
  85757. get: function () {
  85758. return this._zoomStopsAnimation;
  85759. },
  85760. /**
  85761. * Sets the flag that indicates if user zooming should stop animation.
  85762. */
  85763. set: function (flag) {
  85764. this._zoomStopsAnimation = flag;
  85765. },
  85766. enumerable: true,
  85767. configurable: true
  85768. });
  85769. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  85770. /**
  85771. * Gets the transition time when framing the mesh, in milliseconds
  85772. */
  85773. get: function () {
  85774. return this._framingTime;
  85775. },
  85776. /**
  85777. * Sets the transition time when framing the mesh, in milliseconds
  85778. */
  85779. set: function (time) {
  85780. this._framingTime = time;
  85781. },
  85782. enumerable: true,
  85783. configurable: true
  85784. });
  85785. FramingBehavior.prototype.init = function () {
  85786. // Do notihng
  85787. };
  85788. FramingBehavior.prototype.attach = function (camera) {
  85789. var _this = this;
  85790. this._attachedCamera = camera;
  85791. var scene = this._attachedCamera.getScene();
  85792. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  85793. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  85794. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  85795. _this._isPointerDown = true;
  85796. return;
  85797. }
  85798. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  85799. _this._isPointerDown = false;
  85800. }
  85801. });
  85802. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  85803. if (mesh) {
  85804. _this.zoomOnMesh(mesh);
  85805. }
  85806. });
  85807. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  85808. // Stop the animation if there is user interaction and the animation should stop for this interaction
  85809. _this._applyUserInteraction();
  85810. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  85811. // back to the default position after a given timeout
  85812. _this._maintainCameraAboveGround();
  85813. });
  85814. };
  85815. FramingBehavior.prototype.detach = function () {
  85816. if (!this._attachedCamera) {
  85817. return;
  85818. }
  85819. var scene = this._attachedCamera.getScene();
  85820. if (this._onPrePointerObservableObserver) {
  85821. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  85822. }
  85823. if (this._onAfterCheckInputsObserver) {
  85824. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  85825. }
  85826. if (this._onMeshTargetChangedObserver) {
  85827. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  85828. }
  85829. this._attachedCamera = null;
  85830. };
  85831. /**
  85832. * Targets the given mesh and updates zoom level accordingly.
  85833. * @param mesh The mesh to target.
  85834. * @param radius Optional. If a cached radius position already exists, overrides default.
  85835. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85836. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85837. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85838. */
  85839. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85840. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85841. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85842. mesh.computeWorldMatrix(true);
  85843. var boundingBox = mesh.getBoundingInfo().boundingBox;
  85844. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  85845. };
  85846. /**
  85847. * Targets the given mesh with its children and updates zoom level accordingly.
  85848. * @param mesh The mesh to target.
  85849. * @param radius Optional. If a cached radius position already exists, overrides default.
  85850. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85851. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85852. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85853. */
  85854. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  85855. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85856. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85857. mesh.computeWorldMatrix(true);
  85858. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  85859. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  85860. };
  85861. /**
  85862. * Targets the given meshes with their children and updates zoom level accordingly.
  85863. * @param meshes The mesh to target.
  85864. * @param radius Optional. If a cached radius position already exists, overrides default.
  85865. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85866. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85867. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85868. */
  85869. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  85870. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85871. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85872. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  85873. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  85874. for (var i = 0; i < meshes.length; i++) {
  85875. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  85876. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  85877. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  85878. }
  85879. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  85880. };
  85881. /**
  85882. * Targets the given mesh and updates zoom level accordingly.
  85883. * @param mesh The mesh to target.
  85884. * @param radius Optional. If a cached radius position already exists, overrides default.
  85885. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  85886. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  85887. * @param onAnimationEnd Callback triggered at the end of the framing animation
  85888. */
  85889. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  85890. var _this = this;
  85891. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  85892. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  85893. var zoomTarget;
  85894. if (!this._attachedCamera) {
  85895. return;
  85896. }
  85897. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  85898. var bottom = minimumWorld.y;
  85899. var top = maximumWorld.y;
  85900. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  85901. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  85902. if (focusOnOriginXZ) {
  85903. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  85904. }
  85905. else {
  85906. var centerWorld = minimumWorld.add(radiusWorld);
  85907. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  85908. }
  85909. if (!this._vectorTransition) {
  85910. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  85911. }
  85912. this._betaIsAnimating = true;
  85913. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  85914. if (animatable) {
  85915. this._animatables.push(animatable);
  85916. }
  85917. // sets the radius and lower radius bounds
  85918. // Small delta ensures camera is not always at lower zoom limit.
  85919. var radius = 0;
  85920. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  85921. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85922. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  85923. radius = position;
  85924. }
  85925. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85926. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  85927. if (this._attachedCamera.lowerRadiusLimit === null) {
  85928. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  85929. }
  85930. }
  85931. // Set sensibilities
  85932. var extend = maximumWorld.subtract(minimumWorld).length();
  85933. this._attachedCamera.panningSensibility = 5000 / extend;
  85934. this._attachedCamera.wheelPrecision = 100 / radius;
  85935. // transition to new radius
  85936. if (!this._radiusTransition) {
  85937. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  85938. }
  85939. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  85940. if (onAnimationEnd) {
  85941. onAnimationEnd();
  85942. }
  85943. if (_this._attachedCamera) {
  85944. _this._attachedCamera.storeState();
  85945. }
  85946. });
  85947. if (animatable) {
  85948. this._animatables.push(animatable);
  85949. }
  85950. };
  85951. /**
  85952. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  85953. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  85954. * frustum width.
  85955. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  85956. * to fully enclose the mesh in the viewing frustum.
  85957. */
  85958. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  85959. var size = maximumWorld.subtract(minimumWorld);
  85960. var boxVectorGlobalDiagonal = size.length();
  85961. var frustumSlope = this._getFrustumSlope();
  85962. // Formula for setting distance
  85963. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  85964. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  85965. // Horizon distance
  85966. var radius = radiusWithoutFraming * this._radiusScale;
  85967. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  85968. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  85969. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  85970. var camera = this._attachedCamera;
  85971. if (!camera) {
  85972. return 0;
  85973. }
  85974. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  85975. // Don't exceed the requested limit
  85976. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  85977. }
  85978. // Don't exceed the upper radius limit
  85979. if (camera.upperRadiusLimit) {
  85980. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  85981. }
  85982. return distance;
  85983. };
  85984. /**
  85985. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  85986. * is automatically returned to its default position (expected to be above ground plane).
  85987. */
  85988. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  85989. var _this = this;
  85990. if (this._elevationReturnTime < 0) {
  85991. return;
  85992. }
  85993. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  85994. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  85995. var limitBeta = Math.PI * 0.5;
  85996. // Bring the camera back up if below the ground plane
  85997. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  85998. this._betaIsAnimating = true;
  85999. //Transition to new position
  86000. this.stopAllAnimations();
  86001. if (!this._betaTransition) {
  86002. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86003. }
  86004. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86005. _this._clearAnimationLocks();
  86006. _this.stopAllAnimations();
  86007. });
  86008. if (animatabe) {
  86009. this._animatables.push(animatabe);
  86010. }
  86011. }
  86012. };
  86013. /**
  86014. * Returns the frustum slope based on the canvas ratio and camera FOV
  86015. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86016. */
  86017. FramingBehavior.prototype._getFrustumSlope = function () {
  86018. // Calculate the viewport ratio
  86019. // Aspect Ratio is Height/Width.
  86020. var camera = this._attachedCamera;
  86021. if (!camera) {
  86022. return BABYLON.Vector2.Zero();
  86023. }
  86024. var engine = camera.getScene().getEngine();
  86025. var aspectRatio = engine.getAspectRatio(camera);
  86026. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86027. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86028. var frustumSlopeY = Math.tan(camera.fov / 2);
  86029. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86030. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86031. // along the forward vector.
  86032. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86033. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86034. };
  86035. /**
  86036. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86037. */
  86038. FramingBehavior.prototype._clearAnimationLocks = function () {
  86039. this._betaIsAnimating = false;
  86040. };
  86041. /**
  86042. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86043. */
  86044. FramingBehavior.prototype._applyUserInteraction = function () {
  86045. if (this.isUserIsMoving) {
  86046. this._lastInteractionTime = BABYLON.Tools.Now;
  86047. this.stopAllAnimations();
  86048. this._clearAnimationLocks();
  86049. }
  86050. };
  86051. /**
  86052. * Stops and removes all animations that have been applied to the camera
  86053. */
  86054. FramingBehavior.prototype.stopAllAnimations = function () {
  86055. if (this._attachedCamera) {
  86056. this._attachedCamera.animations = [];
  86057. }
  86058. while (this._animatables.length) {
  86059. if (this._animatables[0]) {
  86060. this._animatables[0].onAnimationEnd = null;
  86061. this._animatables[0].stop();
  86062. }
  86063. this._animatables.shift();
  86064. }
  86065. };
  86066. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86067. /**
  86068. * Gets a value indicating if the user is moving the camera
  86069. */
  86070. get: function () {
  86071. if (!this._attachedCamera) {
  86072. return false;
  86073. }
  86074. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86075. this._attachedCamera.inertialBetaOffset !== 0 ||
  86076. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86077. this._attachedCamera.inertialPanningX !== 0 ||
  86078. this._attachedCamera.inertialPanningY !== 0 ||
  86079. this._isPointerDown;
  86080. },
  86081. enumerable: true,
  86082. configurable: true
  86083. });
  86084. /**
  86085. * The easing function used by animations
  86086. */
  86087. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86088. /**
  86089. * The easing mode used by animations
  86090. */
  86091. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86092. // Statics
  86093. /**
  86094. * The camera can move all the way towards the mesh.
  86095. */
  86096. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86097. /**
  86098. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86099. */
  86100. FramingBehavior.FitFrustumSidesMode = 1;
  86101. return FramingBehavior;
  86102. }());
  86103. BABYLON.FramingBehavior = FramingBehavior;
  86104. })(BABYLON || (BABYLON = {}));
  86105. //# sourceMappingURL=babylon.framingBehavior.js.map
  86106. var BABYLON;
  86107. (function (BABYLON) {
  86108. /**
  86109. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86110. */
  86111. var BouncingBehavior = /** @class */ (function () {
  86112. function BouncingBehavior() {
  86113. /**
  86114. * The duration of the animation, in milliseconds
  86115. */
  86116. this.transitionDuration = 450;
  86117. /**
  86118. * Length of the distance animated by the transition when lower radius is reached
  86119. */
  86120. this.lowerRadiusTransitionRange = 2;
  86121. /**
  86122. * Length of the distance animated by the transition when upper radius is reached
  86123. */
  86124. this.upperRadiusTransitionRange = -2;
  86125. this._autoTransitionRange = false;
  86126. // Animations
  86127. this._radiusIsAnimating = false;
  86128. this._radiusBounceTransition = null;
  86129. this._animatables = new Array();
  86130. }
  86131. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86132. get: function () {
  86133. return "Bouncing";
  86134. },
  86135. enumerable: true,
  86136. configurable: true
  86137. });
  86138. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86139. /**
  86140. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86141. */
  86142. get: function () {
  86143. return this._autoTransitionRange;
  86144. },
  86145. /**
  86146. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86147. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86148. */
  86149. set: function (value) {
  86150. var _this = this;
  86151. if (this._autoTransitionRange === value) {
  86152. return;
  86153. }
  86154. this._autoTransitionRange = value;
  86155. var camera = this._attachedCamera;
  86156. if (!camera) {
  86157. return;
  86158. }
  86159. if (value) {
  86160. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86161. if (!mesh) {
  86162. return;
  86163. }
  86164. mesh.computeWorldMatrix(true);
  86165. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86166. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86167. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86168. });
  86169. }
  86170. else if (this._onMeshTargetChangedObserver) {
  86171. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86172. }
  86173. },
  86174. enumerable: true,
  86175. configurable: true
  86176. });
  86177. BouncingBehavior.prototype.init = function () {
  86178. // Do notihng
  86179. };
  86180. BouncingBehavior.prototype.attach = function (camera) {
  86181. var _this = this;
  86182. this._attachedCamera = camera;
  86183. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86184. if (!_this._attachedCamera) {
  86185. return;
  86186. }
  86187. // Add the bounce animation to the lower radius limit
  86188. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86189. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86190. }
  86191. // Add the bounce animation to the upper radius limit
  86192. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86193. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86194. }
  86195. });
  86196. };
  86197. BouncingBehavior.prototype.detach = function () {
  86198. if (!this._attachedCamera) {
  86199. return;
  86200. }
  86201. if (this._onAfterCheckInputsObserver) {
  86202. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86203. }
  86204. if (this._onMeshTargetChangedObserver) {
  86205. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86206. }
  86207. this._attachedCamera = null;
  86208. };
  86209. /**
  86210. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86211. * @param radiusLimit The limit to check against.
  86212. * @return Bool to indicate if at limit.
  86213. */
  86214. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86215. if (!this._attachedCamera) {
  86216. return false;
  86217. }
  86218. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86219. return true;
  86220. }
  86221. return false;
  86222. };
  86223. /**
  86224. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86225. * @param radiusDelta The delta by which to animate to. Can be negative.
  86226. */
  86227. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86228. var _this = this;
  86229. if (!this._attachedCamera) {
  86230. return;
  86231. }
  86232. if (!this._radiusBounceTransition) {
  86233. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86234. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86235. }
  86236. // Prevent zoom until bounce has completed
  86237. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86238. this._attachedCamera.wheelPrecision = Infinity;
  86239. this._attachedCamera.inertialRadiusOffset = 0;
  86240. // Animate to the radius limit
  86241. this.stopAllAnimations();
  86242. this._radiusIsAnimating = true;
  86243. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86244. if (animatable) {
  86245. this._animatables.push(animatable);
  86246. }
  86247. };
  86248. /**
  86249. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86250. */
  86251. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86252. this._radiusIsAnimating = false;
  86253. if (this._attachedCamera) {
  86254. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86255. }
  86256. };
  86257. /**
  86258. * Stops and removes all animations that have been applied to the camera
  86259. */
  86260. BouncingBehavior.prototype.stopAllAnimations = function () {
  86261. if (this._attachedCamera) {
  86262. this._attachedCamera.animations = [];
  86263. }
  86264. while (this._animatables.length) {
  86265. this._animatables[0].onAnimationEnd = null;
  86266. this._animatables[0].stop();
  86267. this._animatables.shift();
  86268. }
  86269. };
  86270. /**
  86271. * The easing function used by animations
  86272. */
  86273. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86274. /**
  86275. * The easing mode used by animations
  86276. */
  86277. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86278. return BouncingBehavior;
  86279. }());
  86280. BABYLON.BouncingBehavior = BouncingBehavior;
  86281. })(BABYLON || (BABYLON = {}));
  86282. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86283. var BABYLON;
  86284. (function (BABYLON) {
  86285. var AutoRotationBehavior = /** @class */ (function () {
  86286. function AutoRotationBehavior() {
  86287. this._zoomStopsAnimation = false;
  86288. this._idleRotationSpeed = 0.05;
  86289. this._idleRotationWaitTime = 2000;
  86290. this._idleRotationSpinupTime = 2000;
  86291. this._isPointerDown = false;
  86292. this._lastFrameTime = null;
  86293. this._lastInteractionTime = -Infinity;
  86294. this._cameraRotationSpeed = 0;
  86295. this._lastFrameRadius = 0;
  86296. }
  86297. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86298. get: function () {
  86299. return "AutoRotation";
  86300. },
  86301. enumerable: true,
  86302. configurable: true
  86303. });
  86304. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86305. /**
  86306. * Gets the flag that indicates if user zooming should stop animation.
  86307. */
  86308. get: function () {
  86309. return this._zoomStopsAnimation;
  86310. },
  86311. /**
  86312. * Sets the flag that indicates if user zooming should stop animation.
  86313. */
  86314. set: function (flag) {
  86315. this._zoomStopsAnimation = flag;
  86316. },
  86317. enumerable: true,
  86318. configurable: true
  86319. });
  86320. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  86321. /**
  86322. * Gets the default speed at which the camera rotates around the model.
  86323. */
  86324. get: function () {
  86325. return this._idleRotationSpeed;
  86326. },
  86327. /**
  86328. * Sets the default speed at which the camera rotates around the model.
  86329. */
  86330. set: function (speed) {
  86331. this._idleRotationSpeed = speed;
  86332. },
  86333. enumerable: true,
  86334. configurable: true
  86335. });
  86336. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  86337. /**
  86338. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  86339. */
  86340. get: function () {
  86341. return this._idleRotationWaitTime;
  86342. },
  86343. /**
  86344. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  86345. */
  86346. set: function (time) {
  86347. this._idleRotationWaitTime = time;
  86348. },
  86349. enumerable: true,
  86350. configurable: true
  86351. });
  86352. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  86353. /**
  86354. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86355. */
  86356. get: function () {
  86357. return this._idleRotationSpinupTime;
  86358. },
  86359. /**
  86360. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86361. */
  86362. set: function (time) {
  86363. this._idleRotationSpinupTime = time;
  86364. },
  86365. enumerable: true,
  86366. configurable: true
  86367. });
  86368. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  86369. /**
  86370. * Gets a value indicating if the camera is currently rotating because of this behavior
  86371. */
  86372. get: function () {
  86373. return Math.abs(this._cameraRotationSpeed) > 0;
  86374. },
  86375. enumerable: true,
  86376. configurable: true
  86377. });
  86378. AutoRotationBehavior.prototype.init = function () {
  86379. // Do notihng
  86380. };
  86381. AutoRotationBehavior.prototype.attach = function (camera) {
  86382. var _this = this;
  86383. this._attachedCamera = camera;
  86384. var scene = this._attachedCamera.getScene();
  86385. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86386. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86387. _this._isPointerDown = true;
  86388. return;
  86389. }
  86390. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86391. _this._isPointerDown = false;
  86392. }
  86393. });
  86394. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86395. var now = BABYLON.Tools.Now;
  86396. var dt = 0;
  86397. if (_this._lastFrameTime != null) {
  86398. dt = now - _this._lastFrameTime;
  86399. }
  86400. _this._lastFrameTime = now;
  86401. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86402. _this._applyUserInteraction();
  86403. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  86404. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  86405. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  86406. // Step camera rotation by rotation speed
  86407. if (_this._attachedCamera) {
  86408. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  86409. }
  86410. });
  86411. };
  86412. AutoRotationBehavior.prototype.detach = function () {
  86413. if (!this._attachedCamera) {
  86414. return;
  86415. }
  86416. var scene = this._attachedCamera.getScene();
  86417. if (this._onPrePointerObservableObserver) {
  86418. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86419. }
  86420. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86421. this._attachedCamera = null;
  86422. };
  86423. /**
  86424. * Returns true if user is scrolling.
  86425. * @return true if user is scrolling.
  86426. */
  86427. AutoRotationBehavior.prototype._userIsZooming = function () {
  86428. if (!this._attachedCamera) {
  86429. return false;
  86430. }
  86431. return this._attachedCamera.inertialRadiusOffset !== 0;
  86432. };
  86433. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  86434. if (!this._attachedCamera) {
  86435. return false;
  86436. }
  86437. var zoomHasHitLimit = false;
  86438. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  86439. zoomHasHitLimit = true;
  86440. }
  86441. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  86442. this._lastFrameRadius = this._attachedCamera.radius;
  86443. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  86444. };
  86445. /**
  86446. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86447. */
  86448. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  86449. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  86450. this._lastInteractionTime = BABYLON.Tools.Now;
  86451. }
  86452. };
  86453. // Tools
  86454. AutoRotationBehavior.prototype._userIsMoving = function () {
  86455. if (!this._attachedCamera) {
  86456. return false;
  86457. }
  86458. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86459. this._attachedCamera.inertialBetaOffset !== 0 ||
  86460. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86461. this._attachedCamera.inertialPanningX !== 0 ||
  86462. this._attachedCamera.inertialPanningY !== 0 ||
  86463. this._isPointerDown;
  86464. };
  86465. return AutoRotationBehavior;
  86466. }());
  86467. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  86468. })(BABYLON || (BABYLON = {}));
  86469. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  86470. var BABYLON;
  86471. (function (BABYLON) {
  86472. var NullEngineOptions = /** @class */ (function () {
  86473. function NullEngineOptions() {
  86474. this.renderWidth = 512;
  86475. this.renderHeight = 256;
  86476. this.textureSize = 512;
  86477. this.deterministicLockstep = false;
  86478. this.lockstepMaxSteps = 4;
  86479. }
  86480. return NullEngineOptions;
  86481. }());
  86482. BABYLON.NullEngineOptions = NullEngineOptions;
  86483. /**
  86484. * The null engine class provides support for headless version of babylon.js.
  86485. * This can be used in server side scenario or for testing purposes
  86486. */
  86487. var NullEngine = /** @class */ (function (_super) {
  86488. __extends(NullEngine, _super);
  86489. function NullEngine(options) {
  86490. if (options === void 0) { options = new NullEngineOptions(); }
  86491. var _this = _super.call(this, null) || this;
  86492. if (options.deterministicLockstep === undefined) {
  86493. options.deterministicLockstep = false;
  86494. }
  86495. if (options.lockstepMaxSteps === undefined) {
  86496. options.lockstepMaxSteps = 4;
  86497. }
  86498. _this._options = options;
  86499. // Init caps
  86500. // We consider we are on a webgl1 capable device
  86501. _this._caps = new BABYLON.EngineCapabilities();
  86502. _this._caps.maxTexturesImageUnits = 16;
  86503. _this._caps.maxVertexTextureImageUnits = 16;
  86504. _this._caps.maxTextureSize = 512;
  86505. _this._caps.maxCubemapTextureSize = 512;
  86506. _this._caps.maxRenderTextureSize = 512;
  86507. _this._caps.maxVertexAttribs = 16;
  86508. _this._caps.maxVaryingVectors = 16;
  86509. _this._caps.maxFragmentUniformVectors = 16;
  86510. _this._caps.maxVertexUniformVectors = 16;
  86511. // Extensions
  86512. _this._caps.standardDerivatives = false;
  86513. _this._caps.astc = null;
  86514. _this._caps.s3tc = null;
  86515. _this._caps.pvrtc = null;
  86516. _this._caps.etc1 = null;
  86517. _this._caps.etc2 = null;
  86518. _this._caps.textureAnisotropicFilterExtension = null;
  86519. _this._caps.maxAnisotropy = 0;
  86520. _this._caps.uintIndices = false;
  86521. _this._caps.fragmentDepthSupported = false;
  86522. _this._caps.highPrecisionShaderSupported = true;
  86523. _this._caps.colorBufferFloat = false;
  86524. _this._caps.textureFloat = false;
  86525. _this._caps.textureFloatLinearFiltering = false;
  86526. _this._caps.textureFloatRender = false;
  86527. _this._caps.textureHalfFloat = false;
  86528. _this._caps.textureHalfFloatLinearFiltering = false;
  86529. _this._caps.textureHalfFloatRender = false;
  86530. _this._caps.textureLOD = false;
  86531. _this._caps.drawBuffersExtension = false;
  86532. _this._caps.depthTextureExtension = false;
  86533. _this._caps.vertexArrayObject = false;
  86534. _this._caps.instancedArrays = false;
  86535. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  86536. // Wrappers
  86537. if (typeof URL === "undefined") {
  86538. URL = {
  86539. createObjectURL: function () { },
  86540. revokeObjectURL: function () { }
  86541. };
  86542. }
  86543. if (typeof Blob === "undefined") {
  86544. Blob = function () { };
  86545. }
  86546. return _this;
  86547. }
  86548. NullEngine.prototype.isDeterministicLockStep = function () {
  86549. return this._options.deterministicLockstep;
  86550. };
  86551. NullEngine.prototype.getLockstepMaxSteps = function () {
  86552. return this._options.lockstepMaxSteps;
  86553. };
  86554. NullEngine.prototype.createVertexBuffer = function (vertices) {
  86555. return {
  86556. capacity: 0,
  86557. references: 1,
  86558. is32Bits: false
  86559. };
  86560. };
  86561. NullEngine.prototype.createIndexBuffer = function (indices) {
  86562. return {
  86563. capacity: 0,
  86564. references: 1,
  86565. is32Bits: false
  86566. };
  86567. };
  86568. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  86569. if (stencil === void 0) { stencil = false; }
  86570. };
  86571. NullEngine.prototype.getRenderWidth = function (useScreen) {
  86572. if (useScreen === void 0) { useScreen = false; }
  86573. if (!useScreen && this._currentRenderTarget) {
  86574. return this._currentRenderTarget.width;
  86575. }
  86576. return this._options.renderWidth;
  86577. };
  86578. NullEngine.prototype.getRenderHeight = function (useScreen) {
  86579. if (useScreen === void 0) { useScreen = false; }
  86580. if (!useScreen && this._currentRenderTarget) {
  86581. return this._currentRenderTarget.height;
  86582. }
  86583. return this._options.renderHeight;
  86584. };
  86585. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  86586. this._cachedViewport = viewport;
  86587. };
  86588. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  86589. return {
  86590. transformFeedback: null,
  86591. __SPECTOR_rebuildProgram: null
  86592. };
  86593. };
  86594. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  86595. return [];
  86596. };
  86597. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  86598. return [];
  86599. };
  86600. NullEngine.prototype.bindSamplers = function (effect) {
  86601. this._currentEffect = null;
  86602. };
  86603. NullEngine.prototype.enableEffect = function (effect) {
  86604. this._currentEffect = effect;
  86605. if (effect.onBind) {
  86606. effect.onBind(effect);
  86607. }
  86608. effect.onBindObservable.notifyObservers(effect);
  86609. };
  86610. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  86611. if (zOffset === void 0) { zOffset = 0; }
  86612. if (reverseSide === void 0) { reverseSide = false; }
  86613. };
  86614. NullEngine.prototype.setIntArray = function (uniform, array) {
  86615. };
  86616. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  86617. };
  86618. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  86619. };
  86620. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  86621. };
  86622. NullEngine.prototype.setFloatArray = function (uniform, array) {
  86623. };
  86624. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  86625. };
  86626. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  86627. };
  86628. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  86629. };
  86630. NullEngine.prototype.setArray = function (uniform, array) {
  86631. };
  86632. NullEngine.prototype.setArray2 = function (uniform, array) {
  86633. };
  86634. NullEngine.prototype.setArray3 = function (uniform, array) {
  86635. };
  86636. NullEngine.prototype.setArray4 = function (uniform, array) {
  86637. };
  86638. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  86639. };
  86640. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  86641. };
  86642. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  86643. };
  86644. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  86645. };
  86646. NullEngine.prototype.setFloat = function (uniform, value) {
  86647. };
  86648. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  86649. };
  86650. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  86651. };
  86652. NullEngine.prototype.setBool = function (uniform, bool) {
  86653. };
  86654. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  86655. };
  86656. NullEngine.prototype.setColor3 = function (uniform, color3) {
  86657. };
  86658. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  86659. };
  86660. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  86661. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  86662. if (this._alphaMode === mode) {
  86663. return;
  86664. }
  86665. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  86666. if (!noDepthWriteChange) {
  86667. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  86668. }
  86669. this._alphaMode = mode;
  86670. };
  86671. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  86672. };
  86673. NullEngine.prototype.wipeCaches = function (bruteForce) {
  86674. if (this.preventCacheWipeBetweenFrames) {
  86675. return;
  86676. }
  86677. this.resetTextureCache();
  86678. this._currentEffect = null;
  86679. if (bruteForce) {
  86680. this._currentProgram = null;
  86681. this._stencilState.reset();
  86682. this._depthCullingState.reset();
  86683. this._alphaState.reset();
  86684. }
  86685. this._cachedVertexBuffers = null;
  86686. this._cachedIndexBuffer = null;
  86687. this._cachedEffectForVertexBuffers = null;
  86688. };
  86689. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  86690. };
  86691. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  86692. };
  86693. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  86694. };
  86695. NullEngine.prototype._createTexture = function () {
  86696. return {};
  86697. };
  86698. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  86699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  86700. if (onLoad === void 0) { onLoad = null; }
  86701. if (onError === void 0) { onError = null; }
  86702. if (buffer === void 0) { buffer = null; }
  86703. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  86704. var url = String(urlArg);
  86705. texture.url = url;
  86706. texture.generateMipMaps = !noMipmap;
  86707. texture.samplingMode = samplingMode;
  86708. texture.invertY = invertY;
  86709. texture.baseWidth = this._options.textureSize;
  86710. texture.baseHeight = this._options.textureSize;
  86711. texture.width = this._options.textureSize;
  86712. texture.height = this._options.textureSize;
  86713. if (format) {
  86714. texture.format = format;
  86715. }
  86716. texture.isReady = true;
  86717. if (onLoad) {
  86718. onLoad();
  86719. }
  86720. return texture;
  86721. };
  86722. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  86723. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  86724. if (options !== undefined && typeof options === "object") {
  86725. fullOptions.generateMipMaps = options.generateMipMaps;
  86726. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  86727. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  86728. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  86729. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  86730. }
  86731. else {
  86732. fullOptions.generateMipMaps = options;
  86733. fullOptions.generateDepthBuffer = true;
  86734. fullOptions.generateStencilBuffer = false;
  86735. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86736. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  86737. }
  86738. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  86739. var width = size.width || size;
  86740. var height = size.height || size;
  86741. texture._depthStencilBuffer = {};
  86742. texture._framebuffer = {};
  86743. texture.baseWidth = width;
  86744. texture.baseHeight = height;
  86745. texture.width = width;
  86746. texture.height = height;
  86747. texture.isReady = true;
  86748. texture.samples = 1;
  86749. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  86750. texture.samplingMode = fullOptions.samplingMode;
  86751. texture.type = fullOptions.type;
  86752. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  86753. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  86754. return texture;
  86755. };
  86756. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  86757. texture.samplingMode = samplingMode;
  86758. };
  86759. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  86760. if (this._currentRenderTarget) {
  86761. this.unBindFramebuffer(this._currentRenderTarget);
  86762. }
  86763. this._currentRenderTarget = texture;
  86764. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  86765. if (this._cachedViewport && !forceFullscreenViewport) {
  86766. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  86767. }
  86768. };
  86769. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  86770. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  86771. this._currentRenderTarget = null;
  86772. if (onBeforeUnbind) {
  86773. if (texture._MSAAFramebuffer) {
  86774. this._currentFramebuffer = texture._framebuffer;
  86775. }
  86776. onBeforeUnbind();
  86777. }
  86778. this._currentFramebuffer = null;
  86779. };
  86780. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  86781. var vbo = {
  86782. capacity: 1,
  86783. references: 1,
  86784. is32Bits: false
  86785. };
  86786. return vbo;
  86787. };
  86788. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  86789. if (offset === void 0) { offset = 0; }
  86790. };
  86791. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  86792. };
  86793. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  86794. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  86795. this._boundTexturesCache[this._activeChannel] = texture;
  86796. }
  86797. };
  86798. NullEngine.prototype._bindTexture = function (channel, texture) {
  86799. if (channel < 0) {
  86800. return;
  86801. }
  86802. this._bindTextureDirectly(0, texture);
  86803. };
  86804. NullEngine.prototype._releaseBuffer = function (buffer) {
  86805. buffer.references--;
  86806. if (buffer.references === 0) {
  86807. return true;
  86808. }
  86809. return false;
  86810. };
  86811. return NullEngine;
  86812. }(BABYLON.Engine));
  86813. BABYLON.NullEngine = NullEngine;
  86814. })(BABYLON || (BABYLON = {}));
  86815. //# sourceMappingURL=babylon.nullEngine.js.map
  86816. var BABYLON;
  86817. (function (BABYLON) {
  86818. /**
  86819. * This class can be used to get instrumentation data from a Babylon engine
  86820. */
  86821. var EngineInstrumentation = /** @class */ (function () {
  86822. function EngineInstrumentation(engine) {
  86823. this.engine = engine;
  86824. this._captureGPUFrameTime = false;
  86825. this._gpuFrameTime = new BABYLON.PerfCounter();
  86826. this._captureShaderCompilationTime = false;
  86827. this._shaderCompilationTime = new BABYLON.PerfCounter();
  86828. // Observers
  86829. this._onBeginFrameObserver = null;
  86830. this._onEndFrameObserver = null;
  86831. this._onBeforeShaderCompilationObserver = null;
  86832. this._onAfterShaderCompilationObserver = null;
  86833. }
  86834. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  86835. // Properties
  86836. /**
  86837. * Gets the perf counter used for GPU frame time
  86838. */
  86839. get: function () {
  86840. return this._gpuFrameTime;
  86841. },
  86842. enumerable: true,
  86843. configurable: true
  86844. });
  86845. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  86846. /**
  86847. * Gets the GPU frame time capture status
  86848. */
  86849. get: function () {
  86850. return this._captureGPUFrameTime;
  86851. },
  86852. /**
  86853. * Enable or disable the GPU frame time capture
  86854. */
  86855. set: function (value) {
  86856. var _this = this;
  86857. if (value === this._captureGPUFrameTime) {
  86858. return;
  86859. }
  86860. this._captureGPUFrameTime = value;
  86861. if (value) {
  86862. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  86863. if (!_this._gpuFrameTimeToken) {
  86864. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  86865. }
  86866. });
  86867. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  86868. if (!_this._gpuFrameTimeToken) {
  86869. return;
  86870. }
  86871. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  86872. if (time > -1) {
  86873. _this._gpuFrameTimeToken = null;
  86874. _this._gpuFrameTime.fetchNewFrame();
  86875. _this._gpuFrameTime.addCount(time, true);
  86876. }
  86877. });
  86878. }
  86879. else {
  86880. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86881. this._onBeginFrameObserver = null;
  86882. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86883. this._onEndFrameObserver = null;
  86884. }
  86885. },
  86886. enumerable: true,
  86887. configurable: true
  86888. });
  86889. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  86890. /**
  86891. * Gets the perf counter used for shader compilation time
  86892. */
  86893. get: function () {
  86894. return this._shaderCompilationTime;
  86895. },
  86896. enumerable: true,
  86897. configurable: true
  86898. });
  86899. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  86900. /**
  86901. * Gets the shader compilation time capture status
  86902. */
  86903. get: function () {
  86904. return this._captureShaderCompilationTime;
  86905. },
  86906. /**
  86907. * Enable or disable the shader compilation time capture
  86908. */
  86909. set: function (value) {
  86910. var _this = this;
  86911. if (value === this._captureShaderCompilationTime) {
  86912. return;
  86913. }
  86914. this._captureShaderCompilationTime = value;
  86915. if (value) {
  86916. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  86917. _this._shaderCompilationTime.fetchNewFrame();
  86918. _this._shaderCompilationTime.beginMonitoring();
  86919. });
  86920. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  86921. _this._shaderCompilationTime.endMonitoring();
  86922. });
  86923. }
  86924. else {
  86925. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86926. this._onBeforeShaderCompilationObserver = null;
  86927. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86928. this._onAfterShaderCompilationObserver = null;
  86929. }
  86930. },
  86931. enumerable: true,
  86932. configurable: true
  86933. });
  86934. EngineInstrumentation.prototype.dispose = function () {
  86935. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  86936. this._onBeginFrameObserver = null;
  86937. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  86938. this._onEndFrameObserver = null;
  86939. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  86940. this._onBeforeShaderCompilationObserver = null;
  86941. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  86942. this._onAfterShaderCompilationObserver = null;
  86943. this.engine = null;
  86944. };
  86945. return EngineInstrumentation;
  86946. }());
  86947. BABYLON.EngineInstrumentation = EngineInstrumentation;
  86948. })(BABYLON || (BABYLON = {}));
  86949. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  86950. var BABYLON;
  86951. (function (BABYLON) {
  86952. /**
  86953. * This class can be used to get instrumentation data from a Babylon engine
  86954. */
  86955. var SceneInstrumentation = /** @class */ (function () {
  86956. function SceneInstrumentation(scene) {
  86957. var _this = this;
  86958. this.scene = scene;
  86959. this._captureActiveMeshesEvaluationTime = false;
  86960. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  86961. this._captureRenderTargetsRenderTime = false;
  86962. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  86963. this._captureFrameTime = false;
  86964. this._frameTime = new BABYLON.PerfCounter();
  86965. this._captureRenderTime = false;
  86966. this._renderTime = new BABYLON.PerfCounter();
  86967. this._captureInterFrameTime = false;
  86968. this._interFrameTime = new BABYLON.PerfCounter();
  86969. this._captureParticlesRenderTime = false;
  86970. this._particlesRenderTime = new BABYLON.PerfCounter();
  86971. this._captureSpritesRenderTime = false;
  86972. this._spritesRenderTime = new BABYLON.PerfCounter();
  86973. this._capturePhysicsTime = false;
  86974. this._physicsTime = new BABYLON.PerfCounter();
  86975. this._captureAnimationsTime = false;
  86976. this._animationsTime = new BABYLON.PerfCounter();
  86977. // Observers
  86978. this._onBeforeActiveMeshesEvaluationObserver = null;
  86979. this._onAfterActiveMeshesEvaluationObserver = null;
  86980. this._onBeforeRenderTargetsRenderObserver = null;
  86981. this._onAfterRenderTargetsRenderObserver = null;
  86982. this._onAfterRenderObserver = null;
  86983. this._onBeforeDrawPhaseObserver = null;
  86984. this._onAfterDrawPhaseObserver = null;
  86985. this._onBeforeAnimationsObserver = null;
  86986. this._onBeforeParticlesRenderingObserver = null;
  86987. this._onAfterParticlesRenderingObserver = null;
  86988. this._onBeforeSpritesRenderingObserver = null;
  86989. this._onAfterSpritesRenderingObserver = null;
  86990. this._onBeforePhysicsObserver = null;
  86991. this._onAfterPhysicsObserver = null;
  86992. this._onAfterAnimationsObserver = null;
  86993. // Before render
  86994. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  86995. if (_this._captureActiveMeshesEvaluationTime) {
  86996. _this._activeMeshesEvaluationTime.fetchNewFrame();
  86997. }
  86998. if (_this._captureRenderTargetsRenderTime) {
  86999. _this._renderTargetsRenderTime.fetchNewFrame();
  87000. }
  87001. if (_this._captureFrameTime) {
  87002. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87003. _this._frameTime.beginMonitoring();
  87004. }
  87005. if (_this._captureInterFrameTime) {
  87006. _this._interFrameTime.endMonitoring();
  87007. }
  87008. if (_this._captureParticlesRenderTime) {
  87009. _this._particlesRenderTime.fetchNewFrame();
  87010. }
  87011. if (_this._captureSpritesRenderTime) {
  87012. _this._spritesRenderTime.fetchNewFrame();
  87013. }
  87014. if (_this._captureAnimationsTime) {
  87015. _this._animationsTime.beginMonitoring();
  87016. }
  87017. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87018. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87019. });
  87020. // After render
  87021. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87022. if (_this._captureFrameTime) {
  87023. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87024. _this._frameTime.endMonitoring();
  87025. }
  87026. if (_this._captureRenderTime) {
  87027. _this._renderTime.endMonitoring(false);
  87028. }
  87029. if (_this._captureInterFrameTime) {
  87030. _this._interFrameTime.beginMonitoring();
  87031. }
  87032. });
  87033. }
  87034. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87035. // Properties
  87036. /**
  87037. * Gets the perf counter used for active meshes evaluation time
  87038. */
  87039. get: function () {
  87040. return this._activeMeshesEvaluationTime;
  87041. },
  87042. enumerable: true,
  87043. configurable: true
  87044. });
  87045. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87046. /**
  87047. * Gets the active meshes evaluation time capture status
  87048. */
  87049. get: function () {
  87050. return this._captureActiveMeshesEvaluationTime;
  87051. },
  87052. /**
  87053. * Enable or disable the active meshes evaluation time capture
  87054. */
  87055. set: function (value) {
  87056. var _this = this;
  87057. if (value === this._captureActiveMeshesEvaluationTime) {
  87058. return;
  87059. }
  87060. this._captureActiveMeshesEvaluationTime = value;
  87061. if (value) {
  87062. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87063. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87064. _this._activeMeshesEvaluationTime.beginMonitoring();
  87065. });
  87066. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87067. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87068. _this._activeMeshesEvaluationTime.endMonitoring();
  87069. });
  87070. }
  87071. else {
  87072. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87073. this._onBeforeActiveMeshesEvaluationObserver = null;
  87074. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87075. this._onAfterActiveMeshesEvaluationObserver = null;
  87076. }
  87077. },
  87078. enumerable: true,
  87079. configurable: true
  87080. });
  87081. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87082. /**
  87083. * Gets the perf counter used for render targets render time
  87084. */
  87085. get: function () {
  87086. return this._renderTargetsRenderTime;
  87087. },
  87088. enumerable: true,
  87089. configurable: true
  87090. });
  87091. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87092. /**
  87093. * Gets the render targets render time capture status
  87094. */
  87095. get: function () {
  87096. return this._captureRenderTargetsRenderTime;
  87097. },
  87098. /**
  87099. * Enable or disable the render targets render time capture
  87100. */
  87101. set: function (value) {
  87102. var _this = this;
  87103. if (value === this._captureRenderTargetsRenderTime) {
  87104. return;
  87105. }
  87106. this._captureRenderTargetsRenderTime = value;
  87107. if (value) {
  87108. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87109. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87110. _this._renderTargetsRenderTime.beginMonitoring();
  87111. });
  87112. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87113. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87114. _this._renderTargetsRenderTime.endMonitoring(false);
  87115. });
  87116. }
  87117. else {
  87118. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87119. this._onBeforeRenderTargetsRenderObserver = null;
  87120. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87121. this._onAfterRenderTargetsRenderObserver = null;
  87122. }
  87123. },
  87124. enumerable: true,
  87125. configurable: true
  87126. });
  87127. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87128. /**
  87129. * Gets the perf counter used for particles render time
  87130. */
  87131. get: function () {
  87132. return this._particlesRenderTime;
  87133. },
  87134. enumerable: true,
  87135. configurable: true
  87136. });
  87137. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87138. /**
  87139. * Gets the particles render time capture status
  87140. */
  87141. get: function () {
  87142. return this._captureParticlesRenderTime;
  87143. },
  87144. /**
  87145. * Enable or disable the particles render time capture
  87146. */
  87147. set: function (value) {
  87148. var _this = this;
  87149. if (value === this._captureParticlesRenderTime) {
  87150. return;
  87151. }
  87152. this._captureParticlesRenderTime = value;
  87153. if (value) {
  87154. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87155. BABYLON.Tools.StartPerformanceCounter("Particles");
  87156. _this._particlesRenderTime.beginMonitoring();
  87157. });
  87158. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87159. BABYLON.Tools.EndPerformanceCounter("Particles");
  87160. _this._particlesRenderTime.endMonitoring(false);
  87161. });
  87162. }
  87163. else {
  87164. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87165. this._onBeforeParticlesRenderingObserver = null;
  87166. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87167. this._onAfterParticlesRenderingObserver = null;
  87168. }
  87169. },
  87170. enumerable: true,
  87171. configurable: true
  87172. });
  87173. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87174. /**
  87175. * Gets the perf counter used for sprites render time
  87176. */
  87177. get: function () {
  87178. return this._spritesRenderTime;
  87179. },
  87180. enumerable: true,
  87181. configurable: true
  87182. });
  87183. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87184. /**
  87185. * Gets the sprites render time capture status
  87186. */
  87187. get: function () {
  87188. return this._captureSpritesRenderTime;
  87189. },
  87190. /**
  87191. * Enable or disable the sprites render time capture
  87192. */
  87193. set: function (value) {
  87194. var _this = this;
  87195. if (value === this._captureSpritesRenderTime) {
  87196. return;
  87197. }
  87198. this._captureSpritesRenderTime = value;
  87199. if (value) {
  87200. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87201. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87202. _this._spritesRenderTime.beginMonitoring();
  87203. });
  87204. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87205. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87206. _this._spritesRenderTime.endMonitoring(false);
  87207. });
  87208. }
  87209. else {
  87210. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87211. this._onBeforeSpritesRenderingObserver = null;
  87212. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87213. this._onAfterSpritesRenderingObserver = null;
  87214. }
  87215. },
  87216. enumerable: true,
  87217. configurable: true
  87218. });
  87219. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87220. /**
  87221. * Gets the perf counter used for physics time
  87222. */
  87223. get: function () {
  87224. return this._physicsTime;
  87225. },
  87226. enumerable: true,
  87227. configurable: true
  87228. });
  87229. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87230. /**
  87231. * Gets the physics time capture status
  87232. */
  87233. get: function () {
  87234. return this._capturePhysicsTime;
  87235. },
  87236. /**
  87237. * Enable or disable the physics time capture
  87238. */
  87239. set: function (value) {
  87240. var _this = this;
  87241. if (value === this._capturePhysicsTime) {
  87242. return;
  87243. }
  87244. this._capturePhysicsTime = value;
  87245. if (value) {
  87246. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87247. BABYLON.Tools.StartPerformanceCounter("Physics");
  87248. _this._physicsTime.beginMonitoring();
  87249. });
  87250. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87251. BABYLON.Tools.EndPerformanceCounter("Physics");
  87252. _this._physicsTime.endMonitoring();
  87253. });
  87254. }
  87255. else {
  87256. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87257. this._onBeforePhysicsObserver = null;
  87258. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87259. this._onAfterPhysicsObserver = null;
  87260. }
  87261. },
  87262. enumerable: true,
  87263. configurable: true
  87264. });
  87265. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87266. /**
  87267. * Gets the perf counter used for animations time
  87268. */
  87269. get: function () {
  87270. return this._animationsTime;
  87271. },
  87272. enumerable: true,
  87273. configurable: true
  87274. });
  87275. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87276. /**
  87277. * Gets the animations time capture status
  87278. */
  87279. get: function () {
  87280. return this._captureAnimationsTime;
  87281. },
  87282. /**
  87283. * Enable or disable the animations time capture
  87284. */
  87285. set: function (value) {
  87286. var _this = this;
  87287. if (value === this._captureAnimationsTime) {
  87288. return;
  87289. }
  87290. this._captureAnimationsTime = value;
  87291. if (value) {
  87292. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87293. _this._animationsTime.endMonitoring();
  87294. });
  87295. }
  87296. else {
  87297. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87298. this._onAfterAnimationsObserver = null;
  87299. }
  87300. },
  87301. enumerable: true,
  87302. configurable: true
  87303. });
  87304. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87305. /**
  87306. * Gets the perf counter used for frame time capture
  87307. */
  87308. get: function () {
  87309. return this._frameTime;
  87310. },
  87311. enumerable: true,
  87312. configurable: true
  87313. });
  87314. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87315. /**
  87316. * Gets the frame time capture status
  87317. */
  87318. get: function () {
  87319. return this._captureFrameTime;
  87320. },
  87321. /**
  87322. * Enable or disable the frame time capture
  87323. */
  87324. set: function (value) {
  87325. this._captureFrameTime = value;
  87326. },
  87327. enumerable: true,
  87328. configurable: true
  87329. });
  87330. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87331. /**
  87332. * Gets the perf counter used for inter-frames time capture
  87333. */
  87334. get: function () {
  87335. return this._interFrameTime;
  87336. },
  87337. enumerable: true,
  87338. configurable: true
  87339. });
  87340. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87341. /**
  87342. * Gets the inter-frames time capture status
  87343. */
  87344. get: function () {
  87345. return this._captureInterFrameTime;
  87346. },
  87347. /**
  87348. * Enable or disable the inter-frames time capture
  87349. */
  87350. set: function (value) {
  87351. this._captureInterFrameTime = value;
  87352. },
  87353. enumerable: true,
  87354. configurable: true
  87355. });
  87356. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87357. /**
  87358. * Gets the perf counter used for render time capture
  87359. */
  87360. get: function () {
  87361. return this._renderTime;
  87362. },
  87363. enumerable: true,
  87364. configurable: true
  87365. });
  87366. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87367. /**
  87368. * Gets the render time capture status
  87369. */
  87370. get: function () {
  87371. return this._captureRenderTime;
  87372. },
  87373. /**
  87374. * Enable or disable the render time capture
  87375. */
  87376. set: function (value) {
  87377. var _this = this;
  87378. if (value === this._captureRenderTime) {
  87379. return;
  87380. }
  87381. this._captureRenderTime = value;
  87382. if (value) {
  87383. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87384. _this._renderTime.beginMonitoring();
  87385. BABYLON.Tools.StartPerformanceCounter("Main render");
  87386. });
  87387. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87388. _this._renderTime.endMonitoring(false);
  87389. BABYLON.Tools.EndPerformanceCounter("Main render");
  87390. });
  87391. }
  87392. else {
  87393. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87394. this._onBeforeDrawPhaseObserver = null;
  87395. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87396. this._onAfterDrawPhaseObserver = null;
  87397. }
  87398. },
  87399. enumerable: true,
  87400. configurable: true
  87401. });
  87402. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87403. /**
  87404. * Gets the perf counter used for draw calls
  87405. */
  87406. get: function () {
  87407. return this.scene.getEngine()._drawCalls;
  87408. },
  87409. enumerable: true,
  87410. configurable: true
  87411. });
  87412. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87413. /**
  87414. * Gets the perf counter used for texture collisions
  87415. */
  87416. get: function () {
  87417. return this.scene.getEngine()._textureCollisions;
  87418. },
  87419. enumerable: true,
  87420. configurable: true
  87421. });
  87422. SceneInstrumentation.prototype.dispose = function () {
  87423. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87424. this._onAfterRenderObserver = null;
  87425. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87426. this._onBeforeActiveMeshesEvaluationObserver = null;
  87427. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87428. this._onAfterActiveMeshesEvaluationObserver = null;
  87429. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87430. this._onBeforeRenderTargetsRenderObserver = null;
  87431. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87432. this._onAfterRenderTargetsRenderObserver = null;
  87433. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87434. this._onBeforeAnimationsObserver = null;
  87435. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87436. this._onBeforeParticlesRenderingObserver = null;
  87437. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87438. this._onAfterParticlesRenderingObserver = null;
  87439. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87440. this._onBeforeSpritesRenderingObserver = null;
  87441. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87442. this._onAfterSpritesRenderingObserver = null;
  87443. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87444. this._onBeforeDrawPhaseObserver = null;
  87445. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87446. this._onAfterDrawPhaseObserver = null;
  87447. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87448. this._onBeforePhysicsObserver = null;
  87449. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87450. this._onAfterPhysicsObserver = null;
  87451. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87452. this._onAfterAnimationsObserver = null;
  87453. this.scene = null;
  87454. };
  87455. return SceneInstrumentation;
  87456. }());
  87457. BABYLON.SceneInstrumentation = SceneInstrumentation;
  87458. })(BABYLON || (BABYLON = {}));
  87459. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  87460. var BABYLON;
  87461. (function (BABYLON) {
  87462. var _TimeToken = /** @class */ (function () {
  87463. function _TimeToken() {
  87464. this._timeElapsedQueryEnded = false;
  87465. }
  87466. return _TimeToken;
  87467. }());
  87468. BABYLON._TimeToken = _TimeToken;
  87469. })(BABYLON || (BABYLON = {}));
  87470. //# sourceMappingURL=babylon.timeToken.js.map
  87471. var BABYLON;
  87472. (function (BABYLON) {
  87473. /**
  87474. * Background material defines definition.
  87475. * @ignore Mainly internal Use
  87476. */
  87477. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  87478. __extends(BackgroundMaterialDefines, _super);
  87479. /**
  87480. * Constructor of the defines.
  87481. */
  87482. function BackgroundMaterialDefines() {
  87483. var _this = _super.call(this) || this;
  87484. /**
  87485. * True if the diffuse texture is in use.
  87486. */
  87487. _this.DIFFUSE = false;
  87488. /**
  87489. * The direct UV channel to use.
  87490. */
  87491. _this.DIFFUSEDIRECTUV = 0;
  87492. /**
  87493. * True if the diffuse texture is in gamma space.
  87494. */
  87495. _this.GAMMADIFFUSE = false;
  87496. /**
  87497. * True if the diffuse texture has opacity in the alpha channel.
  87498. */
  87499. _this.DIFFUSEHASALPHA = false;
  87500. /**
  87501. * True if you want the material to fade to transparent at grazing angle.
  87502. */
  87503. _this.OPACITYFRESNEL = false;
  87504. /**
  87505. * True if an extra blur needs to be added in the reflection.
  87506. */
  87507. _this.REFLECTIONBLUR = false;
  87508. /**
  87509. * True if you want the material to fade to reflection at grazing angle.
  87510. */
  87511. _this.REFLECTIONFRESNEL = false;
  87512. /**
  87513. * True if you want the material to falloff as far as you move away from the scene center.
  87514. */
  87515. _this.REFLECTIONFALLOFF = false;
  87516. /**
  87517. * False if the current Webgl implementation does not support the texture lod extension.
  87518. */
  87519. _this.TEXTURELODSUPPORT = false;
  87520. /**
  87521. * True to ensure the data are premultiplied.
  87522. */
  87523. _this.PREMULTIPLYALPHA = false;
  87524. /**
  87525. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  87526. */
  87527. _this.USERGBCOLOR = false;
  87528. /**
  87529. * True to add noise in order to reduce the banding effect.
  87530. */
  87531. _this.NOISE = false;
  87532. // Image Processing Configuration.
  87533. _this.IMAGEPROCESSING = false;
  87534. _this.VIGNETTE = false;
  87535. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87536. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87537. _this.TONEMAPPING = false;
  87538. _this.CONTRAST = false;
  87539. _this.COLORCURVES = false;
  87540. _this.COLORGRADING = false;
  87541. _this.COLORGRADING3D = false;
  87542. _this.SAMPLER3DGREENDEPTH = false;
  87543. _this.SAMPLER3DBGRMAP = false;
  87544. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87545. _this.EXPOSURE = false;
  87546. // Reflection.
  87547. _this.REFLECTION = false;
  87548. _this.REFLECTIONMAP_3D = false;
  87549. _this.REFLECTIONMAP_SPHERICAL = false;
  87550. _this.REFLECTIONMAP_PLANAR = false;
  87551. _this.REFLECTIONMAP_CUBIC = false;
  87552. _this.REFLECTIONMAP_PROJECTION = false;
  87553. _this.REFLECTIONMAP_SKYBOX = false;
  87554. _this.REFLECTIONMAP_EXPLICIT = false;
  87555. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  87556. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  87557. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  87558. _this.INVERTCUBICMAP = false;
  87559. _this.REFLECTIONMAP_OPPOSITEZ = false;
  87560. _this.LODINREFLECTIONALPHA = false;
  87561. _this.GAMMAREFLECTION = false;
  87562. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  87563. // Default BJS.
  87564. _this.MAINUV1 = false;
  87565. _this.MAINUV2 = false;
  87566. _this.UV1 = false;
  87567. _this.UV2 = false;
  87568. _this.CLIPPLANE = false;
  87569. _this.POINTSIZE = false;
  87570. _this.FOG = false;
  87571. _this.NORMAL = false;
  87572. _this.NUM_BONE_INFLUENCERS = 0;
  87573. _this.BonesPerMesh = 0;
  87574. _this.INSTANCES = false;
  87575. _this.SHADOWFLOAT = false;
  87576. _this.rebuild();
  87577. return _this;
  87578. }
  87579. return BackgroundMaterialDefines;
  87580. }(BABYLON.MaterialDefines));
  87581. /**
  87582. * Background material used to create an efficient environement around your scene.
  87583. */
  87584. var BackgroundMaterial = /** @class */ (function (_super) {
  87585. __extends(BackgroundMaterial, _super);
  87586. /**
  87587. * Instantiates a Background Material in the given scene
  87588. * @param name The friendly name of the material
  87589. * @param scene The scene to add the material to
  87590. */
  87591. function BackgroundMaterial(name, scene) {
  87592. var _this = _super.call(this, name, scene) || this;
  87593. /**
  87594. * Key light Color (multiply against the R channel of the environement texture)
  87595. */
  87596. _this.primaryColor = BABYLON.Color3.White();
  87597. /**
  87598. * Key light Level (allowing HDR output of the background)
  87599. */
  87600. _this.primaryLevel = 1;
  87601. /**
  87602. * Secondary light Color (multiply against the G channel of the environement texture)
  87603. */
  87604. _this.secondaryColor = BABYLON.Color3.Gray();
  87605. /**
  87606. * Secondary light Level (allowing HDR output of the background)
  87607. */
  87608. _this.secondaryLevel = 1;
  87609. /**
  87610. * Tertiary light Color (multiply against the B channel of the environement texture)
  87611. */
  87612. _this.tertiaryColor = BABYLON.Color3.Black();
  87613. /**
  87614. * Tertiary light Level (allowing HDR output of the background)
  87615. */
  87616. _this.tertiaryLevel = 1;
  87617. /**
  87618. * Reflection Texture used in the material.
  87619. * Should be author in a specific way for the best result (refer to the documentation).
  87620. */
  87621. _this.reflectionTexture = null;
  87622. /**
  87623. * Reflection Texture level of blur.
  87624. *
  87625. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  87626. * texture twice.
  87627. */
  87628. _this.reflectionBlur = 0;
  87629. /**
  87630. * Diffuse Texture used in the material.
  87631. * Should be author in a specific way for the best result (refer to the documentation).
  87632. */
  87633. _this.diffuseTexture = null;
  87634. _this._shadowLights = null;
  87635. /**
  87636. * Specify the list of lights casting shadow on the material.
  87637. * All scene shadow lights will be included if null.
  87638. */
  87639. _this.shadowLights = null;
  87640. /**
  87641. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  87642. * soft lighting on the background.
  87643. */
  87644. _this.shadowBlurScale = 1;
  87645. /**
  87646. * Helps adjusting the shadow to a softer level if required.
  87647. * 0 means black shadows and 1 means no shadows.
  87648. */
  87649. _this.shadowLevel = 0;
  87650. /**
  87651. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  87652. * It is usually zero but might be interesting to modify according to your setup.
  87653. */
  87654. _this.sceneCenter = BABYLON.Vector3.Zero();
  87655. /**
  87656. * This helps specifying that the material is falling off to the sky box at grazing angle.
  87657. * This helps ensuring a nice transition when the camera goes under the ground.
  87658. */
  87659. _this.opacityFresnel = true;
  87660. /**
  87661. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  87662. * This helps adding a mirror texture on the ground.
  87663. */
  87664. _this.reflectionFresnel = false;
  87665. /**
  87666. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  87667. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  87668. */
  87669. _this.reflectionFalloffDistance = 0.0;
  87670. /**
  87671. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  87672. */
  87673. _this.reflectionAmount = 1.0;
  87674. /**
  87675. * This specifies the weight of the reflection at grazing angle.
  87676. */
  87677. _this.reflectionReflectance0 = 0.05;
  87678. /**
  87679. * This specifies the weight of the reflection at a perpendicular point of view.
  87680. */
  87681. _this.reflectionReflectance90 = 0.5;
  87682. /**
  87683. * Helps to directly use the maps channels instead of their level.
  87684. */
  87685. _this.useRGBColor = true;
  87686. /**
  87687. * This helps reducing the banding effect that could occur on the background.
  87688. */
  87689. _this.enableNoise = false;
  87690. _this._fovMultiplier = 1.0;
  87691. /**
  87692. * Enable the FOV adjustment feature controlled by fovMultiplier.
  87693. * @type {boolean}
  87694. */
  87695. _this.useEquirectangularFOV = false;
  87696. _this._maxSimultaneousLights = 4;
  87697. /**
  87698. * Number of Simultaneous lights allowed on the material.
  87699. */
  87700. _this.maxSimultaneousLights = 4;
  87701. /**
  87702. * Keep track of the image processing observer to allow dispose and replace.
  87703. */
  87704. _this._imageProcessingObserver = null;
  87705. // Temp values kept as cache in the material.
  87706. _this._renderTargets = new BABYLON.SmartArray(16);
  87707. _this._reflectionControls = BABYLON.Vector4.Zero();
  87708. // Setup the default processing configuration to the scene.
  87709. _this._attachImageProcessingConfiguration(null);
  87710. _this.getRenderTargetTextures = function () {
  87711. _this._renderTargets.reset();
  87712. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  87713. _this._renderTargets.push(_this._diffuseTexture);
  87714. }
  87715. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  87716. _this._renderTargets.push(_this._reflectionTexture);
  87717. }
  87718. return _this._renderTargets;
  87719. };
  87720. return _this;
  87721. }
  87722. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  87723. /**
  87724. * Sets the reflection reflectance fresnel values according to the default standard
  87725. * empirically know to work well :-)
  87726. */
  87727. set: function (value) {
  87728. var reflectionWeight = value;
  87729. if (reflectionWeight < 0.5) {
  87730. reflectionWeight = reflectionWeight * 2.0;
  87731. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  87732. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  87733. }
  87734. else {
  87735. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  87736. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  87737. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  87738. }
  87739. },
  87740. enumerable: true,
  87741. configurable: true
  87742. });
  87743. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  87744. /**
  87745. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  87746. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  87747. * Recommended to be keep at 1.0 except for special cases.
  87748. */
  87749. get: function () {
  87750. return this._fovMultiplier;
  87751. },
  87752. set: function (value) {
  87753. if (isNaN(value)) {
  87754. value = 1.0;
  87755. }
  87756. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  87757. },
  87758. enumerable: true,
  87759. configurable: true
  87760. });
  87761. /**
  87762. * Attaches a new image processing configuration to the PBR Material.
  87763. * @param configuration (if null the scene configuration will be use)
  87764. */
  87765. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  87766. var _this = this;
  87767. if (configuration === this._imageProcessingConfiguration) {
  87768. return;
  87769. }
  87770. // Detaches observer.
  87771. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  87772. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  87773. }
  87774. // Pick the scene configuration if needed.
  87775. if (!configuration) {
  87776. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  87777. }
  87778. else {
  87779. this._imageProcessingConfiguration = configuration;
  87780. }
  87781. // Attaches observer.
  87782. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  87783. _this._markAllSubMeshesAsImageProcessingDirty();
  87784. });
  87785. };
  87786. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  87787. /**
  87788. * Gets the image processing configuration used either in this material.
  87789. */
  87790. get: function () {
  87791. return this._imageProcessingConfiguration;
  87792. },
  87793. /**
  87794. * Sets the Default image processing configuration used either in the this material.
  87795. *
  87796. * If sets to null, the scene one is in use.
  87797. */
  87798. set: function (value) {
  87799. this._attachImageProcessingConfiguration(value);
  87800. // Ensure the effect will be rebuilt.
  87801. this._markAllSubMeshesAsTexturesDirty();
  87802. },
  87803. enumerable: true,
  87804. configurable: true
  87805. });
  87806. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  87807. /**
  87808. * Gets wether the color curves effect is enabled.
  87809. */
  87810. get: function () {
  87811. return this.imageProcessingConfiguration.colorCurvesEnabled;
  87812. },
  87813. /**
  87814. * Sets wether the color curves effect is enabled.
  87815. */
  87816. set: function (value) {
  87817. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  87818. },
  87819. enumerable: true,
  87820. configurable: true
  87821. });
  87822. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  87823. /**
  87824. * Gets wether the color grading effect is enabled.
  87825. */
  87826. get: function () {
  87827. return this.imageProcessingConfiguration.colorGradingEnabled;
  87828. },
  87829. /**
  87830. * Gets wether the color grading effect is enabled.
  87831. */
  87832. set: function (value) {
  87833. this.imageProcessingConfiguration.colorGradingEnabled = value;
  87834. },
  87835. enumerable: true,
  87836. configurable: true
  87837. });
  87838. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  87839. /**
  87840. * Gets wether tonemapping is enabled or not.
  87841. */
  87842. get: function () {
  87843. return this._imageProcessingConfiguration.toneMappingEnabled;
  87844. },
  87845. /**
  87846. * Sets wether tonemapping is enabled or not
  87847. */
  87848. set: function (value) {
  87849. this._imageProcessingConfiguration.toneMappingEnabled = value;
  87850. },
  87851. enumerable: true,
  87852. configurable: true
  87853. });
  87854. ;
  87855. ;
  87856. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  87857. /**
  87858. * The camera exposure used on this material.
  87859. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87860. * This corresponds to a photographic exposure.
  87861. */
  87862. get: function () {
  87863. return this._imageProcessingConfiguration.exposure;
  87864. },
  87865. /**
  87866. * The camera exposure used on this material.
  87867. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  87868. * This corresponds to a photographic exposure.
  87869. */
  87870. set: function (value) {
  87871. this._imageProcessingConfiguration.exposure = value;
  87872. },
  87873. enumerable: true,
  87874. configurable: true
  87875. });
  87876. ;
  87877. ;
  87878. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  87879. /**
  87880. * Gets The camera contrast used on this material.
  87881. */
  87882. get: function () {
  87883. return this._imageProcessingConfiguration.contrast;
  87884. },
  87885. /**
  87886. * Sets The camera contrast used on this material.
  87887. */
  87888. set: function (value) {
  87889. this._imageProcessingConfiguration.contrast = value;
  87890. },
  87891. enumerable: true,
  87892. configurable: true
  87893. });
  87894. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  87895. /**
  87896. * Gets the Color Grading 2D Lookup Texture.
  87897. */
  87898. get: function () {
  87899. return this._imageProcessingConfiguration.colorGradingTexture;
  87900. },
  87901. /**
  87902. * Sets the Color Grading 2D Lookup Texture.
  87903. */
  87904. set: function (value) {
  87905. this.imageProcessingConfiguration.colorGradingTexture = value;
  87906. },
  87907. enumerable: true,
  87908. configurable: true
  87909. });
  87910. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  87911. /**
  87912. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87913. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87914. * 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;
  87915. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87916. */
  87917. get: function () {
  87918. return this.imageProcessingConfiguration.colorCurves;
  87919. },
  87920. /**
  87921. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  87922. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  87923. * 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;
  87924. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  87925. */
  87926. set: function (value) {
  87927. this.imageProcessingConfiguration.colorCurves = value;
  87928. },
  87929. enumerable: true,
  87930. configurable: true
  87931. });
  87932. /**
  87933. * The entire material has been created in order to prevent overdraw.
  87934. * @returns false
  87935. */
  87936. BackgroundMaterial.prototype.needAlphaTesting = function () {
  87937. return true;
  87938. };
  87939. /**
  87940. * The entire material has been created in order to prevent overdraw.
  87941. * @returns true if blending is enable
  87942. */
  87943. BackgroundMaterial.prototype.needAlphaBlending = function () {
  87944. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  87945. };
  87946. /**
  87947. * Checks wether the material is ready to be rendered for a given mesh.
  87948. * @param mesh The mesh to render
  87949. * @param subMesh The submesh to check against
  87950. * @param useInstances Specify wether or not the material is used with instances
  87951. * @returns true if all the dependencies are ready (Textures, Effects...)
  87952. */
  87953. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  87954. var _this = this;
  87955. if (useInstances === void 0) { useInstances = false; }
  87956. if (subMesh.effect && this.isFrozen) {
  87957. if (this._wasPreviouslyReady) {
  87958. return true;
  87959. }
  87960. }
  87961. if (!subMesh._materialDefines) {
  87962. subMesh._materialDefines = new BackgroundMaterialDefines();
  87963. }
  87964. var scene = this.getScene();
  87965. var defines = subMesh._materialDefines;
  87966. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  87967. if (defines._renderId === scene.getRenderId()) {
  87968. return true;
  87969. }
  87970. }
  87971. var engine = scene.getEngine();
  87972. // Lights
  87973. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  87974. defines._needNormals = true;
  87975. // Textures
  87976. if (defines._areTexturesDirty) {
  87977. defines._needUVs = false;
  87978. if (scene.texturesEnabled) {
  87979. if (scene.getEngine().getCaps().textureLOD) {
  87980. defines.TEXTURELODSUPPORT = true;
  87981. }
  87982. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  87983. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  87984. return false;
  87985. }
  87986. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  87987. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  87988. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  87989. defines.OPACITYFRESNEL = this._opacityFresnel;
  87990. }
  87991. else {
  87992. defines.DIFFUSE = false;
  87993. defines.DIFFUSEHASALPHA = false;
  87994. defines.GAMMADIFFUSE = false;
  87995. defines.OPACITYFRESNEL = false;
  87996. }
  87997. var reflectionTexture = this._reflectionTexture;
  87998. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  87999. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88000. return false;
  88001. }
  88002. defines.REFLECTION = true;
  88003. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88004. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88005. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88006. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88007. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88008. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88009. defines.INVERTCUBICMAP = true;
  88010. }
  88011. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88012. switch (reflectionTexture.coordinatesMode) {
  88013. case BABYLON.Texture.CUBIC_MODE:
  88014. case BABYLON.Texture.INVCUBIC_MODE:
  88015. defines.REFLECTIONMAP_CUBIC = true;
  88016. break;
  88017. case BABYLON.Texture.EXPLICIT_MODE:
  88018. defines.REFLECTIONMAP_EXPLICIT = true;
  88019. break;
  88020. case BABYLON.Texture.PLANAR_MODE:
  88021. defines.REFLECTIONMAP_PLANAR = true;
  88022. break;
  88023. case BABYLON.Texture.PROJECTION_MODE:
  88024. defines.REFLECTIONMAP_PROJECTION = true;
  88025. break;
  88026. case BABYLON.Texture.SKYBOX_MODE:
  88027. defines.REFLECTIONMAP_SKYBOX = true;
  88028. break;
  88029. case BABYLON.Texture.SPHERICAL_MODE:
  88030. defines.REFLECTIONMAP_SPHERICAL = true;
  88031. break;
  88032. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88033. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88034. break;
  88035. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88036. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88037. break;
  88038. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88039. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88040. break;
  88041. }
  88042. if (this.reflectionFresnel) {
  88043. defines.REFLECTIONFRESNEL = true;
  88044. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88045. this._reflectionControls.x = this.reflectionAmount;
  88046. this._reflectionControls.y = this.reflectionReflectance0;
  88047. this._reflectionControls.z = this.reflectionReflectance90;
  88048. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88049. }
  88050. else {
  88051. defines.REFLECTIONFRESNEL = false;
  88052. defines.REFLECTIONFALLOFF = false;
  88053. }
  88054. }
  88055. else {
  88056. defines.REFLECTION = false;
  88057. defines.REFLECTIONFALLOFF = false;
  88058. defines.REFLECTIONBLUR = false;
  88059. defines.REFLECTIONMAP_3D = false;
  88060. defines.REFLECTIONMAP_SPHERICAL = false;
  88061. defines.REFLECTIONMAP_PLANAR = false;
  88062. defines.REFLECTIONMAP_CUBIC = false;
  88063. defines.REFLECTIONMAP_PROJECTION = false;
  88064. defines.REFLECTIONMAP_SKYBOX = false;
  88065. defines.REFLECTIONMAP_EXPLICIT = false;
  88066. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88067. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88068. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88069. defines.INVERTCUBICMAP = false;
  88070. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88071. defines.LODINREFLECTIONALPHA = false;
  88072. defines.GAMMAREFLECTION = false;
  88073. }
  88074. }
  88075. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88076. defines.USERGBCOLOR = this._useRGBColor;
  88077. defines.NOISE = this._enableNoise;
  88078. }
  88079. if (defines._areImageProcessingDirty) {
  88080. if (!this._imageProcessingConfiguration.isReady()) {
  88081. return false;
  88082. }
  88083. this._imageProcessingConfiguration.prepareDefines(defines);
  88084. }
  88085. // Misc.
  88086. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88087. // Values that need to be evaluated on every frame
  88088. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88089. // Attribs
  88090. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88091. if (mesh) {
  88092. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88093. mesh.createNormals(true);
  88094. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88095. }
  88096. }
  88097. }
  88098. // Get correct effect
  88099. if (defines.isDirty) {
  88100. defines.markAsProcessed();
  88101. scene.resetCachedMaterial();
  88102. // Fallbacks
  88103. var fallbacks = new BABYLON.EffectFallbacks();
  88104. if (defines.FOG) {
  88105. fallbacks.addFallback(0, "FOG");
  88106. }
  88107. if (defines.POINTSIZE) {
  88108. fallbacks.addFallback(1, "POINTSIZE");
  88109. }
  88110. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88111. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88112. fallbacks.addCPUSkinningFallback(0, mesh);
  88113. }
  88114. //Attributes
  88115. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88116. if (defines.NORMAL) {
  88117. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88118. }
  88119. if (defines.UV1) {
  88120. attribs.push(BABYLON.VertexBuffer.UVKind);
  88121. }
  88122. if (defines.UV2) {
  88123. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88124. }
  88125. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88126. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88127. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88128. "vFogInfos", "vFogColor", "pointSize",
  88129. "vClipPlane", "mBones",
  88130. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88131. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88132. "shadowLevel", "alpha",
  88133. "vBackgroundCenter", "vReflectionControl",
  88134. "vDiffuseInfos", "diffuseMatrix",
  88135. ];
  88136. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88137. var uniformBuffers = ["Material", "Scene"];
  88138. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88139. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88140. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88141. uniformsNames: uniforms,
  88142. uniformBuffersNames: uniformBuffers,
  88143. samplers: samplers,
  88144. defines: defines,
  88145. maxSimultaneousLights: this._maxSimultaneousLights
  88146. });
  88147. var onCompiled = function (effect) {
  88148. if (_this.onCompiled) {
  88149. _this.onCompiled(effect);
  88150. }
  88151. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88152. };
  88153. var join = defines.toString();
  88154. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88155. attributes: attribs,
  88156. uniformsNames: uniforms,
  88157. uniformBuffersNames: uniformBuffers,
  88158. samplers: samplers,
  88159. defines: join,
  88160. fallbacks: fallbacks,
  88161. onCompiled: onCompiled,
  88162. onError: this.onError,
  88163. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88164. }, engine), defines);
  88165. this.buildUniformLayout();
  88166. }
  88167. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88168. return false;
  88169. }
  88170. defines._renderId = scene.getRenderId();
  88171. this._wasPreviouslyReady = true;
  88172. return true;
  88173. };
  88174. /**
  88175. * Build the uniform buffer used in the material.
  88176. */
  88177. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88178. // Order is important !
  88179. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88180. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88181. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88182. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88183. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88184. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88185. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88186. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88187. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88188. this._uniformBuffer.addUniform("pointSize", 1);
  88189. this._uniformBuffer.addUniform("shadowLevel", 1);
  88190. this._uniformBuffer.addUniform("alpha", 1);
  88191. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88192. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88193. this._uniformBuffer.create();
  88194. };
  88195. /**
  88196. * Unbind the material.
  88197. */
  88198. BackgroundMaterial.prototype.unbind = function () {
  88199. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88200. this._uniformBuffer.setTexture("diffuseSampler", null);
  88201. }
  88202. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88203. this._uniformBuffer.setTexture("reflectionSampler", null);
  88204. }
  88205. _super.prototype.unbind.call(this);
  88206. };
  88207. /**
  88208. * Bind only the world matrix to the material.
  88209. * @param world The world matrix to bind.
  88210. */
  88211. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88212. this._activeEffect.setMatrix("world", world);
  88213. };
  88214. /**
  88215. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88216. * @param world The world matrix to bind.
  88217. * @param subMesh The submesh to bind for.
  88218. */
  88219. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88220. var scene = this.getScene();
  88221. var defines = subMesh._materialDefines;
  88222. if (!defines) {
  88223. return;
  88224. }
  88225. var effect = subMesh.effect;
  88226. if (!effect) {
  88227. return;
  88228. }
  88229. this._activeEffect = effect;
  88230. // Matrices
  88231. this.bindOnlyWorldMatrix(world);
  88232. // Bones
  88233. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88234. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88235. if (mustRebind) {
  88236. this._uniformBuffer.bindToEffect(effect, "Material");
  88237. this.bindViewProjection(effect);
  88238. var reflectionTexture = this._reflectionTexture;
  88239. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88240. // Texture uniforms
  88241. if (scene.texturesEnabled) {
  88242. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88243. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88244. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88245. }
  88246. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88247. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88248. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88249. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88250. }
  88251. }
  88252. if (this.shadowLevel > 0) {
  88253. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88254. }
  88255. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88256. // Point size
  88257. if (this.pointsCloud) {
  88258. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88259. }
  88260. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88261. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88262. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88263. }
  88264. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88265. // Textures
  88266. if (scene.texturesEnabled) {
  88267. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88268. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88269. }
  88270. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88271. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88272. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88273. }
  88274. else if (!defines.REFLECTIONBLUR) {
  88275. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88276. }
  88277. else {
  88278. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88279. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88280. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88281. }
  88282. if (defines.REFLECTIONFRESNEL) {
  88283. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88284. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88285. }
  88286. }
  88287. }
  88288. // Clip plane
  88289. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88290. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88291. }
  88292. if (mustRebind || !this.isFrozen) {
  88293. if (scene.lightsEnabled) {
  88294. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88295. }
  88296. // View
  88297. this.bindView(effect);
  88298. // Fog
  88299. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88300. // image processing
  88301. this._imageProcessingConfiguration.bind(this._activeEffect);
  88302. }
  88303. this._uniformBuffer.update();
  88304. this._afterBind(mesh);
  88305. };
  88306. /**
  88307. * Dispose the material.
  88308. * @param forceDisposeEffect Force disposal of the associated effect.
  88309. * @param forceDisposeTextures Force disposal of the associated textures.
  88310. */
  88311. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88312. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88313. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88314. if (forceDisposeTextures) {
  88315. if (this.diffuseTexture) {
  88316. this.diffuseTexture.dispose();
  88317. }
  88318. if (this.reflectionTexture) {
  88319. this.reflectionTexture.dispose();
  88320. }
  88321. }
  88322. this._renderTargets.dispose();
  88323. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88324. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88325. }
  88326. _super.prototype.dispose.call(this, forceDisposeEffect);
  88327. };
  88328. /**
  88329. * Clones the material.
  88330. * @param name The cloned name.
  88331. * @returns The cloned material.
  88332. */
  88333. BackgroundMaterial.prototype.clone = function (name) {
  88334. var _this = this;
  88335. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88336. };
  88337. /**
  88338. * Serializes the current material to its JSON representation.
  88339. * @returns The JSON representation.
  88340. */
  88341. BackgroundMaterial.prototype.serialize = function () {
  88342. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88343. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88344. return serializationObject;
  88345. };
  88346. /**
  88347. * Gets the class name of the material
  88348. * @returns "BackgroundMaterial"
  88349. */
  88350. BackgroundMaterial.prototype.getClassName = function () {
  88351. return "BackgroundMaterial";
  88352. };
  88353. /**
  88354. * Parse a JSON input to create back a background material.
  88355. * @param source The JSON data to parse
  88356. * @param scene The scene to create the parsed material in
  88357. * @param rootUrl The root url of the assets the material depends upon
  88358. * @returns the instantiated BackgroundMaterial.
  88359. */
  88360. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88361. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88362. };
  88363. /**
  88364. * Standard reflectance value at parallel view angle.
  88365. */
  88366. BackgroundMaterial.StandardReflectance0 = 0.05;
  88367. /**
  88368. * Standard reflectance value at grazing angle.
  88369. */
  88370. BackgroundMaterial.StandardReflectance90 = 0.5;
  88371. __decorate([
  88372. BABYLON.serializeAsColor3()
  88373. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88374. __decorate([
  88375. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88376. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88377. __decorate([
  88378. BABYLON.serialize()
  88379. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88380. __decorate([
  88381. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88382. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88383. __decorate([
  88384. BABYLON.serializeAsColor3()
  88385. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88386. __decorate([
  88387. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88388. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88389. __decorate([
  88390. BABYLON.serialize()
  88391. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88392. __decorate([
  88393. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88394. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88395. __decorate([
  88396. BABYLON.serializeAsColor3()
  88397. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88398. __decorate([
  88399. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88400. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88401. __decorate([
  88402. BABYLON.serialize()
  88403. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88404. __decorate([
  88405. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88406. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88407. __decorate([
  88408. BABYLON.serializeAsTexture()
  88409. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88410. __decorate([
  88411. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88412. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88413. __decorate([
  88414. BABYLON.serialize()
  88415. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88416. __decorate([
  88417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88418. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88419. __decorate([
  88420. BABYLON.serializeAsTexture()
  88421. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88422. __decorate([
  88423. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88424. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88425. __decorate([
  88426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88427. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88428. __decorate([
  88429. BABYLON.serialize()
  88430. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88431. __decorate([
  88432. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88433. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88434. __decorate([
  88435. BABYLON.serialize()
  88436. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88437. __decorate([
  88438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88439. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88440. __decorate([
  88441. BABYLON.serializeAsVector3()
  88442. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88443. __decorate([
  88444. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88445. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88446. __decorate([
  88447. BABYLON.serialize()
  88448. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  88449. __decorate([
  88450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88451. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  88452. __decorate([
  88453. BABYLON.serialize()
  88454. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  88455. __decorate([
  88456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88457. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  88458. __decorate([
  88459. BABYLON.serialize()
  88460. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  88461. __decorate([
  88462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88463. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  88464. __decorate([
  88465. BABYLON.serialize()
  88466. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  88467. __decorate([
  88468. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88469. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  88470. __decorate([
  88471. BABYLON.serialize()
  88472. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  88473. __decorate([
  88474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88475. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  88476. __decorate([
  88477. BABYLON.serialize()
  88478. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  88479. __decorate([
  88480. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88481. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  88482. __decorate([
  88483. BABYLON.serialize()
  88484. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  88485. __decorate([
  88486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88487. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  88488. __decorate([
  88489. BABYLON.serialize()
  88490. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  88491. __decorate([
  88492. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88493. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  88494. __decorate([
  88495. BABYLON.serialize()
  88496. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  88497. __decorate([
  88498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88499. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  88500. __decorate([
  88501. BABYLON.serializeAsImageProcessingConfiguration()
  88502. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  88503. return BackgroundMaterial;
  88504. }(BABYLON.PushMaterial));
  88505. BABYLON.BackgroundMaterial = BackgroundMaterial;
  88506. })(BABYLON || (BABYLON = {}));
  88507. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  88508. var __assign = (this && this.__assign) || Object.assign || function(t) {
  88509. for (var s, i = 1, n = arguments.length; i < n; i++) {
  88510. s = arguments[i];
  88511. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  88512. t[p] = s[p];
  88513. }
  88514. return t;
  88515. };
  88516. var BABYLON;
  88517. (function (BABYLON) {
  88518. /**
  88519. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  88520. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  88521. * It also helps with the default setup of your imageProcessing configuration.
  88522. */
  88523. var EnvironmentHelper = /** @class */ (function () {
  88524. /**
  88525. * constructor
  88526. * @param options
  88527. * @param scene The scene to add the material to
  88528. */
  88529. function EnvironmentHelper(options, scene) {
  88530. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  88531. this._scene = scene;
  88532. this._setupBackground();
  88533. this._setupImageProcessing();
  88534. }
  88535. /**
  88536. * Creates the default options for the helper.
  88537. */
  88538. EnvironmentHelper._getDefaultOptions = function () {
  88539. return {
  88540. createGround: true,
  88541. groundSize: 15,
  88542. groundTexture: this._groundTextureCDNUrl,
  88543. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88544. groundOpacity: 0.9,
  88545. enableGroundShadow: true,
  88546. groundShadowLevel: 0.5,
  88547. enableGroundMirror: false,
  88548. groundMirrorSizeRatio: 0.3,
  88549. groundMirrorBlurKernel: 64,
  88550. groundMirrorAmount: 1,
  88551. groundMirrorFresnelWeight: 1,
  88552. groundMirrorFallOffDistance: 0,
  88553. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  88554. groundYBias: 0.00001,
  88555. createSkybox: true,
  88556. skyboxSize: 20,
  88557. skyboxTexture: this._skyboxTextureCDNUrl,
  88558. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  88559. backgroundYRotation: 0,
  88560. sizeAuto: true,
  88561. rootPosition: BABYLON.Vector3.Zero(),
  88562. setupImageProcessing: true,
  88563. environmentTexture: this._environmentTextureCDNUrl,
  88564. cameraExposure: 0.8,
  88565. cameraContrast: 1.2,
  88566. toneMappingEnabled: true,
  88567. };
  88568. };
  88569. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  88570. /**
  88571. * Gets the root mesh created by the helper.
  88572. */
  88573. get: function () {
  88574. return this._rootMesh;
  88575. },
  88576. enumerable: true,
  88577. configurable: true
  88578. });
  88579. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  88580. /**
  88581. * Gets the skybox created by the helper.
  88582. */
  88583. get: function () {
  88584. return this._skybox;
  88585. },
  88586. enumerable: true,
  88587. configurable: true
  88588. });
  88589. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  88590. /**
  88591. * Gets the skybox texture created by the helper.
  88592. */
  88593. get: function () {
  88594. return this._skyboxTexture;
  88595. },
  88596. enumerable: true,
  88597. configurable: true
  88598. });
  88599. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  88600. /**
  88601. * Gets the skybox material created by the helper.
  88602. */
  88603. get: function () {
  88604. return this._skyboxMaterial;
  88605. },
  88606. enumerable: true,
  88607. configurable: true
  88608. });
  88609. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  88610. /**
  88611. * Gets the ground mesh created by the helper.
  88612. */
  88613. get: function () {
  88614. return this._ground;
  88615. },
  88616. enumerable: true,
  88617. configurable: true
  88618. });
  88619. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  88620. /**
  88621. * Gets the ground texture created by the helper.
  88622. */
  88623. get: function () {
  88624. return this._groundTexture;
  88625. },
  88626. enumerable: true,
  88627. configurable: true
  88628. });
  88629. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  88630. /**
  88631. * Gets the ground mirror created by the helper.
  88632. */
  88633. get: function () {
  88634. return this._groundMirror;
  88635. },
  88636. enumerable: true,
  88637. configurable: true
  88638. });
  88639. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  88640. /**
  88641. * Gets the ground mirror render list to helps pushing the meshes
  88642. * you wish in the ground reflection.
  88643. */
  88644. get: function () {
  88645. if (this._groundMirror) {
  88646. return this._groundMirror.renderList;
  88647. }
  88648. return null;
  88649. },
  88650. enumerable: true,
  88651. configurable: true
  88652. });
  88653. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  88654. /**
  88655. * Gets the ground material created by the helper.
  88656. */
  88657. get: function () {
  88658. return this._groundMaterial;
  88659. },
  88660. enumerable: true,
  88661. configurable: true
  88662. });
  88663. /**
  88664. * Updates the background according to the new options
  88665. * @param options
  88666. */
  88667. EnvironmentHelper.prototype.updateOptions = function (options) {
  88668. var newOptions = __assign({}, this._options, options);
  88669. if (this._ground && !newOptions.createGround) {
  88670. this._ground.dispose();
  88671. this._ground = null;
  88672. }
  88673. if (this._groundMaterial && !newOptions.createGround) {
  88674. this._groundMaterial.dispose();
  88675. this._groundMaterial = null;
  88676. }
  88677. if (this._groundTexture) {
  88678. if (this._options.groundTexture != newOptions.groundTexture) {
  88679. this._groundTexture.dispose();
  88680. this._groundTexture = null;
  88681. }
  88682. }
  88683. if (this._skybox && !newOptions.createSkybox) {
  88684. this._skybox.dispose();
  88685. this._skybox = null;
  88686. }
  88687. if (this._skyboxMaterial && !newOptions.createSkybox) {
  88688. this._skyboxMaterial.dispose();
  88689. this._skyboxMaterial = null;
  88690. }
  88691. if (this._skyboxTexture) {
  88692. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  88693. this._skyboxTexture.dispose();
  88694. this._skyboxTexture = null;
  88695. }
  88696. }
  88697. if (this._groundMirror && !newOptions.enableGroundMirror) {
  88698. this._groundMirror.dispose();
  88699. this._groundMirror = null;
  88700. }
  88701. if (this._scene.environmentTexture) {
  88702. if (this._options.environmentTexture != newOptions.environmentTexture) {
  88703. this._scene.environmentTexture.dispose();
  88704. }
  88705. }
  88706. this._options = newOptions;
  88707. this._setupBackground();
  88708. this._setupImageProcessing();
  88709. };
  88710. /**
  88711. * Sets the primary color of all the available elements.
  88712. * @param color
  88713. */
  88714. EnvironmentHelper.prototype.setMainColor = function (color) {
  88715. if (this.groundMaterial) {
  88716. this.groundMaterial.primaryColor = color;
  88717. }
  88718. if (this.skyboxMaterial) {
  88719. this.skyboxMaterial.primaryColor = color;
  88720. }
  88721. if (this.groundMirror) {
  88722. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  88723. }
  88724. };
  88725. /**
  88726. * Setup the image processing according to the specified options.
  88727. */
  88728. EnvironmentHelper.prototype._setupImageProcessing = function () {
  88729. if (this._options.setupImageProcessing) {
  88730. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  88731. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  88732. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  88733. this._setupEnvironmentTexture();
  88734. }
  88735. };
  88736. /**
  88737. * Setup the environment texture according to the specified options.
  88738. */
  88739. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  88740. if (this._scene.environmentTexture) {
  88741. return;
  88742. }
  88743. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  88744. this._scene.environmentTexture = this._options.environmentTexture;
  88745. return;
  88746. }
  88747. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  88748. this._scene.environmentTexture = environmentTexture;
  88749. };
  88750. /**
  88751. * Setup the background according to the specified options.
  88752. */
  88753. EnvironmentHelper.prototype._setupBackground = function () {
  88754. if (!this._rootMesh) {
  88755. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  88756. }
  88757. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  88758. var sceneSize = this._getSceneSize();
  88759. if (this._options.createGround) {
  88760. this._setupGround(sceneSize);
  88761. this._setupGroundMaterial();
  88762. this._setupGroundDiffuseTexture();
  88763. if (this._options.enableGroundMirror) {
  88764. this._setupGroundMirrorTexture(sceneSize);
  88765. }
  88766. this._setupMirrorInGroundMaterial();
  88767. }
  88768. if (this._options.createSkybox) {
  88769. this._setupSkybox(sceneSize);
  88770. this._setupSkyboxMaterial();
  88771. this._setupSkyboxReflectionTexture();
  88772. }
  88773. this._rootMesh.position.x = sceneSize.rootPosition.x;
  88774. this._rootMesh.position.z = sceneSize.rootPosition.z;
  88775. this._rootMesh.position.y = sceneSize.rootPosition.y;
  88776. };
  88777. /**
  88778. * Get the scene sizes according to the setup.
  88779. */
  88780. EnvironmentHelper.prototype._getSceneSize = function () {
  88781. var groundSize = this._options.groundSize;
  88782. var skyboxSize = this._options.skyboxSize;
  88783. var rootPosition = this._options.rootPosition;
  88784. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  88785. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88786. }
  88787. var sceneExtends = this._scene.getWorldExtends();
  88788. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  88789. if (this._options.sizeAuto) {
  88790. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  88791. this._scene.activeCamera.upperRadiusLimit) {
  88792. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  88793. skyboxSize = groundSize;
  88794. }
  88795. var sceneDiagonalLenght = sceneDiagonal.length();
  88796. if (sceneDiagonalLenght > groundSize) {
  88797. groundSize = sceneDiagonalLenght * 2;
  88798. skyboxSize = groundSize;
  88799. }
  88800. // 10 % bigger.
  88801. groundSize *= 1.1;
  88802. skyboxSize *= 1.5;
  88803. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  88804. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  88805. }
  88806. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  88807. };
  88808. /**
  88809. * Setup the ground according to the specified options.
  88810. */
  88811. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  88812. var _this = this;
  88813. if (!this._ground) {
  88814. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  88815. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  88816. this._ground.parent = this._rootMesh;
  88817. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  88818. }
  88819. this._ground.receiveShadows = this._options.enableGroundShadow;
  88820. };
  88821. /**
  88822. * Setup the ground material according to the specified options.
  88823. */
  88824. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  88825. if (!this._groundMaterial) {
  88826. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  88827. }
  88828. this._groundMaterial.alpha = this._options.groundOpacity;
  88829. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  88830. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  88831. this._groundMaterial.primaryLevel = 1;
  88832. this._groundMaterial.primaryColor = this._options.groundColor;
  88833. this._groundMaterial.secondaryLevel = 0;
  88834. this._groundMaterial.tertiaryLevel = 0;
  88835. this._groundMaterial.useRGBColor = false;
  88836. this._groundMaterial.enableNoise = true;
  88837. if (this._ground) {
  88838. this._ground.material = this._groundMaterial;
  88839. }
  88840. };
  88841. /**
  88842. * Setup the ground diffuse texture according to the specified options.
  88843. */
  88844. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  88845. if (!this._groundMaterial) {
  88846. return;
  88847. }
  88848. if (this._groundTexture) {
  88849. return;
  88850. }
  88851. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  88852. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  88853. return;
  88854. }
  88855. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  88856. diffuseTexture.gammaSpace = false;
  88857. diffuseTexture.hasAlpha = true;
  88858. this._groundMaterial.diffuseTexture = diffuseTexture;
  88859. };
  88860. /**
  88861. * Setup the ground mirror texture according to the specified options.
  88862. */
  88863. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  88864. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88865. if (!this._groundMirror) {
  88866. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  88867. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  88868. this._groundMirror.anisotropicFilteringLevel = 1;
  88869. this._groundMirror.wrapU = wrapping;
  88870. this._groundMirror.wrapV = wrapping;
  88871. this._groundMirror.gammaSpace = false;
  88872. if (this._groundMirror.renderList) {
  88873. for (var i = 0; i < this._scene.meshes.length; i++) {
  88874. var mesh = this._scene.meshes[i];
  88875. if (mesh !== this._ground &&
  88876. mesh !== this._skybox &&
  88877. mesh !== this._rootMesh) {
  88878. this._groundMirror.renderList.push(mesh);
  88879. }
  88880. }
  88881. }
  88882. }
  88883. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  88884. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  88885. };
  88886. /**
  88887. * Setup the ground to receive the mirror texture.
  88888. */
  88889. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  88890. if (this._groundMaterial) {
  88891. this._groundMaterial.reflectionTexture = this._groundMirror;
  88892. this._groundMaterial.reflectionFresnel = true;
  88893. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  88894. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  88895. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  88896. }
  88897. };
  88898. /**
  88899. * Setup the skybox according to the specified options.
  88900. */
  88901. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  88902. var _this = this;
  88903. if (!this._skybox) {
  88904. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  88905. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  88906. }
  88907. this._skybox.parent = this._rootMesh;
  88908. };
  88909. /**
  88910. * Setup the skybox material according to the specified options.
  88911. */
  88912. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  88913. if (!this._skybox) {
  88914. return;
  88915. }
  88916. if (!this._skyboxMaterial) {
  88917. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  88918. }
  88919. this._skyboxMaterial.useRGBColor = false;
  88920. this._skyboxMaterial.primaryLevel = 1;
  88921. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  88922. this._skyboxMaterial.secondaryLevel = 0;
  88923. this._skyboxMaterial.tertiaryLevel = 0;
  88924. this._skyboxMaterial.enableNoise = true;
  88925. this._skybox.material = this._skyboxMaterial;
  88926. };
  88927. /**
  88928. * Setup the skybox reflection texture according to the specified options.
  88929. */
  88930. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  88931. if (!this._skyboxMaterial) {
  88932. return;
  88933. }
  88934. if (this._skyboxTexture) {
  88935. return;
  88936. }
  88937. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  88938. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88939. return;
  88940. }
  88941. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  88942. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  88943. this._skyboxTexture.gammaSpace = false;
  88944. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  88945. };
  88946. /**
  88947. * Dispose all the elements created by the Helper.
  88948. */
  88949. EnvironmentHelper.prototype.dispose = function () {
  88950. if (this._groundMaterial) {
  88951. this._groundMaterial.dispose(true, true);
  88952. }
  88953. if (this._skyboxMaterial) {
  88954. this._skyboxMaterial.dispose(true, true);
  88955. }
  88956. this._rootMesh.dispose(false);
  88957. };
  88958. /**
  88959. * Default ground texture URL.
  88960. */
  88961. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  88962. /**
  88963. * Default skybox texture URL.
  88964. */
  88965. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  88966. /**
  88967. * Default environment texture URL.
  88968. */
  88969. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  88970. return EnvironmentHelper;
  88971. }());
  88972. BABYLON.EnvironmentHelper = EnvironmentHelper;
  88973. })(BABYLON || (BABYLON = {}));
  88974. //# sourceMappingURL=babylon.environmentHelper.js.map
  88975. var BABYLON;
  88976. (function (BABYLON) {
  88977. /**
  88978. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  88979. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  88980. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  88981. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  88982. */
  88983. var VideoDome = /** @class */ (function (_super) {
  88984. __extends(VideoDome, _super);
  88985. /**
  88986. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  88987. * @param name Element's name, child elements will append suffixes for their own names.
  88988. * @param urlsOrVideo
  88989. * @param options An object containing optional or exposed sub element properties:
  88990. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  88991. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  88992. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  88993. * @param options **loop=true** Automatically loop video on end.
  88994. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  88995. */
  88996. function VideoDome(name, urlsOrVideo, options, scene) {
  88997. var _this = _super.call(this, name, scene) || this;
  88998. // set defaults and manage values
  88999. name = name || "videoDome";
  89000. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  89001. options.clickToPlay = Boolean(options.clickToPlay);
  89002. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  89003. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  89004. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  89005. // create
  89006. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  89007. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  89008. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  89009. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  89010. flat: false,
  89011. radius: options.size,
  89012. subdivisions: options.resolution,
  89013. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  89014. }, scene);
  89015. // configure material
  89016. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  89017. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  89018. material.reflectionTexture = _this._videoTexture;
  89019. material.useEquirectangularFOV = true;
  89020. material.fovMultiplier = 1.0;
  89021. // configure mesh
  89022. _this._mesh.material = material;
  89023. _this._mesh.parent = _this;
  89024. // optional configuration
  89025. if (options.clickToPlay) {
  89026. scene.onPointerUp = function () {
  89027. _this._videoTexture.video.play();
  89028. };
  89029. }
  89030. return _this;
  89031. }
  89032. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  89033. /**
  89034. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89035. * Also see the options.resolution property.
  89036. */
  89037. get: function () {
  89038. return this._material.fovMultiplier;
  89039. },
  89040. set: function (value) {
  89041. this._material.fovMultiplier = value;
  89042. },
  89043. enumerable: true,
  89044. configurable: true
  89045. });
  89046. return VideoDome;
  89047. }(BABYLON.Node));
  89048. BABYLON.VideoDome = VideoDome;
  89049. })(BABYLON || (BABYLON = {}));
  89050. //# sourceMappingURL=babylon.videoDome.js.map
  89051. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\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 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>\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#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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\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>\nvoid main(void) {\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\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\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#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\ngl_FragColor=color;\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;\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,1.0));\n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\nvoid main() {\noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\nuniform float currentCount;\nuniform float timeDelta;\nuniform float generalRandom;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\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}\nvoid main() {\nif (age>=life) {\n\noutPosition=(emitterWM*vec4(0.,0.,0.,1.)).xyz;\n\nvec3 randoms=getRandomVec3(generalRandom);\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\noutDirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n} else { \noutPosition=position+(direction+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\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 screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\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}","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","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","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\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\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}","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\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#ifdef NOISE\ncolor.rgb=dither(vPositionW.xy,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  89052. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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","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}","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","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};","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};"};
  89053. (function universalModuleDefinition(root, factory) {
  89054. var f = factory();
  89055. if (root && root["BABYLON"]) {
  89056. return;
  89057. }
  89058. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  89059. globalObject["BABYLON"] = f;
  89060. if(true)
  89061. module.exports = f;
  89062. else if(typeof define === 'function' && define.amd)
  89063. define(["BABYLON"], factory);
  89064. else if(typeof exports === 'object')
  89065. exports["BABYLON"] = f;
  89066. else {
  89067. root["BABYLON"] = f;
  89068. }
  89069. })(this, function() {
  89070. return BABYLON;
  89071. });
  89072. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  89073. /***/ }),
  89074. /* 1 */
  89075. /***/ (function(module, exports, __webpack_require__) {
  89076. "use strict";
  89077. Object.defineProperty(exports, "__esModule", { value: true });
  89078. var babylonjs_1 = __webpack_require__(0);
  89079. var helper_1 = __webpack_require__(3);
  89080. var HTMLMapper = (function () {
  89081. function HTMLMapper() {
  89082. }
  89083. HTMLMapper.prototype.map = function (element) {
  89084. var config = {};
  89085. var _loop_1 = function (attrIdx) {
  89086. var attr = element.attributes.item(attrIdx);
  89087. var split = attr.nodeName.split('.');
  89088. split.reduce(function (currentConfig, key, idx) {
  89089. var camelKey = helper_1.kebabToCamel(key);
  89090. if (idx === split.length - 1) {
  89091. var val = attr.nodeValue;
  89092. if (val === "true") {
  89093. val = true;
  89094. }
  89095. else if (val === "false") {
  89096. val = false;
  89097. }
  89098. else {
  89099. var number = parseFloat(val);
  89100. if (!isNaN(number)) {
  89101. val = number;
  89102. }
  89103. }
  89104. currentConfig[camelKey] = val;
  89105. }
  89106. else {
  89107. currentConfig[camelKey] = currentConfig[camelKey] || {};
  89108. }
  89109. return currentConfig[camelKey];
  89110. }, config);
  89111. };
  89112. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  89113. _loop_1(attrIdx);
  89114. }
  89115. return config;
  89116. };
  89117. return HTMLMapper;
  89118. }());
  89119. var JSONMapper = (function () {
  89120. function JSONMapper() {
  89121. }
  89122. JSONMapper.prototype.map = function (rawSource) {
  89123. return JSON.parse(rawSource);
  89124. };
  89125. return JSONMapper;
  89126. }());
  89127. var DOMMapper = (function () {
  89128. function DOMMapper() {
  89129. }
  89130. DOMMapper.prototype.map = function (baseElement) {
  89131. var htmlMapper = new HTMLMapper();
  89132. var config = htmlMapper.map(baseElement);
  89133. var traverseChildren = function (element, partConfig) {
  89134. var children = element.children;
  89135. if (children.length) {
  89136. for (var i = 0; i < children.length; ++i) {
  89137. var item = children.item(i);
  89138. var configMapped = htmlMapper.map(item);
  89139. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  89140. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  89141. partConfig[key] = [];
  89142. }
  89143. else {
  89144. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  89145. partConfig.push(configMapped);
  89146. }
  89147. else if (partConfig[key]) {
  89148. element.setAttribute('array', 'true');
  89149. var oldItem = partConfig[key];
  89150. partConfig = [oldItem, configMapped];
  89151. }
  89152. else {
  89153. partConfig[key] = configMapped;
  89154. }
  89155. }
  89156. traverseChildren(item, partConfig[key] || configMapped);
  89157. }
  89158. }
  89159. return partConfig;
  89160. };
  89161. traverseChildren(baseElement, config);
  89162. return config;
  89163. };
  89164. return DOMMapper;
  89165. }());
  89166. var MapperManager = (function () {
  89167. function MapperManager() {
  89168. this.mappers = {
  89169. "html": new HTMLMapper(),
  89170. "json": new JSONMapper(),
  89171. "dom": new DOMMapper()
  89172. };
  89173. }
  89174. MapperManager.prototype.getMapper = function (type) {
  89175. if (!this.mappers[type]) {
  89176. babylonjs_1.Tools.Error("No mapper defined for " + type);
  89177. }
  89178. return this.mappers[type] || this.mappers[MapperManager.DefaultMapper];
  89179. };
  89180. MapperManager.prototype.registerMapper = function (type, mapper) {
  89181. this.mappers[type] = mapper;
  89182. };
  89183. MapperManager.DefaultMapper = 'json';
  89184. return MapperManager;
  89185. }());
  89186. exports.MapperManager = MapperManager;
  89187. exports.mapperManager = new MapperManager();
  89188. /***/ }),
  89189. /* 2 */
  89190. /***/ (function(module, exports) {
  89191. var g;
  89192. // This works in non-strict mode
  89193. g = (function() {
  89194. return this;
  89195. })();
  89196. try {
  89197. // This works if eval is allowed (see CSP)
  89198. g = g || Function("return this")() || (1,eval)("this");
  89199. } catch(e) {
  89200. // This works if the window reference is available
  89201. if(typeof window === "object")
  89202. g = window;
  89203. }
  89204. // g can still be undefined, but nothing to do about it...
  89205. // We return undefined, instead of nothing here, so it's
  89206. // easier to handle this case. if(!global) { ...}
  89207. module.exports = g;
  89208. /***/ }),
  89209. /* 3 */
  89210. /***/ (function(module, exports, __webpack_require__) {
  89211. "use strict";
  89212. Object.defineProperty(exports, "__esModule", { value: true });
  89213. function isUrl(urlToCheck) {
  89214. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  89215. return true;
  89216. }
  89217. return false;
  89218. }
  89219. exports.isUrl = isUrl;
  89220. function loadFile(url) {
  89221. return new Promise(function (resolve, reject) {
  89222. var xhr = new XMLHttpRequest();
  89223. xhr.open('GET', url);
  89224. xhr.send();
  89225. xhr.onreadystatechange = function () {
  89226. var DONE = 4;
  89227. var OK = 200;
  89228. if (xhr.readyState === DONE) {
  89229. if (xhr.status === OK) {
  89230. resolve(xhr.responseText);
  89231. }
  89232. }
  89233. else {
  89234. console.log('Error: ' + xhr.status, url);
  89235. reject('Error: ' + xhr.status);
  89236. }
  89237. };
  89238. });
  89239. }
  89240. exports.loadFile = loadFile;
  89241. function kebabToCamel(s) {
  89242. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  89243. }
  89244. exports.kebabToCamel = kebabToCamel;
  89245. function camelToKebab(str) {
  89246. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  89247. }
  89248. exports.camelToKebab = camelToKebab;
  89249. /***/ }),
  89250. /* 4 */
  89251. /***/ (function(module, exports, __webpack_require__) {
  89252. "use strict";
  89253. Object.defineProperty(exports, "__esModule", { value: true });
  89254. var babylonjs_1 = __webpack_require__(0);
  89255. var ViewerManager = (function () {
  89256. function ViewerManager() {
  89257. this.viewers = {};
  89258. this.onViewerAddedObservable = new babylonjs_1.Observable();
  89259. }
  89260. ViewerManager.prototype.addViewer = function (viewer) {
  89261. this.viewers[viewer.getBaseId()] = viewer;
  89262. this._onViewerAdded(viewer);
  89263. };
  89264. ViewerManager.prototype.getViewerById = function (id) {
  89265. return this.viewers[id];
  89266. };
  89267. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  89268. for (var id in this.viewers) {
  89269. if (this.viewers[id].containerElement === element) {
  89270. return this.getViewerById(id);
  89271. }
  89272. }
  89273. };
  89274. ViewerManager.prototype.getViewerPromiseById = function (id) {
  89275. var _this = this;
  89276. return new Promise(function (resolve, reject) {
  89277. var localViewer = _this.getViewerById(id);
  89278. if (localViewer) {
  89279. return resolve(localViewer);
  89280. }
  89281. var viewerFunction = function (viewer) {
  89282. if (viewer.getBaseId() === id) {
  89283. resolve(viewer);
  89284. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  89285. }
  89286. };
  89287. _this.onViewerAddedObservable.add(viewerFunction);
  89288. });
  89289. };
  89290. ViewerManager.prototype._onViewerAdded = function (viewer) {
  89291. this.onViewerAdded && this.onViewerAdded(viewer);
  89292. this.onViewerAddedObservable.notifyObservers(viewer);
  89293. };
  89294. return ViewerManager;
  89295. }());
  89296. exports.ViewerManager = ViewerManager;
  89297. exports.viewerManager = new ViewerManager();
  89298. /***/ }),
  89299. /* 5 */
  89300. /***/ (function(module, exports, __webpack_require__) {
  89301. "use strict";
  89302. var __extends = (this && this.__extends) || (function () {
  89303. var extendStatics = Object.setPrototypeOf ||
  89304. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  89305. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  89306. return function (d, b) {
  89307. extendStatics(d, b);
  89308. function __() { this.constructor = d; }
  89309. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  89310. };
  89311. })();
  89312. Object.defineProperty(exports, "__esModule", { value: true });
  89313. var viewer_1 = __webpack_require__(6);
  89314. var babylonjs_1 = __webpack_require__(0);
  89315. var DefaultViewer = (function (_super) {
  89316. __extends(DefaultViewer, _super);
  89317. function DefaultViewer(containerElement, initialConfiguration) {
  89318. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  89319. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  89320. _this.containerElement = containerElement;
  89321. _this.onModelLoaded = function (meshes) {
  89322. var hideLoadingDelay = 500;
  89323. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  89324. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  89325. }
  89326. setTimeout(function () {
  89327. _this.hideLoadingScreen();
  89328. }, hideLoadingDelay);
  89329. meshes[0].rotation.y += Math.PI;
  89330. return;
  89331. };
  89332. _this.onModelLoadedObservable.add(_this.onModelLoaded);
  89333. return _this;
  89334. }
  89335. DefaultViewer.prototype.initScene = function () {
  89336. var _this = this;
  89337. return _super.prototype.initScene.call(this).then(function () {
  89338. _this.extendClassWithConfig(_this.scene, _this.configuration.scene);
  89339. return _this.scene;
  89340. });
  89341. };
  89342. DefaultViewer.prototype.onTemplatesLoaded = function () {
  89343. var _this = this;
  89344. this.showLoadingScreen();
  89345. this.initNavbar();
  89346. var closeButton = document.getElementById('close-button');
  89347. if (closeButton) {
  89348. closeButton.addEventListener('pointerdown', function () {
  89349. _this.hideOverlayScreen();
  89350. });
  89351. }
  89352. return _super.prototype.onTemplatesLoaded.call(this);
  89353. };
  89354. DefaultViewer.prototype.initNavbar = function () {
  89355. var navbar = this.templateManager.getTemplate('navBar');
  89356. if (navbar) {
  89357. var navbarHeight_1 = navbar.parent.clientHeight + 'px';
  89358. var navbarShown_1 = true;
  89359. var timeoutCancel_1;
  89360. var triggerNavbar = function (show, evt) {
  89361. if (show === void 0) { show = false; }
  89362. if (!navbar || evt.button > 0)
  89363. return;
  89364. timeoutCancel_1 && clearTimeout(timeoutCancel_1);
  89365. if (show === navbarShown_1)
  89366. return;
  89367. if (show) {
  89368. navbar.parent.style.bottom = show ? '0px' : '-' + navbarHeight_1;
  89369. navbarShown_1 = show;
  89370. }
  89371. else {
  89372. var visibilityTimeout = 2000;
  89373. if (navbar.configuration.params && navbar.configuration.params.visibilityTimeout !== undefined) {
  89374. visibilityTimeout = navbar.configuration.params.visibilityTimeout;
  89375. }
  89376. timeoutCancel_1 = setTimeout(function () {
  89377. if (navbar) {
  89378. navbar.parent.style.bottom = '-' + navbarHeight_1;
  89379. }
  89380. navbarShown_1 = show;
  89381. }, visibilityTimeout);
  89382. }
  89383. };
  89384. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerout');
  89385. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, true), 'pointerdown');
  89386. this.templateManager.eventManager.registerCallback('viewer', triggerNavbar.bind(this, false), 'pointerup');
  89387. this.templateManager.eventManager.registerCallback('navBar', triggerNavbar.bind(this, true), 'pointerover');
  89388. var viewerTemplate = this.templateManager.getTemplate('viewer');
  89389. var viewerElement_1 = viewerTemplate && viewerTemplate.parent;
  89390. var triggerFullscren = function (eventData) {
  89391. if (viewerElement_1) {
  89392. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  89393. if (!fullscreenElement) {
  89394. var requestFullScreen = viewerElement_1.requestFullscreen || viewerElement_1.webkitRequestFullscreen || viewerElement_1.msRequestFullscreen || viewerElement_1.mozRequestFullScreen;
  89395. requestFullScreen.call(viewerElement_1);
  89396. }
  89397. else {
  89398. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  89399. exitFullscreen.call(document);
  89400. }
  89401. }
  89402. };
  89403. this.templateManager.eventManager.registerCallback('navBar', triggerFullscren, 'pointerdown', '#fullscreen-button');
  89404. }
  89405. };
  89406. DefaultViewer.prototype.prepareContainerElement = function () {
  89407. this.containerElement.style.position = 'relative';
  89408. this.containerElement.style.display = 'flex';
  89409. };
  89410. DefaultViewer.prototype.configureModel = function (modelConfiguration) {
  89411. _super.prototype.configureModel.call(this, modelConfiguration);
  89412. var navbar = this.templateManager.getTemplate('navBar');
  89413. if (!navbar)
  89414. return;
  89415. var metadataContainer = navbar.parent.querySelector('#model-metadata');
  89416. if (metadataContainer) {
  89417. if (modelConfiguration.title !== undefined) {
  89418. var element = metadataContainer.querySelector('span.model-title');
  89419. if (element) {
  89420. element.innerHTML = modelConfiguration.title;
  89421. }
  89422. }
  89423. if (modelConfiguration.subtitle !== undefined) {
  89424. var element = metadataContainer.querySelector('span.model-subtitle');
  89425. if (element) {
  89426. element.innerHTML = modelConfiguration.subtitle;
  89427. }
  89428. }
  89429. if (modelConfiguration.thumbnail !== undefined) {
  89430. metadataContainer.querySelector('.thumbnail').style.backgroundImage = "url('" + modelConfiguration.thumbnail + "')";
  89431. }
  89432. }
  89433. };
  89434. DefaultViewer.prototype.loadModel = function (model) {
  89435. var _this = this;
  89436. if (model === void 0) { model = this.configuration.model; }
  89437. this.showLoadingScreen();
  89438. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  89439. console.log(error);
  89440. _this.hideLoadingScreen();
  89441. _this.showOverlayScreen('error');
  89442. return _this.scene;
  89443. });
  89444. };
  89445. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  89446. var _this = this;
  89447. var template = this.templateManager.getTemplate('overlay');
  89448. if (!template)
  89449. return Promise.reject('Overlay template not found');
  89450. return template.show((function (template) {
  89451. var canvasRect = _this.containerElement.getBoundingClientRect();
  89452. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  89453. template.parent.style.display = 'flex';
  89454. template.parent.style.width = canvasRect.width + "px";
  89455. template.parent.style.height = canvasRect.height + "px";
  89456. template.parent.style.opacity = "1";
  89457. var subTemplate = _this.templateManager.getTemplate(subScreen);
  89458. if (!subTemplate) {
  89459. return Promise.reject(subScreen + ' template not found');
  89460. }
  89461. return subTemplate.show((function (template) {
  89462. template.parent.style.display = 'flex';
  89463. return Promise.resolve(template);
  89464. }));
  89465. }));
  89466. };
  89467. DefaultViewer.prototype.hideOverlayScreen = function () {
  89468. var template = this.templateManager.getTemplate('overlay');
  89469. if (!template)
  89470. return Promise.reject('Overlay template not found');
  89471. return template.hide((function (template) {
  89472. template.parent.style.opacity = "0";
  89473. var onTransitionEnd = function () {
  89474. template.parent.removeEventListener("transitionend", onTransitionEnd);
  89475. template.parent.style.display = 'none';
  89476. };
  89477. template.parent.addEventListener("transitionend", onTransitionEnd);
  89478. var overlays = template.parent.querySelectorAll('.overlay');
  89479. if (overlays) {
  89480. for (var i = 0; i < overlays.length; ++i) {
  89481. var htmlElement = overlays.item(i);
  89482. htmlElement.style.display = 'none';
  89483. }
  89484. }
  89485. return Promise.resolve(template);
  89486. }));
  89487. };
  89488. DefaultViewer.prototype.showLoadingScreen = function () {
  89489. var _this = this;
  89490. var template = this.templateManager.getTemplate('loadingScreen');
  89491. if (!template)
  89492. return Promise.reject('oading Screen template not found');
  89493. return template.show((function (template) {
  89494. var canvasRect = _this.containerElement.getBoundingClientRect();
  89495. var canvasPositioning = window.getComputedStyle(_this.containerElement).position;
  89496. template.parent.style.display = 'flex';
  89497. template.parent.style.width = canvasRect.width + "px";
  89498. template.parent.style.height = canvasRect.height + "px";
  89499. template.parent.style.opacity = "1";
  89500. template.parent.style.backgroundColor = "black";
  89501. return Promise.resolve(template);
  89502. }));
  89503. };
  89504. DefaultViewer.prototype.hideLoadingScreen = function () {
  89505. var template = this.templateManager.getTemplate('loadingScreen');
  89506. if (!template)
  89507. return Promise.reject('oading Screen template not found');
  89508. return template.hide((function (template) {
  89509. template.parent.style.opacity = "0";
  89510. var onTransitionEnd = function () {
  89511. template.parent.removeEventListener("transitionend", onTransitionEnd);
  89512. template.parent.style.display = 'none';
  89513. };
  89514. template.parent.addEventListener("transitionend", onTransitionEnd);
  89515. return Promise.resolve(template);
  89516. }));
  89517. };
  89518. DefaultViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  89519. var _this = this;
  89520. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  89521. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  89522. _super.prototype.configureLights.call(this, lightsConfiguration, focusMeshes);
  89523. console.log("flashlight", this.configuration.lab);
  89524. if (this.configuration.lab && this.configuration.lab.flashlight) {
  89525. var pointerPosition = BABYLON.Vector3.Zero();
  89526. var lightTarget_1;
  89527. var angle = 0.5;
  89528. var exponent = Math.PI / 2;
  89529. if (typeof this.configuration.lab.flashlight === "object") {
  89530. exponent = this.configuration.lab.flashlight.exponent || exponent;
  89531. angle = this.configuration.lab.flashlight.angle || angle;
  89532. }
  89533. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.scene);
  89534. if (typeof this.configuration.lab.flashlight === "object") {
  89535. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  89536. if (this.configuration.lab.flashlight.diffuse) {
  89537. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  89538. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  89539. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  89540. }
  89541. if (this.configuration.lab.flashlight.specular) {
  89542. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  89543. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  89544. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  89545. }
  89546. }
  89547. this.scene.constantlyUpdateMeshUnderPointer = true;
  89548. this.scene.onPointerObservable.add(function (eventData, eventState) {
  89549. if (eventData.type === 4 && eventData.pickInfo) {
  89550. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  89551. }
  89552. else {
  89553. lightTarget_1 = undefined;
  89554. }
  89555. });
  89556. var updateFlashlightFunction = function () {
  89557. if (_this.camera && flashlight) {
  89558. flashlight.position.copyFrom(_this.camera.position);
  89559. if (lightTarget_1) {
  89560. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  89561. }
  89562. }
  89563. };
  89564. this.scene.registerBeforeRender(updateFlashlightFunction);
  89565. this.registeredOnBeforerenderFunctions.push(updateFlashlightFunction);
  89566. }
  89567. };
  89568. return DefaultViewer;
  89569. }(viewer_1.AbstractViewer));
  89570. exports.DefaultViewer = DefaultViewer;
  89571. /***/ }),
  89572. /* 6 */
  89573. /***/ (function(module, exports, __webpack_require__) {
  89574. "use strict";
  89575. Object.defineProperty(exports, "__esModule", { value: true });
  89576. var viewerManager_1 = __webpack_require__(4);
  89577. var templateManager_1 = __webpack_require__(19);
  89578. var loader_1 = __webpack_require__(22);
  89579. var babylonjs_1 = __webpack_require__(0);
  89580. var deepmerge = __webpack_require__(14);
  89581. var AbstractViewer = (function () {
  89582. function AbstractViewer(containerElement, initialConfiguration) {
  89583. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  89584. var _this = this;
  89585. this.containerElement = containerElement;
  89586. this.resize = function () {
  89587. if (!_this.isCanvasInDOM()) {
  89588. return;
  89589. }
  89590. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  89591. return;
  89592. }
  89593. _this.engine.resize();
  89594. };
  89595. this.render = function () {
  89596. _this.scene && _this.scene.activeCamera && _this.scene.render();
  89597. };
  89598. if (containerElement.id) {
  89599. this.baseId = containerElement.id;
  89600. }
  89601. else {
  89602. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  89603. }
  89604. this.onSceneInitObservable = new babylonjs_1.Observable();
  89605. this.onEngineInitObservable = new babylonjs_1.Observable();
  89606. this.onModelLoadedObservable = new babylonjs_1.Observable();
  89607. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  89608. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  89609. this.onInitDoneObservable = new babylonjs_1.Observable();
  89610. this.onLoaderInitObservable = new babylonjs_1.Observable();
  89611. this.registeredOnBeforerenderFunctions = [];
  89612. viewerManager_1.viewerManager.addViewer(this);
  89613. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  89614. this.prepareContainerElement();
  89615. loader_1.default.loadConfiguration(initialConfiguration, function (configuration) {
  89616. _this.configuration = deepmerge(_this.configuration || {}, configuration);
  89617. if (_this.configuration.observers) {
  89618. _this.configureObservers(_this.configuration.observers);
  89619. }
  89620. var templateConfiguration = _this.configuration.templates || {};
  89621. _this.templateManager.initTemplate(templateConfiguration);
  89622. _this.templateManager.onAllLoaded.add(function () {
  89623. var canvas = _this.templateManager.getCanvas();
  89624. if (canvas) {
  89625. _this.canvas = canvas;
  89626. }
  89627. _this._onTemplateLoaded();
  89628. });
  89629. });
  89630. }
  89631. Object.defineProperty(AbstractViewer.prototype, "isHdrSupported", {
  89632. get: function () {
  89633. return this._hdrSupport;
  89634. },
  89635. enumerable: true,
  89636. configurable: true
  89637. });
  89638. AbstractViewer.prototype.getBaseId = function () {
  89639. return this.baseId;
  89640. };
  89641. AbstractViewer.prototype.isCanvasInDOM = function () {
  89642. return !!this.canvas && !!this.canvas.parentElement;
  89643. };
  89644. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  89645. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  89646. this.configuration = deepmerge(this.configuration || {}, newConfiguration);
  89647. if (newConfiguration.scene) {
  89648. this.configureScene(newConfiguration.scene);
  89649. }
  89650. if (newConfiguration.optimizer) {
  89651. this.configureOptimizer(newConfiguration.optimizer);
  89652. }
  89653. if (newConfiguration.observers) {
  89654. this.configureObservers(newConfiguration.observers);
  89655. }
  89656. if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  89657. this.configureModel(newConfiguration.model);
  89658. }
  89659. if (newConfiguration.lights) {
  89660. this.configureLights(newConfiguration.lights);
  89661. }
  89662. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  89663. this.configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  89664. }
  89665. if (newConfiguration.camera) {
  89666. this.configureCamera(newConfiguration.camera);
  89667. }
  89668. };
  89669. AbstractViewer.prototype.configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  89670. if (!skyboxConifguration && !groundConfiguration) {
  89671. if (this.environmentHelper) {
  89672. this.environmentHelper.dispose();
  89673. delete this.environmentHelper;
  89674. }
  89675. ;
  89676. return Promise.resolve(this.scene);
  89677. }
  89678. var options = {
  89679. createGround: !!groundConfiguration,
  89680. createSkybox: !!skyboxConifguration,
  89681. setupImageProcessing: false
  89682. };
  89683. if (groundConfiguration) {
  89684. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  89685. var groundSize = groundConfig.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  89686. if (groundSize) {
  89687. options.groundSize = groundSize;
  89688. }
  89689. options.enableGroundShadow = groundConfig === true || groundConfig.receiveShadows;
  89690. if (groundConfig.shadowLevel !== undefined) {
  89691. options.groundShadowLevel = groundConfig.shadowLevel;
  89692. }
  89693. options.enableGroundMirror = !!groundConfig.mirror;
  89694. if (groundConfig.texture) {
  89695. options.groundTexture = groundConfig.texture;
  89696. }
  89697. if (groundConfig.color) {
  89698. options.groundColor = new babylonjs_1.Color3(groundConfig.color.r, groundConfig.color.g, groundConfig.color.b);
  89699. }
  89700. if (groundConfig.opacity !== undefined) {
  89701. options.groundOpacity = groundConfig.opacity;
  89702. }
  89703. if (groundConfig.mirror) {
  89704. options.enableGroundMirror = true;
  89705. if (typeof groundConfig.mirror === "object") {
  89706. if (groundConfig.mirror.amount !== undefined)
  89707. options.groundMirrorAmount = groundConfig.mirror.amount;
  89708. if (groundConfig.mirror.sizeRatio !== undefined)
  89709. options.groundMirrorSizeRatio = groundConfig.mirror.sizeRatio;
  89710. if (groundConfig.mirror.blurKernel !== undefined)
  89711. options.groundMirrorBlurKernel = groundConfig.mirror.blurKernel;
  89712. if (groundConfig.mirror.fresnelWeight !== undefined)
  89713. options.groundMirrorFresnelWeight = groundConfig.mirror.fresnelWeight;
  89714. if (groundConfig.mirror.fallOffDistance !== undefined)
  89715. options.groundMirrorFallOffDistance = groundConfig.mirror.fallOffDistance;
  89716. if (this.defaultPipelineTextureType !== undefined)
  89717. options.groundMirrorTextureType = this.defaultPipelineTextureType;
  89718. }
  89719. }
  89720. }
  89721. var postInitSkyboxMaterial = false;
  89722. if (skyboxConifguration) {
  89723. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  89724. if (conf.material && conf.material.imageProcessingConfiguration) {
  89725. options.setupImageProcessing = false;
  89726. }
  89727. var skyboxSize = conf.scale;
  89728. if (skyboxSize) {
  89729. options.skyboxSize = skyboxSize;
  89730. }
  89731. options.sizeAuto = !options.skyboxSize;
  89732. if (conf.color) {
  89733. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  89734. }
  89735. if (conf.cubeTexture && conf.cubeTexture.url) {
  89736. if (typeof conf.cubeTexture.url === "string") {
  89737. options.skyboxTexture = conf.cubeTexture.url;
  89738. }
  89739. else {
  89740. postInitSkyboxMaterial = true;
  89741. }
  89742. }
  89743. if (conf.material && conf.material.imageProcessingConfiguration) {
  89744. postInitSkyboxMaterial = true;
  89745. }
  89746. }
  89747. options.setupImageProcessing = false;
  89748. if (!this.environmentHelper) {
  89749. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  89750. }
  89751. else {
  89752. var scene = this.environmentHelper.rootMesh.getScene();
  89753. if (scene !== this.scene) {
  89754. this.environmentHelper.dispose();
  89755. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  89756. }
  89757. else {
  89758. this.environmentHelper.updateOptions(options);
  89759. }
  89760. }
  89761. if (postInitSkyboxMaterial) {
  89762. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  89763. if (skyboxMaterial) {
  89764. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material && skyboxConifguration.material.imageProcessingConfiguration) {
  89765. this.extendClassWithConfig(skyboxMaterial.imageProcessingConfiguration, skyboxConifguration.material.imageProcessingConfiguration);
  89766. }
  89767. }
  89768. }
  89769. };
  89770. AbstractViewer.prototype.configureScene = function (sceneConfig, optimizerConfig) {
  89771. if (!this.scene) {
  89772. return;
  89773. }
  89774. if (sceneConfig.debug) {
  89775. this.scene.debugLayer.show();
  89776. }
  89777. else {
  89778. if (this.scene.debugLayer.isVisible()) {
  89779. this.scene.debugLayer.hide();
  89780. }
  89781. }
  89782. if (sceneConfig.clearColor) {
  89783. var cc = sceneConfig.clearColor;
  89784. var oldcc = this.scene.clearColor;
  89785. if (cc.r !== undefined) {
  89786. oldcc.r = cc.r;
  89787. }
  89788. if (cc.g !== undefined) {
  89789. oldcc.g = cc.g;
  89790. }
  89791. if (cc.b !== undefined) {
  89792. oldcc.b = cc.b;
  89793. }
  89794. if (cc.a !== undefined) {
  89795. oldcc.a = cc.a;
  89796. }
  89797. }
  89798. if (sceneConfig.imageProcessingConfiguration) {
  89799. this.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  89800. }
  89801. if (sceneConfig.environmentTexture) {
  89802. if (this.scene.environmentTexture) {
  89803. this.scene.environmentTexture.dispose();
  89804. }
  89805. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  89806. this.scene.environmentTexture = environmentTexture;
  89807. }
  89808. if (sceneConfig.autoRotate) {
  89809. this.camera.useAutoRotationBehavior = true;
  89810. }
  89811. };
  89812. AbstractViewer.prototype.configureOptimizer = function (optimizerConfig) {
  89813. if (typeof optimizerConfig === 'boolean') {
  89814. if (this.sceneOptimizer) {
  89815. this.sceneOptimizer.stop();
  89816. this.sceneOptimizer.dispose();
  89817. delete this.sceneOptimizer;
  89818. }
  89819. if (optimizerConfig) {
  89820. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  89821. this.sceneOptimizer.start();
  89822. }
  89823. }
  89824. else {
  89825. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  89826. if (optimizerConfig.degradation) {
  89827. switch (optimizerConfig.degradation) {
  89828. case "low":
  89829. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  89830. break;
  89831. case "moderate":
  89832. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  89833. break;
  89834. case "hight":
  89835. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  89836. break;
  89837. }
  89838. }
  89839. if (this.sceneOptimizer) {
  89840. this.sceneOptimizer.stop();
  89841. this.sceneOptimizer.dispose();
  89842. }
  89843. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  89844. this.sceneOptimizer.start();
  89845. }
  89846. };
  89847. AbstractViewer.prototype.configureObservers = function (observersConfiguration) {
  89848. if (observersConfiguration.onEngineInit) {
  89849. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  89850. }
  89851. else {
  89852. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  89853. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  89854. }
  89855. }
  89856. if (observersConfiguration.onSceneInit) {
  89857. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  89858. }
  89859. else {
  89860. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  89861. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  89862. }
  89863. }
  89864. if (observersConfiguration.onModelLoaded) {
  89865. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  89866. }
  89867. else {
  89868. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  89869. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  89870. }
  89871. }
  89872. };
  89873. AbstractViewer.prototype.configureCamera = function (cameraConfig, focusMeshes) {
  89874. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  89875. if (!this.scene.activeCamera) {
  89876. this.scene.createDefaultCamera(true, true, true);
  89877. this.camera = this.scene.activeCamera;
  89878. }
  89879. if (cameraConfig.position) {
  89880. this.camera.position.copyFromFloats(cameraConfig.position.x || 0, cameraConfig.position.y || 0, cameraConfig.position.z || 0);
  89881. }
  89882. if (cameraConfig.rotation) {
  89883. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  89884. }
  89885. this.extendClassWithConfig(this.camera, cameraConfig);
  89886. this.camera.minZ = cameraConfig.minZ || this.camera.minZ;
  89887. this.camera.maxZ = cameraConfig.maxZ || this.camera.maxZ;
  89888. if (cameraConfig.behaviors) {
  89889. for (var name_1 in cameraConfig.behaviors) {
  89890. this.setCameraBehavior(cameraConfig.behaviors[name_1], focusMeshes);
  89891. }
  89892. }
  89893. ;
  89894. var sceneExtends = this.scene.getWorldExtends();
  89895. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89896. var sceneDiagonalLenght = sceneDiagonal.length();
  89897. if (isFinite(sceneDiagonalLenght))
  89898. this.camera.upperRadiusLimit = sceneDiagonalLenght * 3;
  89899. };
  89900. AbstractViewer.prototype.configureLights = function (lightsConfiguration, focusMeshes) {
  89901. var _this = this;
  89902. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  89903. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  89904. if (!Object.keys(lightsConfiguration).length)
  89905. return;
  89906. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  89907. var lightsToConfigure = Object.keys(this.configuration.lights || []);
  89908. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  89909. lightsAvailable.forEach(function (lName) {
  89910. if (lightsToConfigure.indexOf(lName) === -1) {
  89911. _this.scene.getLightByName(lName).dispose();
  89912. }
  89913. });
  89914. }
  89915. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  89916. var lightConfig = { type: 0 };
  89917. if (typeof lightsConfiguration[name] === 'object') {
  89918. lightConfig = lightsConfiguration[name];
  89919. }
  89920. lightConfig.name = name;
  89921. var light;
  89922. if (lightsAvailable.indexOf(name) === -1) {
  89923. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  89924. if (!constructor)
  89925. return;
  89926. light = constructor();
  89927. }
  89928. else {
  89929. light = _this.scene.getLightByName(name);
  89930. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  89931. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  89932. light.dispose();
  89933. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  89934. if (!constructor)
  89935. return;
  89936. light = constructor();
  89937. }
  89938. }
  89939. if (lightsConfiguration[name] === false) {
  89940. light.dispose();
  89941. return;
  89942. }
  89943. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  89944. light.setEnabled(enabled);
  89945. _this.extendClassWithConfig(light, lightConfig);
  89946. if (light instanceof babylonjs_1.ShadowLight) {
  89947. if (lightConfig.target) {
  89948. if (light.setDirectionToTarget) {
  89949. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  89950. light.setDirectionToTarget(target);
  89951. }
  89952. }
  89953. else if (lightConfig.direction) {
  89954. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  89955. light.direction = direction;
  89956. }
  89957. var shadowGenerator = light.getShadowGenerator();
  89958. if (lightConfig.shadowEnabled && _this.maxShadows) {
  89959. if (!shadowGenerator) {
  89960. shadowGenerator = new babylonjs_1.ShadowGenerator(512, light);
  89961. }
  89962. _this.extendClassWithConfig(shadowGenerator, lightConfig.shadowConfig || {});
  89963. var shadownMap = shadowGenerator.getShadowMap();
  89964. if (!shadownMap)
  89965. return;
  89966. var renderList = shadownMap.renderList;
  89967. for (var index = 0; index < focusMeshes.length; index++) {
  89968. if (babylonjs_1.Tags.MatchesQuery(focusMeshes[index], 'castShadow')) {
  89969. renderList && renderList.push(focusMeshes[index]);
  89970. }
  89971. }
  89972. }
  89973. else if (shadowGenerator) {
  89974. shadowGenerator.dispose();
  89975. }
  89976. }
  89977. });
  89978. };
  89979. AbstractViewer.prototype.configureModel = function (modelConfiguration, focusMeshes) {
  89980. if (focusMeshes === void 0) { focusMeshes = this.scene.meshes; }
  89981. var meshesWithNoParent = focusMeshes.filter(function (m) { return !m.parent; });
  89982. var updateMeshesWithNoParent = function (variable, value, param) {
  89983. meshesWithNoParent.forEach(function (mesh) {
  89984. if (param) {
  89985. mesh[variable][param] = value;
  89986. }
  89987. else {
  89988. mesh[variable] = value;
  89989. }
  89990. });
  89991. };
  89992. var updateXYZ = function (variable, configValues) {
  89993. if (configValues.x !== undefined) {
  89994. updateMeshesWithNoParent(variable, configValues.x, 'x');
  89995. }
  89996. if (configValues.y !== undefined) {
  89997. updateMeshesWithNoParent(variable, configValues.y, 'y');
  89998. }
  89999. if (configValues.z !== undefined) {
  90000. updateMeshesWithNoParent(variable, configValues.z, 'z');
  90001. }
  90002. if (configValues.w !== undefined) {
  90003. updateMeshesWithNoParent(variable, configValues.w, 'w');
  90004. }
  90005. };
  90006. if (modelConfiguration.position) {
  90007. updateXYZ('position', modelConfiguration.position);
  90008. }
  90009. if (modelConfiguration.rotation) {
  90010. if (modelConfiguration.rotation.w) {
  90011. meshesWithNoParent.forEach(function (mesh) {
  90012. if (!mesh.rotationQuaternion) {
  90013. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  90014. }
  90015. });
  90016. updateXYZ('rotationQuaternion', modelConfiguration.rotation);
  90017. }
  90018. else {
  90019. updateXYZ('rotation', modelConfiguration.rotation);
  90020. }
  90021. }
  90022. if (modelConfiguration.scaling) {
  90023. updateXYZ('scaling', modelConfiguration.scaling);
  90024. }
  90025. if (modelConfiguration.castShadow) {
  90026. focusMeshes.forEach(function (mesh) {
  90027. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  90028. });
  90029. }
  90030. if (modelConfiguration.normalize) {
  90031. var center = false;
  90032. var unitSize = false;
  90033. var parentIndex = void 0;
  90034. if (modelConfiguration.normalize === true) {
  90035. center = true;
  90036. unitSize = true;
  90037. parentIndex = 0;
  90038. }
  90039. else {
  90040. center = !!modelConfiguration.normalize.center;
  90041. unitSize = !!modelConfiguration.normalize.unitSize;
  90042. parentIndex = modelConfiguration.normalize.parentIndex;
  90043. }
  90044. var meshesToNormalize = [];
  90045. if (parentIndex !== undefined) {
  90046. meshesToNormalize.push(focusMeshes[parentIndex]);
  90047. }
  90048. else {
  90049. meshesToNormalize = meshesWithNoParent;
  90050. }
  90051. if (unitSize) {
  90052. meshesToNormalize.forEach(function (mesh) {
  90053. console.log(mesh.scaling.x);
  90054. mesh.normalizeToUnitCube(true);
  90055. mesh.computeWorldMatrix(true);
  90056. console.log(mesh.scaling.x);
  90057. });
  90058. }
  90059. if (center) {
  90060. meshesToNormalize.forEach(function (mesh) {
  90061. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  90062. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  90063. var halfSizeVec = sizeVec.scale(0.5);
  90064. var center = boundingInfo.min.add(halfSizeVec);
  90065. mesh.position = center.scale(-1);
  90066. mesh.position.y += halfSizeVec.y;
  90067. mesh.computeWorldMatrix(true);
  90068. });
  90069. }
  90070. }
  90071. };
  90072. AbstractViewer.prototype.dispose = function () {
  90073. window.removeEventListener('resize', this.resize);
  90074. if (this.sceneOptimizer) {
  90075. this.sceneOptimizer.stop();
  90076. this.sceneOptimizer.dispose();
  90077. }
  90078. if (this.scene.activeCamera) {
  90079. this.scene.activeCamera.detachControl(this.canvas);
  90080. }
  90081. this.scene.dispose();
  90082. this.engine.dispose();
  90083. this.templateManager.dispose();
  90084. };
  90085. AbstractViewer.prototype.onTemplatesLoaded = function () {
  90086. return Promise.resolve(this);
  90087. };
  90088. AbstractViewer.prototype._onTemplateLoaded = function () {
  90089. var _this = this;
  90090. return this.onTemplatesLoaded().then(function () {
  90091. var autoLoadModel = !!_this.configuration.model;
  90092. return _this.initEngine().then(function (engine) {
  90093. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  90094. }).then(function () {
  90095. if (autoLoadModel) {
  90096. return _this.loadModel();
  90097. }
  90098. else {
  90099. return _this.scene || _this.initScene();
  90100. }
  90101. }).then(function (scene) {
  90102. return _this.onSceneInitObservable.notifyObserversWithPromise(scene);
  90103. }).then(function () {
  90104. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  90105. }).then(function () {
  90106. return _this;
  90107. });
  90108. });
  90109. };
  90110. AbstractViewer.prototype.initEngine = function () {
  90111. this.injectCustomShaders();
  90112. var canvasElement = this.templateManager.getCanvas();
  90113. if (!canvasElement) {
  90114. return Promise.reject('Canvas element not found!');
  90115. }
  90116. var config = this.configuration.engine || {};
  90117. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  90118. babylonjs_1.Database.IDBStorageEnabled = false;
  90119. if (!config.disableResize) {
  90120. window.addEventListener('resize', this.resize);
  90121. }
  90122. this.engine.runRenderLoop(this.render);
  90123. if (this.configuration.engine && this.configuration.engine.adaptiveQuality) {
  90124. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  90125. this.engine.setHardwareScalingLevel(scale);
  90126. }
  90127. this.handleHardwareLimitations();
  90128. return Promise.resolve(this.engine);
  90129. };
  90130. AbstractViewer.prototype.initScene = function () {
  90131. if (this.scene) {
  90132. this.scene.dispose();
  90133. }
  90134. this.scene = new babylonjs_1.Scene(this.engine);
  90135. this.scene.createDefaultLight(true);
  90136. if (this.configuration.scene) {
  90137. this.configureScene(this.configuration.scene);
  90138. if (this.configuration.optimizer) {
  90139. this.configureOptimizer(this.configuration.optimizer);
  90140. }
  90141. }
  90142. return Promise.resolve(this.scene);
  90143. };
  90144. AbstractViewer.prototype.loadModel = function (model, clearScene) {
  90145. var _this = this;
  90146. if (model === void 0) { model = this.configuration.model; }
  90147. if (clearScene === void 0) { clearScene = true; }
  90148. if (!model.url) {
  90149. return Promise.resolve(this.scene);
  90150. }
  90151. this.configuration.model = model;
  90152. var modelUrl = (typeof model === 'string') ? model : model.url;
  90153. var parts = modelUrl.split('/');
  90154. var filename = parts.pop();
  90155. var base = parts.join('/') + '/';
  90156. var plugin = (typeof model === 'string') ? undefined : model.loader;
  90157. return Promise.resolve(this.scene).then(function (scene) {
  90158. if (!scene)
  90159. return _this.initScene();
  90160. if (clearScene) {
  90161. scene.meshes.forEach(function (mesh) {
  90162. mesh.dispose();
  90163. });
  90164. }
  90165. return scene;
  90166. }).then(function () {
  90167. return new Promise(function (resolve, reject) {
  90168. _this.lastUsedLoader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, _this.scene, function (meshes) {
  90169. resolve(meshes);
  90170. }, function (progressEvent) {
  90171. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  90172. }, function (e, m, exception) {
  90173. _this.onModelLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception }).then(function () {
  90174. reject(exception);
  90175. });
  90176. }, plugin);
  90177. _this.onLoaderInitObservable.notifyObserversWithPromise(_this.lastUsedLoader);
  90178. });
  90179. }).then(function (meshes) {
  90180. return _this.onModelLoadedObservable.notifyObserversWithPromise(meshes)
  90181. .then(function () {
  90182. _this.configureModel(model, meshes);
  90183. _this.configureLights(_this.configuration.lights);
  90184. if (_this.configuration.camera) {
  90185. _this.configureCamera(_this.configuration.camera, meshes);
  90186. }
  90187. return _this.initEnvironment(meshes);
  90188. }).then(function () {
  90189. return _this.scene;
  90190. });
  90191. });
  90192. };
  90193. AbstractViewer.prototype.initEnvironment = function (focusMeshes) {
  90194. if (focusMeshes === void 0) { focusMeshes = []; }
  90195. this.configureEnvironment(this.configuration.skybox, this.configuration.ground);
  90196. return Promise.resolve(this.scene);
  90197. };
  90198. AbstractViewer.prototype.handleHardwareLimitations = function () {
  90199. var maxVaryingRows = this.engine.getCaps().maxVaryingVectors;
  90200. var maxFragmentSamplers = this.engine.getCaps().maxTexturesImageUnits;
  90201. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  90202. this.maxShadows = 0;
  90203. }
  90204. else {
  90205. this.maxShadows = 3;
  90206. }
  90207. var caps = this.engine.getCaps();
  90208. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  90209. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  90210. this._hdrSupport = !!(linearFloatTargets || linearHalfFloatTargets);
  90211. if (linearHalfFloatTargets) {
  90212. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  90213. this.shadowGeneratorBias = 0.002;
  90214. }
  90215. else if (linearFloatTargets) {
  90216. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  90217. this.shadowGeneratorBias = 0.001;
  90218. }
  90219. else {
  90220. this.defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  90221. this.shadowGeneratorBias = 0.001;
  90222. }
  90223. this.defaultPipelineTextureType = this._hdrSupport ? this.defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  90224. };
  90225. AbstractViewer.prototype.injectCustomShaders = function () {
  90226. var customShaders = this.configuration.customShaders;
  90227. if (!customShaders) {
  90228. return;
  90229. }
  90230. if (customShaders.shaders) {
  90231. Object.keys(customShaders.shaders).forEach(function (key) {
  90232. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  90233. });
  90234. }
  90235. if (customShaders.includes) {
  90236. Object.keys(customShaders.includes).forEach(function (key) {
  90237. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  90238. });
  90239. }
  90240. };
  90241. AbstractViewer.prototype.extendClassWithConfig = function (object, config) {
  90242. var _this = this;
  90243. if (!config)
  90244. return;
  90245. Object.keys(config).forEach(function (key) {
  90246. if (key in object && typeof object[key] !== 'function') {
  90247. if (typeof object[key] === 'object') {
  90248. _this.extendClassWithConfig(object[key], config[key]);
  90249. }
  90250. else {
  90251. if (config[key] !== undefined) {
  90252. object[key] = config[key];
  90253. }
  90254. }
  90255. }
  90256. });
  90257. };
  90258. AbstractViewer.prototype.setCameraBehavior = function (behaviorConfig, payload) {
  90259. var behavior;
  90260. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  90261. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  90262. switch (type) {
  90263. case 0:
  90264. this.camera.useAutoRotationBehavior = true;
  90265. behavior = this.camera.autoRotationBehavior;
  90266. break;
  90267. case 1:
  90268. this.camera.useBouncingBehavior = true;
  90269. behavior = this.camera.bouncingBehavior;
  90270. break;
  90271. case 2:
  90272. this.camera.useFramingBehavior = true;
  90273. behavior = this.camera.framingBehavior;
  90274. break;
  90275. default:
  90276. behavior = null;
  90277. break;
  90278. }
  90279. if (behavior) {
  90280. if (typeof behaviorConfig === "object") {
  90281. this.extendClassWithConfig(behavior, behaviorConfig);
  90282. }
  90283. }
  90284. switch (type) {
  90285. case 0:
  90286. break;
  90287. case 1:
  90288. break;
  90289. case 2:
  90290. if (config.zoomOnBoundingInfo) {
  90291. var meshes = payload;
  90292. var bounding = meshes[0].getHierarchyBoundingVectors();
  90293. behavior.zoomOnBoundingInfo(bounding.min, bounding.max);
  90294. }
  90295. break;
  90296. }
  90297. };
  90298. return AbstractViewer;
  90299. }());
  90300. exports.AbstractViewer = AbstractViewer;
  90301. /***/ }),
  90302. /* 7 */
  90303. /***/ (function(module, exports) {
  90304. module.exports = "<viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  90305. /***/ }),
  90306. /* 8 */
  90307. /***/ (function(module, exports) {
  90308. 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}}>";
  90309. /***/ }),
  90310. /* 9 */
  90311. /***/ (function(module, exports) {
  90312. 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=="
  90313. /***/ }),
  90314. /* 10 */
  90315. /***/ (function(module, exports) {
  90316. 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>";
  90317. /***/ }),
  90318. /* 11 */
  90319. /***/ (function(module, exports) {
  90320. 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>";
  90321. /***/ }),
  90322. /* 12 */
  90323. /***/ (function(module, exports) {
  90324. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  90325. /***/ }),
  90326. /* 13 */
  90327. /***/ (function(module, exports) {
  90328. module.exports = "Error loading the model";
  90329. /***/ }),
  90330. /* 14 */
  90331. /***/ (function(module, exports, __webpack_require__) {
  90332. (function (global, factory) {
  90333. true ? module.exports = factory() :
  90334. typeof define === 'function' && define.amd ? define(factory) :
  90335. (global.deepmerge = factory());
  90336. }(this, (function () { 'use strict';
  90337. var isMergeableObject = function isMergeableObject(value) {
  90338. return isNonNullObject(value)
  90339. && !isSpecial(value)
  90340. };
  90341. function isNonNullObject(value) {
  90342. return !!value && typeof value === 'object'
  90343. }
  90344. function isSpecial(value) {
  90345. var stringValue = Object.prototype.toString.call(value);
  90346. return stringValue === '[object RegExp]'
  90347. || stringValue === '[object Date]'
  90348. || isReactElement(value)
  90349. }
  90350. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  90351. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  90352. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  90353. function isReactElement(value) {
  90354. return value.$$typeof === REACT_ELEMENT_TYPE
  90355. }
  90356. function emptyTarget(val) {
  90357. return Array.isArray(val) ? [] : {}
  90358. }
  90359. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  90360. var clone = !optionsArgument || optionsArgument.clone !== false;
  90361. return (clone && isMergeableObject(value))
  90362. ? deepmerge(emptyTarget(value), value, optionsArgument)
  90363. : value
  90364. }
  90365. function defaultArrayMerge(target, source, optionsArgument) {
  90366. return target.concat(source).map(function(element) {
  90367. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  90368. })
  90369. }
  90370. function mergeObject(target, source, optionsArgument) {
  90371. var destination = {};
  90372. if (isMergeableObject(target)) {
  90373. Object.keys(target).forEach(function(key) {
  90374. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  90375. });
  90376. }
  90377. Object.keys(source).forEach(function(key) {
  90378. if (!isMergeableObject(source[key]) || !target[key]) {
  90379. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  90380. } else {
  90381. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  90382. }
  90383. });
  90384. return destination
  90385. }
  90386. function deepmerge(target, source, optionsArgument) {
  90387. var sourceIsArray = Array.isArray(source);
  90388. var targetIsArray = Array.isArray(target);
  90389. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  90390. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  90391. if (!sourceAndTargetTypesMatch) {
  90392. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  90393. } else if (sourceIsArray) {
  90394. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  90395. return arrayMerge(target, source, optionsArgument)
  90396. } else {
  90397. return mergeObject(target, source, optionsArgument)
  90398. }
  90399. }
  90400. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  90401. if (!Array.isArray(array)) {
  90402. throw new Error('first argument should be an array')
  90403. }
  90404. return array.reduce(function(prev, next) {
  90405. return deepmerge(prev, next, optionsArgument)
  90406. }, {})
  90407. };
  90408. var deepmerge_1 = deepmerge;
  90409. return deepmerge_1;
  90410. })));
  90411. /***/ }),
  90412. /* 15 */
  90413. /***/ (function(module, exports, __webpack_require__) {
  90414. module.exports = __webpack_require__(16);
  90415. /***/ }),
  90416. /* 16 */
  90417. /***/ (function(module, exports, __webpack_require__) {
  90418. "use strict";
  90419. Object.defineProperty(exports, "__esModule", { value: true });
  90420. var mappers_1 = __webpack_require__(1);
  90421. exports.mapperManager = mappers_1.mapperManager;
  90422. var viewerManager_1 = __webpack_require__(4);
  90423. exports.viewerManager = viewerManager_1.viewerManager;
  90424. var defaultViewer_1 = __webpack_require__(5);
  90425. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  90426. var viewer_1 = __webpack_require__(6);
  90427. exports.AbstractViewer = viewer_1.AbstractViewer;
  90428. __webpack_require__(0);
  90429. __webpack_require__(30);
  90430. __webpack_require__(31);
  90431. var babylonjs_1 = __webpack_require__(0);
  90432. var initializer_1 = __webpack_require__(32);
  90433. exports.InitTags = initializer_1.InitTags;
  90434. babylonjs_1.PromisePolyfill.Apply();
  90435. exports.disableInit = false;
  90436. document.addEventListener("DOMContentLoaded", function (event) {
  90437. if (exports.disableInit)
  90438. return;
  90439. initializer_1.InitTags();
  90440. });
  90441. /***/ }),
  90442. /* 17 */
  90443. /***/ (function(module, exports) {
  90444. module.exports = cannon;
  90445. /***/ }),
  90446. /* 18 */
  90447. /***/ (function(module, exports, __webpack_require__) {
  90448. /**
  90449. * from OimoPhysics DEV 1.1.0a AS3
  90450. * @author Saharan / http://el-ement.com/
  90451. *
  90452. * to Oimo.js 2015 JAVASCRIPT
  90453. * @author LoTh / http://lo-th.github.io/labs/
  90454. */
  90455. var OIMO = {
  90456. REVISION: "1.2",
  90457. // Global identification of next shape.
  90458. // This will be incremented every time a shape is created.
  90459. nextID: 0,
  90460. proxyID: 0,
  90461. // BroadPhase
  90462. BR_NULL: 0,
  90463. BR_BRUTE_FORCE: 1,
  90464. BR_SWEEP_AND_PRUNE: 2,
  90465. BR_BOUNDING_VOLUME_TREE: 3,
  90466. // body type
  90467. BODY_NULL: 0,
  90468. BODY_DYNAMIC: 1,
  90469. BODY_STATIC: 2,
  90470. // shape type
  90471. SHAPE_NULL: 0,
  90472. SHAPE_SPHERE: 1,
  90473. SHAPE_BOX: 2,
  90474. SHAPE_CYLINDER: 3,
  90475. SHAPE_TETRA: 4,
  90476. // joint type
  90477. JOINT_NULL: 0,
  90478. JOINT_DISTANCE: 1,
  90479. JOINT_BALL_AND_SOCKET: 2,
  90480. JOINT_HINGE: 3,
  90481. JOINT_WHEEL: 4,
  90482. JOINT_SLIDER: 5,
  90483. JOINT_PRISMATIC: 6,
  90484. // this world scale defaut is 0.1 to 10 meters max for dynamique body
  90485. // scale all by 100 so object is between 10 to 10000 three unit.
  90486. WORLD_SCALE: 100,
  90487. INV_SCALE: 0.01,
  90488. // AABB aproximation
  90489. AABB_PROX: 0.005,
  90490. // Math function
  90491. sqrt: Math.sqrt,
  90492. abs: Math.abs,
  90493. floor: Math.floor,
  90494. cos: Math.cos,
  90495. sin: Math.sin,
  90496. acos: Math.acos,
  90497. asin: Math.asin,
  90498. atan2: Math.atan2,
  90499. round: Math.round,
  90500. pow: Math.pow,
  90501. max: Math.max,
  90502. min: Math.min,
  90503. random: Math.random,
  90504. lerp: function (a, b, percent) { return a + (b - a) * percent; },
  90505. rand: function (a, b) { return OIMO.lerp(a, b, OIMO.random()); },
  90506. randInt: function (a, b, n) { return OIMO.lerp(a, b, OIMO.random()).toFixed(n || 0) * 1; },
  90507. int: function (x) { return ~~x; },
  90508. fix: function (x, n) { return x.toFixed(n || 3, 10); },
  90509. clamp: function (value, min, max) { return OIMO.max(min, OIMO.min(max, value)); },
  90510. degtorad: 0.0174532925199432957,
  90511. radtodeg: 57.295779513082320876,
  90512. PI: 3.141592653589793,
  90513. TwoPI: 6.283185307179586,
  90514. PI90: 1.570796326794896,
  90515. PI270: 4.712388980384689,
  90516. CustomError: null,
  90517. Error: function (Class, Msg) {
  90518. if (OIMO.CustomError == null) console.error(Class, Msg);
  90519. else OIMO.CustomError.innerHTML += Class + " - " + Msg + '<br>';
  90520. }
  90521. };
  90522. var OIMO_ARRAY_TYPE;
  90523. if (!OIMO_ARRAY_TYPE) { OIMO_ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; }
  90524. try {
  90525. (function (w) {
  90526. var perfNow;
  90527. var perfNowNames = ['now', 'webkitNow', 'msNow', 'mozNow'];
  90528. if (!!w['performance']) for (var i = 0; i < perfNowNames.length; ++i) {
  90529. var n = perfNowNames[i];
  90530. if (!!w['performance'][n]) {
  90531. perfNow = function () { return w['performance'][n]() };
  90532. break;
  90533. }
  90534. }
  90535. if (!perfNow) perfNow = Date.now;
  90536. //w.perfNow = perfNow;
  90537. OIMO.now = perfNow;
  90538. })(window);
  90539. } catch (e) { OIMO.now = function () { return 0; }; }
  90540. /**
  90541. * The class of physical computing world.
  90542. * You must be added to the world physical all computing objects
  90543. * @author saharan
  90544. * @author lo-th
  90545. */
  90546. OIMO.World = function (TimeStep, BroadPhaseType, Iterations, NoStat) {
  90547. // The time between each step
  90548. this.timeStep = TimeStep || 0.01666; // 1/60;
  90549. // The number of iterations for constraint solvers.
  90550. this.numIterations = Iterations || 8;
  90551. // It is a wide-area collision judgment that is used in order to reduce as much as possible a detailed collision judgment.
  90552. switch (BroadPhaseType || 2) {
  90553. case 1: this.broadPhase = new OIMO.BruteForceBroadPhase(); break;
  90554. case 2: default: this.broadPhase = new OIMO.SAPBroadPhase(); break;
  90555. case 3: this.broadPhase = new OIMO.DBVTBroadPhase(); break;
  90556. }
  90557. // This is the detailed information of the performance.
  90558. this.performance = null;
  90559. this.isNoStat = NoStat || false;
  90560. if (!this.isNoStat) this.performance = new OIMO.Performance(this);
  90561. // Whether the constraints randomizer is enabled or not.
  90562. this.enableRandomizer = true;
  90563. // The rigid body list
  90564. this.rigidBodies = null;
  90565. // number of rigid body
  90566. this.numRigidBodies = 0;
  90567. // The contact list
  90568. this.contacts = null;
  90569. this.unusedContacts = null;
  90570. // The number of contact
  90571. this.numContacts = 0;
  90572. // The number of contact points
  90573. this.numContactPoints = 0;
  90574. // The joint list
  90575. this.joints = null;
  90576. // The number of joints.
  90577. this.numJoints = 0;
  90578. // The number of simulation islands.
  90579. this.numIslands = 0;
  90580. // The gravity in the world.
  90581. this.gravity = new OIMO.Vec3(0, -9.80665, 0);
  90582. var numShapeTypes = 5;//4;//3;
  90583. this.detectors = [];
  90584. this.detectors.length = numShapeTypes;
  90585. var i = numShapeTypes;
  90586. while (i--) {
  90587. this.detectors[i] = [];
  90588. this.detectors[i].length = numShapeTypes;
  90589. }
  90590. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_SPHERE] = new OIMO.SphereSphereCollisionDetector();
  90591. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_BOX] = new OIMO.SphereBoxCollisionDetector(false);
  90592. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_SPHERE] = new OIMO.SphereBoxCollisionDetector(true);
  90593. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_BOX] = new OIMO.BoxBoxCollisionDetector();
  90594. // CYLINDER add
  90595. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_CYLINDER] = new OIMO.CylinderCylinderCollisionDetector();
  90596. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_BOX] = new OIMO.BoxCylinderCollisionDetector(true);
  90597. this.detectors[OIMO.SHAPE_BOX][OIMO.SHAPE_CYLINDER] = new OIMO.BoxCylinderCollisionDetector(false);
  90598. this.detectors[OIMO.SHAPE_CYLINDER][OIMO.SHAPE_SPHERE] = new OIMO.SphereCylinderCollisionDetector(true);
  90599. this.detectors[OIMO.SHAPE_SPHERE][OIMO.SHAPE_CYLINDER] = new OIMO.SphereCylinderCollisionDetector(false);
  90600. // TETRA add
  90601. this.detectors[OIMO.SHAPE_TETRA][OIMO.SHAPE_TETRA] = new OIMO.TetraTetraCollisionDetector();
  90602. this.randX = 65535;
  90603. this.randA = 98765;
  90604. this.randB = 123456789;
  90605. //this.maxIslandRigidBodies = 64;
  90606. this.islandRigidBodies = [];
  90607. //this.islandRigidBodies.length = this.maxIslandRigidBodies;
  90608. this.islandStack = [];
  90609. //this.islandStack.length = this.maxIslandRigidBodies;
  90610. //this.maxIslandConstraints = 128;
  90611. this.islandConstraints = [];
  90612. //this.islandConstraints.length = this.maxIslandConstraints;
  90613. };
  90614. OIMO.World.prototype = {
  90615. constructor: OIMO.World,
  90616. /**
  90617. * Reset the randomizer and remove all rigid bodies, shapes, joints and any object from the world.
  90618. */
  90619. clear: function () {
  90620. this.randX = 65535;
  90621. while (this.joints !== null) {
  90622. this.removeJoint(this.joints);
  90623. }
  90624. while (this.contacts !== null) {
  90625. this.removeContact(this.contacts);
  90626. }
  90627. while (this.rigidBodies !== null) {
  90628. this.removeRigidBody(this.rigidBodies);
  90629. }
  90630. OIMO.nextID = 0;
  90631. OIMO.proxyID = 0;
  90632. },
  90633. /**
  90634. * I'll add a rigid body to the world.
  90635. * Rigid body that has been added will be the operands of each step.
  90636. * @param rigidBody Rigid body that you want to add
  90637. */
  90638. addRigidBody: function (rigidBody) {
  90639. if (rigidBody.parent) {
  90640. OIMO.Error("World", "It is not possible to be added to more than one world one of the rigid body");
  90641. }
  90642. rigidBody.parent = this;
  90643. rigidBody.awake();
  90644. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  90645. this.addShape(shape);
  90646. }
  90647. if (this.rigidBodies !== null) (this.rigidBodies.prev = rigidBody).next = this.rigidBodies;
  90648. this.rigidBodies = rigidBody;
  90649. this.numRigidBodies++;
  90650. },
  90651. /**
  90652. * I will remove the rigid body from the world.
  90653. * Rigid body that has been deleted is excluded from the calculation on a step-by-step basis.
  90654. * @param rigidBody Rigid body to be removed
  90655. */
  90656. removeRigidBody: function (rigidBody) {
  90657. var remove = rigidBody;
  90658. if (remove.parent !== this) return;
  90659. remove.awake();
  90660. var js = remove.jointLink;
  90661. while (js != null) {
  90662. var joint = js.joint;
  90663. js = js.next;
  90664. this.removeJoint(joint);
  90665. }
  90666. for (var shape = rigidBody.shapes; shape !== null; shape = shape.next) {
  90667. this.removeShape(shape);
  90668. }
  90669. var prev = remove.prev;
  90670. var next = remove.next;
  90671. if (prev !== null) prev.next = next;
  90672. if (next !== null) next.prev = prev;
  90673. if (this.rigidBodies == remove) this.rigidBodies = next;
  90674. remove.prev = null;
  90675. remove.next = null;
  90676. remove.parent = null;
  90677. this.numRigidBodies--;
  90678. },
  90679. getByName: function (name) {
  90680. var result = null;
  90681. var body = this.rigidBodies;
  90682. while (body !== null) {
  90683. if (body.name !== " " && body.name === name) result = body;
  90684. body = body.next;
  90685. }
  90686. var joint = this.joints;
  90687. while (joint !== null) {
  90688. if (joint.name !== "" && joint.name === name) result = joint;
  90689. joint = joint.next;
  90690. }
  90691. return result;
  90692. },
  90693. /**
  90694. * I'll add a shape to the world..
  90695. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  90696. * Shape will be added to the world automatically, please do not call from outside this method.
  90697. * @param shape Shape you want to add
  90698. */
  90699. addShape: function (shape) {
  90700. if (!shape.parent || !shape.parent.parent) {
  90701. OIMO.Error("World", "It is not possible to be added alone to shape world");
  90702. }
  90703. shape.proxy = this.broadPhase.createProxy(shape);
  90704. shape.updateProxy();
  90705. this.broadPhase.addProxy(shape.proxy);
  90706. },
  90707. /**
  90708. * I will remove the shape from the world.
  90709. * Add to the rigid world, and if you add a shape to a rigid body that has been added to the world,
  90710. * Shape will be added to the world automatically, please do not call from outside this method.
  90711. * @param shape Shape you want to delete
  90712. */
  90713. removeShape: function (shape) {
  90714. this.broadPhase.removeProxy(shape.proxy);
  90715. shape.proxy = null;
  90716. },
  90717. /**
  90718. * I'll add a joint to the world.
  90719. * Joint that has been added will be the operands of each step.
  90720. * @param shape Joint to be added
  90721. */
  90722. addJoint: function (joint) {
  90723. if (joint.parent) {
  90724. OIMO.Error("World", "It is not possible to be added to more than one world one of the joint");
  90725. }
  90726. if (this.joints != null) (this.joints.prev = joint).next = this.joints;
  90727. this.joints = joint;
  90728. joint.parent = this;
  90729. this.numJoints++;
  90730. joint.awake();
  90731. joint.attach();
  90732. },
  90733. /**
  90734. * I will remove the joint from the world.
  90735. * Joint that has been added will be the operands of each step.
  90736. * @param shape Joint to be deleted
  90737. */
  90738. removeJoint: function (joint) {
  90739. var remove = joint;
  90740. var prev = remove.prev;
  90741. var next = remove.next;
  90742. if (prev !== null) prev.next = next;
  90743. if (next !== null) next.prev = prev;
  90744. if (this.joints == remove) this.joints = next;
  90745. remove.prev = null;
  90746. remove.next = null;
  90747. this.numJoints--;
  90748. remove.awake();
  90749. remove.detach();
  90750. remove.parent = null;
  90751. },
  90752. worldscale: function (scale) {
  90753. OIMO.WORLD_SCALE = scale || 100;
  90754. OIMO.INV_SCALE = 1 / OIMO.WORLD_SCALE;
  90755. },
  90756. addContact: function (s1, s2) {
  90757. var newContact;
  90758. if (this.unusedContacts !== null) {
  90759. newContact = this.unusedContacts;
  90760. this.unusedContacts = this.unusedContacts.next;
  90761. } else {
  90762. newContact = new OIMO.Contact();
  90763. }
  90764. newContact.attach(s1, s2);
  90765. newContact.detector = this.detectors[s1.type][s2.type];
  90766. if (this.contacts) (this.contacts.prev = newContact).next = this.contacts;
  90767. this.contacts = newContact;
  90768. this.numContacts++;
  90769. },
  90770. removeContact: function (contact) {
  90771. var prev = contact.prev;
  90772. var next = contact.next;
  90773. if (next) next.prev = prev;
  90774. if (prev) prev.next = next;
  90775. if (this.contacts == contact) this.contacts = next;
  90776. contact.prev = null;
  90777. contact.next = null;
  90778. contact.detach();
  90779. contact.next = this.unusedContacts;
  90780. this.unusedContacts = contact;
  90781. this.numContacts--;
  90782. },
  90783. checkContact: function (name1, name2) {
  90784. var n1, n2;
  90785. var contact = this.contacts;
  90786. while (contact !== null) {
  90787. n1 = contact.body1.name || ' ';
  90788. n2 = contact.body2.name || ' ';
  90789. if ((n1 == name1 && n2 == name2) || (n2 == name1 && n1 == name2)) { if (contact.touching) return true; else return false; }
  90790. else contact = contact.next;
  90791. }
  90792. return false;
  90793. },
  90794. callSleep: function (body) {
  90795. if (!body.allowSleep) return false;
  90796. if (body.linearVelocity.lengthSq() > 0.04) return false;
  90797. if (body.angularVelocity.lengthSq() > 0.25) return false;
  90798. return true;
  90799. },
  90800. /**
  90801. * I will proceed only time step seconds time of World.
  90802. */
  90803. step: function () {
  90804. var time0, time1, time2, time3;
  90805. var stat = !this.isNoStat ? true : false;
  90806. if (stat) time0 = OIMO.now();
  90807. var body = this.rigidBodies;
  90808. while (body !== null) {
  90809. body.addedToIsland = false;
  90810. if (body.sleeping) {
  90811. if (
  90812. body.linearVelocity.testZero() ||
  90813. body.angularVelocity.testZero() ||
  90814. body.position.testDiff(body.sleepPosition) ||
  90815. body.orientation.testDiff(body.sleepOrientation)
  90816. ) body.awake(); // awake the body
  90817. }
  90818. body = body.next;
  90819. }
  90820. //------------------------------------------------------
  90821. // UPDATE CONTACT
  90822. //------------------------------------------------------
  90823. // broad phase
  90824. if (stat) time1 = OIMO.now();
  90825. this.broadPhase.detectPairs();
  90826. var pairs = this.broadPhase.pairs;
  90827. var i = this.broadPhase.numPairs;
  90828. //do{
  90829. while (i--) {
  90830. //for(var i=0, l=numPairs; i<l; i++){
  90831. var pair = pairs[i];
  90832. var s1;
  90833. var s2;
  90834. if (pair.shape1.id < pair.shape2.id) {
  90835. s1 = pair.shape1;
  90836. s2 = pair.shape2;
  90837. } else {
  90838. s1 = pair.shape2;
  90839. s2 = pair.shape1;
  90840. }
  90841. var link;
  90842. if (s1.numContacts < s2.numContacts) link = s1.contactLink;
  90843. else link = s2.contactLink;
  90844. var exists = false;
  90845. while (link) {
  90846. var contact = link.contact;
  90847. if (contact.shape1 == s1 && contact.shape2 == s2) {
  90848. contact.persisting = true;
  90849. exists = true;// contact already exists
  90850. break;
  90851. }
  90852. link = link.next;
  90853. }
  90854. if (!exists) {
  90855. this.addContact(s1, s2);
  90856. }
  90857. }// while(i-- >0);
  90858. if (stat) {
  90859. time2 = OIMO.now();
  90860. this.performance.broadPhaseTime = time2 - time1;
  90861. }
  90862. // update & narrow phase
  90863. this.numContactPoints = 0;
  90864. contact = this.contacts;
  90865. while (contact !== null) {
  90866. if (!contact.persisting) {
  90867. if (contact.shape1.aabb.intersectTest(contact.shape2.aabb)) {
  90868. /*var aabb1=contact.shape1.aabb;
  90869. var aabb2=contact.shape2.aabb;
  90870. if(
  90871. aabb1.minX>aabb2.maxX || aabb1.maxX<aabb2.minX ||
  90872. aabb1.minY>aabb2.maxY || aabb1.maxY<aabb2.minY ||
  90873. aabb1.minZ>aabb2.maxZ || aabb1.maxZ<aabb2.minZ
  90874. ){*/
  90875. var next = contact.next;
  90876. this.removeContact(contact);
  90877. contact = next;
  90878. continue;
  90879. }
  90880. }
  90881. var b1 = contact.body1;
  90882. var b2 = contact.body2;
  90883. if (b1.isDynamic && !b1.sleeping || b2.isDynamic && !b2.sleeping) {
  90884. contact.updateManifold();
  90885. }
  90886. this.numContactPoints += contact.manifold.numPoints;
  90887. contact.persisting = false;
  90888. contact.constraint.addedToIsland = false;
  90889. contact = contact.next;
  90890. }
  90891. if (stat) {
  90892. time3 = OIMO.now();
  90893. this.performance.narrowPhaseTime = time3 - time2;
  90894. }
  90895. //------------------------------------------------------
  90896. // SOLVE ISLANDS
  90897. //------------------------------------------------------
  90898. var invTimeStep = 1 / this.timeStep;
  90899. //var body;
  90900. var joint;
  90901. var constraint;
  90902. //var num;
  90903. for (joint = this.joints; joint !== null; joint = joint.next) {
  90904. joint.addedToIsland = false;
  90905. }
  90906. // clear old island array
  90907. this.islandRigidBodies = [];
  90908. this.islandConstraints = [];
  90909. this.islandStack = [];
  90910. // expand island buffers
  90911. /*if(this.maxIslandRigidBodies<this.numRigidBodies){
  90912. this.maxIslandRigidBodies=this.numRigidBodies<<1;
  90913. //this.maxIslandRigidBodies=this.numRigidBodies*2;
  90914. this.islandRigidBodies=[];
  90915. this.islandStack=[];
  90916. this.islandRigidBodies.length = this.maxIslandRigidBodies;
  90917. this.islandStack.length = this.maxIslandRigidBodies;
  90918. }
  90919. var numConstraints=this.numJoints+this.numContacts;
  90920. if(this.maxIslandConstraints<numConstraints){
  90921. this.maxIslandConstraints=numConstraints<<1;
  90922. //this.maxIslandConstraints=numConstraints*2;
  90923. this.islandConstraints=[];
  90924. this.islandConstraints.length = this.maxIslandConstraints;
  90925. }*/
  90926. time1 = OIMO.now();
  90927. this.numIslands = 0;
  90928. // build and solve simulation islands
  90929. for (var base = this.rigidBodies; base !== null; base = base.next) {
  90930. if (base.addedToIsland || base.isStatic || base.sleeping) continue;// ignore
  90931. if (base.isLonely()) {// update single body
  90932. if (base.isDynamic) {
  90933. base.linearVelocity.addTime(this.gravity, this.timeStep);
  90934. /*base.linearVelocity.x+=this.gravity.x*this.timeStep;
  90935. base.linearVelocity.y+=this.gravity.y*this.timeStep;
  90936. base.linearVelocity.z+=this.gravity.z*this.timeStep;*/
  90937. }
  90938. if (this.callSleep(base)) {
  90939. base.sleepTime += this.timeStep;
  90940. if (base.sleepTime > 0.5) base.sleep();
  90941. else base.updatePosition(this.timeStep);
  90942. } else {
  90943. base.sleepTime = 0;
  90944. base.updatePosition(this.timeStep);
  90945. }
  90946. this.numIslands++;
  90947. continue;
  90948. }
  90949. var islandNumRigidBodies = 0;
  90950. var islandNumConstraints = 0;
  90951. var stackCount = 1;
  90952. // add rigid body to stack
  90953. this.islandStack[0] = base;
  90954. base.addedToIsland = true;
  90955. // build an island
  90956. do {
  90957. // get rigid body from stack
  90958. body = this.islandStack[--stackCount];
  90959. this.islandStack[stackCount] = null;
  90960. body.sleeping = false;
  90961. // add rigid body to the island
  90962. this.islandRigidBodies[islandNumRigidBodies++] = body;
  90963. if (body.isStatic) continue;
  90964. // search connections
  90965. for (var cs = body.contactLink; cs !== null; cs = cs.next) {
  90966. var contact = cs.contact;
  90967. constraint = contact.constraint;
  90968. if (constraint.addedToIsland || !contact.touching) continue;// ignore
  90969. // add constraint to the island
  90970. this.islandConstraints[islandNumConstraints++] = constraint;
  90971. constraint.addedToIsland = true;
  90972. var next = cs.body;
  90973. if (next.addedToIsland) continue;
  90974. // add rigid body to stack
  90975. this.islandStack[stackCount++] = next;
  90976. next.addedToIsland = true;
  90977. }
  90978. for (var js = body.jointLink; js !== null; js = js.next) {
  90979. constraint = js.joint;
  90980. if (constraint.addedToIsland) continue;// ignore
  90981. // add constraint to the island
  90982. this.islandConstraints[islandNumConstraints++] = constraint;
  90983. constraint.addedToIsland = true;
  90984. next = js.body;
  90985. if (next.addedToIsland || !next.isDynamic) continue;
  90986. // add rigid body to stack
  90987. this.islandStack[stackCount++] = next;
  90988. next.addedToIsland = true;
  90989. }
  90990. } while (stackCount != 0);
  90991. // update velocities
  90992. var gVel = new OIMO.Vec3().addTime(this.gravity, this.timeStep);
  90993. /*var gx=this.gravity.x*this.timeStep;
  90994. var gy=this.gravity.y*this.timeStep;
  90995. var gz=this.gravity.z*this.timeStep;*/
  90996. var j = islandNumRigidBodies;
  90997. while (j--) {
  90998. //or(var j=0, l=islandNumRigidBodies; j<l; j++){
  90999. body = this.islandRigidBodies[j];
  91000. if (body.isDynamic) {
  91001. body.linearVelocity.addEqual(gVel);
  91002. /*body.linearVelocity.x+=gx;
  91003. body.linearVelocity.y+=gy;
  91004. body.linearVelocity.z+=gz;*/
  91005. }
  91006. }
  91007. // randomizing order
  91008. if (this.enableRandomizer) {
  91009. //for(var j=1, l=islandNumConstraints; j<l; j++){
  91010. j = islandNumConstraints;
  91011. while (j--) {
  91012. if (j !== 0) {
  91013. var swap = (this.randX = (this.randX * this.randA + this.randB & 0x7fffffff)) / 2147483648.0 * j | 0;
  91014. constraint = this.islandConstraints[j];
  91015. this.islandConstraints[j] = this.islandConstraints[swap];
  91016. this.islandConstraints[swap] = constraint;
  91017. }
  91018. }
  91019. }
  91020. // solve contraints
  91021. j = islandNumConstraints;
  91022. while (j--) {
  91023. //for(j=0, l=islandNumConstraints; j<l; j++){
  91024. this.islandConstraints[j].preSolve(this.timeStep, invTimeStep);// pre-solve
  91025. }
  91026. var k = this.numIterations;
  91027. while (k--) {
  91028. //for(var k=0, l=this.numIterations; k<l; k++){
  91029. j = islandNumConstraints;
  91030. while (j--) {
  91031. //for(j=0, m=islandNumConstraints; j<m; j++){
  91032. this.islandConstraints[j].solve();// main-solve
  91033. }
  91034. }
  91035. j = islandNumConstraints;
  91036. while (j--) {
  91037. //for(j=0, l=islandNumConstraints; j<l; j++){
  91038. this.islandConstraints[j].postSolve();// post-solve
  91039. this.islandConstraints[j] = null;// gc
  91040. }
  91041. // sleeping check
  91042. var sleepTime = 10;
  91043. j = islandNumRigidBodies;
  91044. while (j--) {
  91045. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  91046. body = this.islandRigidBodies[j];
  91047. if (this.callSleep(body)) {
  91048. body.sleepTime += this.timeStep;
  91049. if (body.sleepTime < sleepTime) sleepTime = body.sleepTime;
  91050. } else {
  91051. body.sleepTime = 0;
  91052. sleepTime = 0;
  91053. continue;
  91054. }
  91055. }
  91056. if (sleepTime > 0.5) {
  91057. // sleep the island
  91058. j = islandNumRigidBodies;
  91059. while (j--) {
  91060. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  91061. this.islandRigidBodies[j].sleep();
  91062. this.islandRigidBodies[j] = null;// gc
  91063. }
  91064. } else {
  91065. // update positions
  91066. j = islandNumRigidBodies;
  91067. while (j--) {
  91068. //for(j=0, l=islandNumRigidBodies;j<l;j++){
  91069. this.islandRigidBodies[j].updatePosition(this.timeStep);
  91070. this.islandRigidBodies[j] = null;// gc
  91071. }
  91072. }
  91073. this.numIslands++;
  91074. }
  91075. if (stat) {
  91076. time2 = OIMO.now();
  91077. this.performance.solvingTime = time2 - time1;
  91078. //------------------------------------------------------
  91079. // END SIMULATION
  91080. //------------------------------------------------------
  91081. time2 = OIMO.now();
  91082. // fps update
  91083. this.performance.upfps();
  91084. this.performance.totalTime = time2 - time0;
  91085. }
  91086. }
  91087. }
  91088. /**
  91089. * The class of rigid body.
  91090. * Rigid body has the shape of a single or multiple collision processing,
  91091. * I can set the parameters individually.
  91092. * @author saharan
  91093. */
  91094. OIMO.RigidBody = function (x, y, z, rad, ax, ay, az) {
  91095. this.name = " ";
  91096. // The maximum number of shapes that can be added to a one rigid.
  91097. this.MAX_SHAPES = 64;//64;
  91098. this.prev = null;
  91099. this.next = null;
  91100. // I represent the kind of rigid body.
  91101. // Please do not change from the outside this variable.
  91102. // If you want to change the type of rigid body, always
  91103. // Please specify the type you want to set the arguments of setupMass method.
  91104. this.type = OIMO.BODY_NULL;
  91105. this.massInfo = new OIMO.MassInfo();
  91106. // It is the world coordinate of the center of gravity.
  91107. this.position = new OIMO.Vec3(x, y, z);
  91108. this.orientation = this.rotationAxisToQuad(rad || 0, ax || 0, ay || 0, az || 0);
  91109. this.newPosition = new OIMO.Vec3();
  91110. this.controlPos = false;
  91111. this.newOrientation = new OIMO.Quat();
  91112. this.newRotation = new OIMO.Vec3();
  91113. this.currentRotation = new OIMO.Vec3();
  91114. this.controlRot = false;
  91115. this.controlRotInTime = false;
  91116. // Is the translational velocity.
  91117. this.linearVelocity = new OIMO.Vec3();
  91118. // Is the angular velocity.
  91119. this.angularVelocity = new OIMO.Vec3();
  91120. // return matrix for three.js
  91121. this.matrix = new OIMO.Mat44();
  91122. //--------------------------------------------
  91123. // Please do not change from the outside this variables.
  91124. //--------------------------------------------
  91125. // It is a world that rigid body has been added.
  91126. this.parent = null;
  91127. this.contactLink = null;
  91128. this.numContacts = 0;
  91129. // An array of shapes that are included in the rigid body.
  91130. this.shapes = null;
  91131. // The number of shapes that are included in the rigid body.
  91132. this.numShapes = 0;
  91133. // It is the link array of joint that is connected to the rigid body.
  91134. this.jointLink = null;
  91135. // The number of joints that are connected to the rigid body.
  91136. this.numJoints = 0;
  91137. // It is the world coordinate of the center of gravity in the sleep just before.
  91138. this.sleepPosition = new OIMO.Vec3();
  91139. // It is a quaternion that represents the attitude of sleep just before.
  91140. this.sleepOrientation = new OIMO.Quat();
  91141. // I will show this rigid body to determine whether it is a rigid body static.
  91142. this.isStatic = false;
  91143. // I indicates that this rigid body to determine whether it is a rigid body dynamic.
  91144. this.isDynamic = false;
  91145. // It is a rotation matrix representing the orientation.
  91146. this.rotation = new OIMO.Mat33();
  91147. //--------------------------------------------
  91148. // It will be recalculated automatically from the shape, which is included.
  91149. //--------------------------------------------
  91150. // This is the weight.
  91151. this.mass = NaN;
  91152. // It is the reciprocal of the mass.
  91153. this.inverseMass = NaN;
  91154. // It is the inverse of the inertia tensor in the world system.
  91155. this.inverseInertia = new OIMO.Mat33();
  91156. // It is the inertia tensor in the initial state.
  91157. this.localInertia = new OIMO.Mat33();
  91158. // It is the inverse of the inertia tensor in the initial state.
  91159. this.inverseLocalInertia = new OIMO.Mat33();
  91160. // I indicates rigid body whether it has been added to the simulation Island.
  91161. this.addedToIsland = false;
  91162. // It shows how to sleep rigid body.
  91163. this.allowSleep = true;
  91164. // This is the time from when the rigid body at rest.
  91165. this.sleepTime = 0;
  91166. // I shows rigid body to determine whether it is a sleep state.
  91167. this.sleeping = false;
  91168. };
  91169. OIMO.RigidBody.prototype = {
  91170. constructor: OIMO.RigidBody,
  91171. /**
  91172. * I'll add a shape to rigid body.
  91173. * If you add a shape, please call the setupMass method to step up to the start of the next.
  91174. * @param shape shape to Add
  91175. */
  91176. addShape: function (shape) {
  91177. if (shape.parent) OIMO.Error("RigidBody", "It is not possible that you add to the multi-rigid body the shape of one");
  91178. if (this.shapes != null) (this.shapes.prev = shape).next = this.shapes;
  91179. this.shapes = shape;
  91180. shape.parent = this;
  91181. if (this.parent) this.parent.addShape(shape);
  91182. this.numShapes++;
  91183. },
  91184. /**
  91185. * I will delete the shape from the rigid body.
  91186. * If you delete a shape, please call the setupMass method to step up to the start of the next.
  91187. * @param shape shape to Delete
  91188. */
  91189. removeShape: function (shape) {
  91190. var remove = shape;
  91191. if (remove.parent != this) return;
  91192. var prev = remove.prev;
  91193. var next = remove.next;
  91194. if (prev != null) prev.next = next;
  91195. if (next != null) next.prev = prev;
  91196. if (this.shapes == remove) this.shapes = next;
  91197. remove.prev = null;
  91198. remove.next = null;
  91199. remove.parent = null;
  91200. if (this.parent) this.parent.removeShape(remove);
  91201. this.numShapes--;
  91202. },
  91203. remove: function () {
  91204. this.dispose();
  91205. },
  91206. dispose: function () {
  91207. this.parent.removeRigidBody(this);
  91208. },
  91209. checkContact: function (name) {
  91210. this.parent.checkContact(this.name, name);
  91211. },
  91212. /**
  91213. * Calulates mass datas(center of gravity, mass, moment inertia, etc...).
  91214. * If the parameter type is set to BODY_STATIC, the rigid body will be fixed to the space.
  91215. * If the parameter adjustPosition is set to true, the shapes' relative positions and
  91216. * the rigid body's position will be adjusted to the center of gravity.
  91217. * @param type
  91218. * @param adjustPosition
  91219. */
  91220. setupMass: function (type, AdjustPosition) {
  91221. var adjustPosition = (AdjustPosition !== undefined) ? AdjustPosition : true;
  91222. this.type = type || OIMO.BODY_DYNAMIC;
  91223. this.isDynamic = this.type == OIMO.BODY_DYNAMIC;
  91224. this.isStatic = this.type == OIMO.BODY_STATIC;
  91225. this.mass = 0;
  91226. this.localInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  91227. var te = this.localInertia.elements;
  91228. //
  91229. var tmpM = new OIMO.Mat33();
  91230. var tmpV = new OIMO.Vec3();
  91231. for (var shape = this.shapes; shape != null; shape = shape.next) {
  91232. shape.calculateMassInfo(this.massInfo);
  91233. var shapeMass = this.massInfo.mass;
  91234. var relX = shape.relativePosition.x;
  91235. var relY = shape.relativePosition.y;
  91236. var relZ = shape.relativePosition.z;
  91237. /*tmpV.x+=relX*shapeMass;
  91238. tmpV.y+=relY*shapeMass;
  91239. tmpV.z+=relZ*shapeMass;*/
  91240. tmpV.addScale(shape.relativePosition, shapeMass);
  91241. this.mass += shapeMass;
  91242. this.rotateInertia(shape.relativeRotation, this.massInfo.inertia, tmpM);
  91243. this.localInertia.addEqual(tmpM);
  91244. // add offset inertia
  91245. te[0] += shapeMass * (relY * relY + relZ * relZ);
  91246. te[4] += shapeMass * (relX * relX + relZ * relZ);
  91247. te[8] += shapeMass * (relX * relX + relY * relY);
  91248. var xy = shapeMass * relX * relY;
  91249. var yz = shapeMass * relY * relZ;
  91250. var zx = shapeMass * relZ * relX;
  91251. te[1] -= xy;
  91252. te[3] -= xy;
  91253. te[2] -= yz;
  91254. te[6] -= yz;
  91255. te[5] -= zx;
  91256. te[7] -= zx;
  91257. }
  91258. this.inverseMass = 1 / this.mass;
  91259. tmpV.scaleEqual(this.inverseMass);
  91260. if (adjustPosition) {
  91261. this.position.addEqual(tmpV);
  91262. for (shape = this.shapes; shape != null; shape = shape.next) {
  91263. shape.relativePosition.subEqual(tmpV);
  91264. }
  91265. // subtract offset inertia
  91266. relX = tmpV.x;
  91267. relY = tmpV.y;
  91268. relZ = tmpV.z;
  91269. //var te = this.localInertia.elements;
  91270. te[0] -= this.mass * (relY * relY + relZ * relZ);
  91271. te[4] -= this.mass * (relX * relX + relZ * relZ);
  91272. te[8] -= this.mass * (relX * relX + relY * relY);
  91273. xy = this.mass * relX * relY;
  91274. yz = this.mass * relY * relZ;
  91275. zx = this.mass * relZ * relX;
  91276. te[1] += xy;
  91277. te[3] += xy;
  91278. te[2] += yz;
  91279. te[6] += yz;
  91280. te[5] += zx;
  91281. te[7] += zx;
  91282. }
  91283. this.inverseLocalInertia.invert(this.localInertia);
  91284. if (this.type == OIMO.BODY_STATIC) {
  91285. this.inverseMass = 0;
  91286. this.inverseLocalInertia.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
  91287. }
  91288. this.syncShapes();
  91289. this.awake();
  91290. },
  91291. /**
  91292. * Awake the rigid body.
  91293. */
  91294. awake: function () {
  91295. if (!this.allowSleep || !this.sleeping) return;
  91296. this.sleeping = false;
  91297. this.sleepTime = 0;
  91298. // awake connected constraints
  91299. var cs = this.contactLink;
  91300. while (cs != null) {
  91301. cs.body.sleepTime = 0;
  91302. cs.body.sleeping = false;
  91303. cs = cs.next;
  91304. }
  91305. var js = this.jointLink;
  91306. while (js != null) {
  91307. js.body.sleepTime = 0;
  91308. js.body.sleeping = false;
  91309. js = js.next;
  91310. }
  91311. for (var shape = this.shapes; shape != null; shape = shape.next) {
  91312. shape.updateProxy();
  91313. }
  91314. },
  91315. /**
  91316. * Sleep the rigid body.
  91317. */
  91318. sleep: function () {
  91319. if (!this.allowSleep || this.sleeping) return;
  91320. this.linearVelocity.set(0, 0, 0);
  91321. this.angularVelocity.set(0, 0, 0);
  91322. this.sleepPosition.copy(this.position);
  91323. this.sleepOrientation.copy(this.orientation);
  91324. /*this.linearVelocity.x=0;
  91325. this.linearVelocity.y=0;
  91326. this.linearVelocity.z=0;
  91327. this.angularVelocity.x=0;
  91328. this.angularVelocity.y=0;
  91329. this.angularVelocity.z=0;
  91330. this.sleepPosition.x=this.position.x;
  91331. this.sleepPosition.y=this.position.y;
  91332. this.sleepPosition.z=this.position.z;*/
  91333. /*this.sleepOrientation.s=this.orientation.s;
  91334. this.sleepOrientation.x=this.orientation.x;
  91335. this.sleepOrientation.y=this.orientation.y;
  91336. this.sleepOrientation.z=this.orientation.z;*/
  91337. this.sleepTime = 0;
  91338. this.sleeping = true;
  91339. for (var shape = this.shapes; shape != null; shape = shape.next) {
  91340. shape.updateProxy();
  91341. }
  91342. },
  91343. /**
  91344. * Get whether the rigid body has not any connection with others.
  91345. * @return
  91346. */
  91347. isLonely: function () {
  91348. return this.numJoints == 0 && this.numContacts == 0;
  91349. },
  91350. /**
  91351. * The time integration of the motion of a rigid body, you can update the information such as the shape.
  91352. * This method is invoked automatically when calling the step of the World,
  91353. * There is no need to call from outside usually.
  91354. * @param timeStep time
  91355. */
  91356. updatePosition: function (timeStep) {
  91357. switch (this.type) {
  91358. case OIMO.BODY_STATIC:
  91359. this.linearVelocity.set(0, 0, 0);
  91360. this.angularVelocity.set(0, 0, 0);
  91361. // ONLY FOR TEST
  91362. if (this.controlPos) {
  91363. this.position.copy(this.newPosition);
  91364. this.controlPos = false;
  91365. }
  91366. if (this.controlRot) {
  91367. this.orientation.copy(this.newOrientation);
  91368. this.controlRot = false;
  91369. }
  91370. /*this.linearVelocity.x=0;
  91371. this.linearVelocity.y=0;
  91372. this.linearVelocity.z=0;
  91373. this.angularVelocity.x=0;
  91374. this.angularVelocity.y=0;
  91375. this.angularVelocity.z=0;*/
  91376. break;
  91377. case OIMO.BODY_DYNAMIC:
  91378. if (this.controlPos) {
  91379. this.angularVelocity.set(0, 0, 0);
  91380. this.linearVelocity.set(0, 0, 0);
  91381. this.linearVelocity.x = (this.newPosition.x - this.position.x) / timeStep;
  91382. this.linearVelocity.y = (this.newPosition.y - this.position.y) / timeStep;
  91383. this.linearVelocity.z = (this.newPosition.z - this.position.z) / timeStep;
  91384. this.controlPos = false;
  91385. }
  91386. if (this.controlRot) {
  91387. this.angularVelocity.set(0, 0, 0);
  91388. this.orientation.copy(this.newOrientation);
  91389. //var t=timeStep//*0.5;
  91390. //var q = new OIMO.Quat();
  91391. //q.sub(this.newOrientation, this.orientation);
  91392. //q.normalize(q);
  91393. /*q.s = (this.newOrientation.s - this.orientation.s)/t;
  91394. q.x = (this.newOrientation.x - this.orientation.x)/t;
  91395. q.y = (this.newOrientation.y - this.orientation.y)/t;
  91396. q.z = (this.newOrientation.z - this.orientation.z)/t;*/
  91397. //this.angularVelocity.applyQuaternion(q);
  91398. //this.angularVelocity.x = this.angularVelocity.x/t;
  91399. //this.angularVelocity.y = this.angularVelocity.y/t;
  91400. //this.angularVelocity.z = this.angularVelocity.z/t;
  91401. this.controlRot = false;
  91402. }
  91403. this.position.addTime(this.linearVelocity, timeStep);
  91404. this.orientation.addTime(this.angularVelocity, timeStep);
  91405. break;
  91406. default: OIMO.Error("RigidBody", "Invalid type.");
  91407. }
  91408. this.syncShapes();
  91409. },
  91410. rotateInertia: function (rot, inertia, out) {
  91411. var tm1 = rot.elements;
  91412. var tm2 = inertia.elements;
  91413. var a0 = tm1[0], a3 = tm1[3], a6 = tm1[6];
  91414. var a1 = tm1[1], a4 = tm1[4], a7 = tm1[7];
  91415. var a2 = tm1[2], a5 = tm1[5], a8 = tm1[8];
  91416. var b0 = tm2[0], b3 = tm2[3], b6 = tm2[6];
  91417. var b1 = tm2[1], b4 = tm2[4], b7 = tm2[7];
  91418. var b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  91419. var e00 = a0 * b0 + a1 * b3 + a2 * b6;
  91420. var e01 = a0 * b1 + a1 * b4 + a2 * b7;
  91421. var e02 = a0 * b2 + a1 * b5 + a2 * b8;
  91422. var e10 = a3 * b0 + a4 * b3 + a5 * b6;
  91423. var e11 = a3 * b1 + a4 * b4 + a5 * b7;
  91424. var e12 = a3 * b2 + a4 * b5 + a5 * b8;
  91425. var e20 = a6 * b0 + a7 * b3 + a8 * b6;
  91426. var e21 = a6 * b1 + a7 * b4 + a8 * b7;
  91427. var e22 = a6 * b2 + a7 * b5 + a8 * b8;
  91428. var oe = out.elements;
  91429. oe[0] = e00 * a0 + e01 * a1 + e02 * a2;
  91430. oe[1] = e00 * a3 + e01 * a4 + e02 * a5;
  91431. oe[2] = e00 * a6 + e01 * a7 + e02 * a8;
  91432. oe[3] = e10 * a0 + e11 * a1 + e12 * a2;
  91433. oe[4] = e10 * a3 + e11 * a4 + e12 * a5;
  91434. oe[5] = e10 * a6 + e11 * a7 + e12 * a8;
  91435. oe[6] = e20 * a0 + e21 * a1 + e22 * a2;
  91436. oe[7] = e20 * a3 + e21 * a4 + e22 * a5;
  91437. oe[8] = e20 * a6 + e21 * a7 + e22 * a8;
  91438. },
  91439. syncShapes: function () {
  91440. var s = this.orientation.s;
  91441. var x = this.orientation.x;
  91442. var y = this.orientation.y;
  91443. var z = this.orientation.z;
  91444. var x2 = 2 * x;
  91445. var y2 = 2 * y;
  91446. var z2 = 2 * z;
  91447. var xx = x * x2;
  91448. var yy = y * y2;
  91449. var zz = z * z2;
  91450. var xy = x * y2;
  91451. var yz = y * z2;
  91452. var xz = x * z2;
  91453. var sx = s * x2;
  91454. var sy = s * y2;
  91455. var sz = s * z2;
  91456. var tr = this.rotation.elements;
  91457. tr[0] = 1 - yy - zz;
  91458. tr[1] = xy - sz;
  91459. tr[2] = xz + sy;
  91460. tr[3] = xy + sz;
  91461. tr[4] = 1 - xx - zz;
  91462. tr[5] = yz - sx;
  91463. tr[6] = xz - sy;
  91464. tr[7] = yz + sx;
  91465. tr[8] = 1 - xx - yy;
  91466. this.rotateInertia(this.rotation, this.inverseLocalInertia, this.inverseInertia);
  91467. for (var shape = this.shapes; shape != null; shape = shape.next) {
  91468. //var relPos=shape.relativePosition;
  91469. //var relRot=shape.relativeRotation;
  91470. //var rot=shape.rotation;
  91471. /*var lx=relPos.x;
  91472. var ly=relPos.y;
  91473. var lz=relPos.z;
  91474. shape.position.x=this.position.x+lx*tr[0]+ly*tr[1]+lz*tr[2];
  91475. shape.position.y=this.position.y+lx*tr[3]+ly*tr[4]+lz*tr[5];
  91476. shape.position.z=this.position.z+lx*tr[6]+ly*tr[7]+lz*tr[8];*/
  91477. shape.position.mul(this.position, shape.relativePosition, this.rotation);
  91478. //shape.rotation.mul(shape.relativeRotation,this.rotation);
  91479. // add by QuaziKb
  91480. shape.rotation.mul(this.rotation, shape.relativeRotation);
  91481. shape.updateProxy();
  91482. }
  91483. },
  91484. applyImpulse: function (position, force) {
  91485. this.linearVelocity.addScale(force, this.inverseMass);
  91486. /*this.linearVelocity.x+=force.x*this.inverseMass;
  91487. this.linearVelocity.y+=force.y*this.inverseMass;
  91488. this.linearVelocity.z+=force.z*this.inverseMass;*/
  91489. var rel = new OIMO.Vec3();
  91490. rel.sub(position, this.position).cross(rel, force).mulMat(this.inverseInertia, rel);
  91491. this.angularVelocity.addEqual(rel);
  91492. /*this.angularVelocity.x+=rel.x;
  91493. this.angularVelocity.y+=rel.y;
  91494. this.angularVelocity.z+=rel.z;*/
  91495. },
  91496. //---------------------------------------------
  91497. //
  91498. // FOR THREE JS
  91499. //
  91500. //---------------------------------------------
  91501. rotationVectToQuad: function (rot) {
  91502. var r = OIMO.EulerToAxis(rot.x * OIMO.degtorad, rot.y * OIMO.degtorad, rot.z * OIMO.degtorad);
  91503. return this.rotationAxisToQuad(r[0], r[1], r[2], r[3]);
  91504. },
  91505. rotationAxisToQuad: function (rad, ax, ay, az) { // in radian
  91506. var len = ax * ax + ay * ay + az * az;
  91507. if (len > 0) {
  91508. len = 1 / OIMO.sqrt(len);
  91509. ax *= len;
  91510. ay *= len;
  91511. az *= len;
  91512. }
  91513. var sin = OIMO.sin(rad * 0.5);
  91514. var cos = OIMO.cos(rad * 0.5);
  91515. return new OIMO.Quat(cos, sin * ax, sin * ay, sin * az);
  91516. },
  91517. //---------------------------------------------
  91518. // SET DYNAMIQUE POSITION AND ROTATION
  91519. //---------------------------------------------
  91520. setPosition: function (pos) {
  91521. this.newPosition.copy(pos).multiplyScalar(OIMO.INV_SCALE);
  91522. //this.newPosition.set(pos.x*OIMO.INV_SCALE,pos.y*OIMO.INV_SCALE,pos.z*OIMO.INV_SCALE);
  91523. this.controlPos = true;
  91524. },
  91525. setQuaternion: function (q) {
  91526. //if(this.type == this.BODY_STATIC)this.orientation.init(q.w,q.x,q.y,q.z);
  91527. this.newOrientation.set(q.x, q.y, q.z, q.w);
  91528. this.controlRot = true;
  91529. },
  91530. setRotation: function (rot) {
  91531. this.newOrientation = this.rotationVectToQuad(rot);
  91532. this.controlRot = true;
  91533. },
  91534. //---------------------------------------------
  91535. // RESET DYNAMIQUE POSITION AND ROTATION
  91536. //---------------------------------------------
  91537. resetPosition: function (x, y, z) {
  91538. this.linearVelocity.set(0, 0, 0);
  91539. this.angularVelocity.set(0, 0, 0);
  91540. this.position.set(x, y, z).multiplyScalar(OIMO.INV_SCALE);
  91541. //this.position.set( x*OIMO.INV_SCALE, y*OIMO.INV_SCALE, z*OIMO.INV_SCALE );
  91542. this.awake();
  91543. },
  91544. resetQuaternion: function (q) {
  91545. this.angularVelocity.set(0, 0, 0);
  91546. this.orientation = new OIMO.Quat(q.w, q.x, q.y, q.z);
  91547. this.awake();
  91548. },
  91549. resetRotation: function (x, y, z) {
  91550. this.angularVelocity.set(0, 0, 0);
  91551. this.orientation = this.rotationVectToQuad(new OIMO.Vec3(x, y, z));
  91552. this.awake();
  91553. },
  91554. //---------------------------------------------
  91555. // GET POSITION AND ROTATION
  91556. //---------------------------------------------
  91557. getPosition: function () {
  91558. return new OIMO.Vec3().scale(this.position, OIMO.WORLD_SCALE);
  91559. },
  91560. getRotation: function () {
  91561. return new OIMO.Euler().setFromRotationMatrix(this.rotation);
  91562. },
  91563. getQuaternion: function () {
  91564. return new OIMO.Quaternion().setFromRotationMatrix(this.rotation);
  91565. },
  91566. getMatrix: function () {
  91567. var m = this.matrix.elements;
  91568. var r, p;
  91569. if (!this.sleeping) {
  91570. // rotation matrix
  91571. r = this.rotation.elements;
  91572. m[0] = r[0]; m[1] = r[3]; m[2] = r[6]; m[3] = 0;
  91573. m[4] = r[1]; m[5] = r[4]; m[6] = r[7]; m[7] = 0;
  91574. m[8] = r[2]; m[9] = r[5]; m[10] = r[8]; m[11] = 0;
  91575. // position matrix
  91576. p = this.position;
  91577. m[12] = p.x * OIMO.WORLD_SCALE;
  91578. m[13] = p.y * OIMO.WORLD_SCALE;
  91579. m[14] = p.z * OIMO.WORLD_SCALE;
  91580. // sleep or not ?
  91581. m[15] = 0;
  91582. } else {
  91583. m[15] = 1;
  91584. }
  91585. return m;
  91586. }
  91587. };
  91588. /**
  91589. * The main class of body.
  91590. * is for simplify creation process and data access of rigidRody
  91591. * Rigid body has the shape of a single or multiple collision processing,
  91592. * all setting in object
  91593. *
  91594. * @author loth
  91595. */
  91596. OIMO.Body = function (Obj) {
  91597. var obj = Obj || {};
  91598. if (!obj.world) return;
  91599. if (obj.type === undefined) obj.type = "box";
  91600. this.name = obj.name || '';
  91601. // obsolete use world.add(obj)
  91602. this.body = obj.world.add(obj);
  91603. /*
  91604. // the world where i am
  91605. this.parent = obj.world;
  91606. // Yep my name
  91607. this.name = obj.name || '';
  91608. // I'm dynamique or not
  91609. var move = obj.move || false;
  91610. // I can sleep or not
  91611. var noSleep = obj.noSleep || false;
  91612. // My start position
  91613. var p = obj.pos || [0,0,0];
  91614. p = p.map(function(x) { return x * OIMO.INV_SCALE; });
  91615. // My size
  91616. var s = obj.size || [1,1,1];
  91617. s = s.map(function(x) { return x * OIMO.INV_SCALE; });
  91618. // My rotation in degre
  91619. var rot = obj.rot || [0,0,0];
  91620. rot = rot.map(function(x) { return x * OIMO.TO_RAD; });
  91621. var r = [];
  91622. for (var i=0; i<rot.length/3; i++){
  91623. var tmp = OIMO.EulerToAxis(rot[i+0], rot[i+1], rot[i+2]);
  91624. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  91625. }
  91626. // My physics setting
  91627. var sc = obj.sc || new OIMO.ShapeConfig();
  91628. if(obj.config){
  91629. // The density of the shape.
  91630. sc.density = obj.config[0] || 1;
  91631. // The coefficient of friction of the shape.
  91632. sc.friction = obj.config[1] || 0.4;
  91633. // The coefficient of restitution of the shape.
  91634. sc.restitution = obj.config[2] || 0.2;
  91635. // The bits of the collision groups to which the shape belongs.
  91636. sc.belongsTo = obj.config[3] || 1;
  91637. // The bits of the collision groups with which the shape collides.
  91638. sc.collidesWith = obj.config[4] || 0xffffffff;
  91639. }
  91640. if(obj.massPos){
  91641. obj.massPos = obj.massPos.map(function(x) { return x * OIMO.INV_SCALE; });
  91642. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  91643. }
  91644. if(obj.massRot){
  91645. obj.massRot = obj.massRot.map(function(x) { return x * OIMO.TO_RAD; });
  91646. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  91647. }
  91648. // My rigidbody
  91649. this.body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  91650. // My shapes
  91651. var shapes = [];
  91652. var type = obj.type || "box";
  91653. if( typeof type === 'string' ) type = [type];// single shape
  91654. var n, n2;
  91655. for(var i=0; i<type.length; i++){
  91656. n = i*3;
  91657. n2 = i*4;
  91658. switch(type[i]){
  91659. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n+0]); break;
  91660. case "cylinder": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break; // fake cylinder
  91661. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n+0], s[n+1], s[n+2]); break;
  91662. }
  91663. this.body.addShape(shapes[i]);
  91664. if(i>0){
  91665. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  91666. shapes[i].relativePosition = new OIMO.Vec3( p[n+0], p[n+1], p[n+2] );
  91667. if(r[n2+0]) shapes[i].relativeRotation = [ r[n2+0], r[n2+1], r[n2+2], r[n2+3] ];
  91668. }
  91669. }
  91670. // I'm static or i move
  91671. if(move){
  91672. if(obj.massPos || obj.massRot)this.body.setupMass(0x1, false);
  91673. else this.body.setupMass(0x1, true);
  91674. if(noSleep) this.body.allowSleep = false;
  91675. else this.body.allowSleep = true;
  91676. } else {
  91677. this.body.setupMass(0x2);
  91678. }
  91679. this.body.name = this.name;
  91680. this.sleeping = this.body.sleeping;
  91681. // finaly add to physics world
  91682. this.parent.addRigidBody(this.body);*/
  91683. }
  91684. OIMO.Body.prototype = {
  91685. constructor: OIMO.Body,
  91686. // SET
  91687. setPosition: function (pos) {
  91688. this.body.setPosition(pos);
  91689. },
  91690. setQuaternion: function (q) {
  91691. this.body.setQuaternion(q);
  91692. },
  91693. setRotation: function (rot) {
  91694. this.body.setRotation(rot);
  91695. },
  91696. // GET
  91697. getPosition: function () {
  91698. return this.body.getPosition();
  91699. },
  91700. getRotation: function () {
  91701. return this.body.getRotation();
  91702. },
  91703. getQuaternion: function () {
  91704. return this.body.getQuaternion();
  91705. },
  91706. getMatrix: function () {
  91707. return this.body.getMatrix();
  91708. },
  91709. getSleep: function () {
  91710. return this.body.sleeping;
  91711. },
  91712. // RESET
  91713. resetPosition: function (x, y, z) {
  91714. this.body.resetPosition(x, y, z);
  91715. },
  91716. resetRotation: function (x, y, z) {
  91717. this.body.resetRotation(x, y, z);
  91718. },
  91719. // force wakeup
  91720. awake: function () {
  91721. this.body.awake();
  91722. },
  91723. // remove rigidbody
  91724. remove: function () {
  91725. this.body.dispose();
  91726. //this.parent.removeRigidBody(this.body);
  91727. },
  91728. // test if this object hit another
  91729. checkContact: function (name) {
  91730. this.body.checkContact(name);
  91731. //this.parent.checkContact(this.name, name);
  91732. }
  91733. }
  91734. /**
  91735. * The main class of link.
  91736. * is for simplify creation process and data access of Joint
  91737. * all setting in object
  91738. *
  91739. * @author loth
  91740. */
  91741. OIMO.Link = function (Obj) {
  91742. var obj = Obj || {};
  91743. if (!obj.world) return;
  91744. if (obj.type === undefined) obj.type = "jointHinge";
  91745. this.name = obj.name || '';
  91746. // obsolete use world.add(obj)
  91747. this.joint = obj.world.add(obj);
  91748. // the world where i am
  91749. /*this.parent = obj.world;
  91750. this.name = obj.name || '';
  91751. var type = obj.type || "jointHinge";
  91752. var axe1 = obj.axe1 || [1,0,0];
  91753. var axe2 = obj.axe2 || [1,0,0];
  91754. var pos1 = obj.pos1 || [0,0,0];
  91755. var pos2 = obj.pos2 || [0,0,0];
  91756. pos1 = pos1.map(function(x){ return x * OIMO.INV_SCALE; });
  91757. pos2 = pos2.map(function(x){ return x * OIMO.INV_SCALE; });
  91758. var min, max;
  91759. if(type==="jointDistance"){
  91760. min = obj.min || 0;
  91761. max = obj.max || 10;
  91762. min = min*OIMO.INV_SCALE;
  91763. max = max*OIMO.INV_SCALE;
  91764. }else{
  91765. min = obj.min || 57.29578;
  91766. max = obj.max || 0;
  91767. min = min*OIMO.TO_RAD;
  91768. max = max*OIMO.TO_RAD;
  91769. }
  91770. var limit = obj.limit || null;
  91771. var spring = obj.spring || null;
  91772. var motor = obj.motor || null;
  91773. // joint setting
  91774. var jc = new OIMO.JointConfig();
  91775. jc.allowCollision = obj.collision || false;;
  91776. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  91777. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  91778. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  91779. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  91780. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = obj.world.getByName(obj.body1);
  91781. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = obj.world.getByName(obj.body2);
  91782. jc.body1 = obj.body1;
  91783. jc.body2 = obj.body2;
  91784. switch(type){
  91785. case "jointDistance": this.joint = new OIMO.DistanceJoint(jc, min, max);
  91786. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);
  91787. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  91788. break;
  91789. case "jointHinge": this.joint = new OIMO.HingeJoint(jc, min, max);
  91790. if(spring !== null) this.joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  91791. if(motor !== null) this.joint.limitMotor.setSpring(motor[0], motor[1]);
  91792. break;
  91793. case "jointPrisme": this.joint = new OIMO.PrismaticJoint(jc, min, max); break;
  91794. case "jointSlide": this.joint = new OIMO.SliderJoint(jc, min, max); break;
  91795. case "jointBall": this.joint = new OIMO.BallAndSocketJoint(jc); break;
  91796. case "jointWheel": this.joint = new OIMO.WheelJoint(jc);
  91797. if(limit !== null) this.joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  91798. if(spring !== null) this.joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  91799. if(motor !== null) this.joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  91800. break;
  91801. }
  91802. this.joint.name = this.name;
  91803. // finaly add to physics world
  91804. this.parent.addJoint(this.joint);*/
  91805. }
  91806. OIMO.Link.prototype = {
  91807. constructor: OIMO.Link,
  91808. getPosition: function () {
  91809. // array of two vect3 [point1, point2]
  91810. return this.joint.getPosition();
  91811. },
  91812. getMatrix: function () {
  91813. return this.joint.getMatrix();
  91814. },
  91815. // remove joint
  91816. remove: function () {
  91817. this.joint.dispose();
  91818. //this.parent.removeJoint(this.joint);
  91819. },
  91820. // force wakeup linked body
  91821. awake: function () {
  91822. this.joint.awake();
  91823. }
  91824. }
  91825. /**
  91826. * The Dictionary class for testing
  91827. * @author lo-th
  91828. */
  91829. OIMO.Dictionary = function () {
  91830. this.data = {};
  91831. this.keys = [];
  91832. };
  91833. OIMO.Dictionary.prototype = {
  91834. constructor: OIMO.Dictionary,
  91835. set: function (value) {
  91836. var key = value.id;
  91837. if (!this.get[key]) this.keys.push(key);
  91838. this.data[key] = value;
  91839. },
  91840. get: function (id) {
  91841. return this.data[id];
  91842. },
  91843. del: function (value) {
  91844. var k = this.keys;
  91845. var n = k.indexOf(value.id);
  91846. if (n > -1) {
  91847. delete this.data[k[n]];
  91848. k.splice(n, 1);
  91849. }
  91850. },
  91851. reset: function () {
  91852. var data = this.data, keys = this.keys, key;
  91853. while (keys.length > 0) {
  91854. key = keys.pop();
  91855. delete data[key];
  91856. }
  91857. }
  91858. };
  91859. OIMO.Performance = function (world) {
  91860. this.parent = world;
  91861. this.infos = new OIMO_ARRAY_TYPE(13);
  91862. this.f = [0, 0, 0];
  91863. this.types = ['None', 'BruteForce', 'Sweep & Prune', 'Bounding Volume Tree'];
  91864. this.broadPhase = this.types[this.parent.broadPhase.types];
  91865. this.version = OIMO.REVISION;
  91866. this.fps = 0;
  91867. this.broadPhaseTime = 0;
  91868. this.narrowPhaseTime = 0;
  91869. this.solvingTime = 0;
  91870. //this.updatingTime = 0;
  91871. this.totalTime = 0;
  91872. };
  91873. OIMO.Performance.prototype = {
  91874. upfps: function () {
  91875. this.f[1] = Date.now();
  91876. 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]++;
  91877. },
  91878. updatingTime: function () {
  91879. return OIMO.fix(this.totalTime - (this.broadPhaseTime + this.narrowPhaseTime + this.solvingTime));
  91880. },
  91881. show: function () {
  91882. var info = [
  91883. "Oimo.js " + this.version + "<br>",
  91884. this.broadPhase + "<br><br>",
  91885. "FPS: " + this.fps + " fps<br><br>",
  91886. "rigidbody " + this.parent.numRigidBodies + "<br>",
  91887. "contact &nbsp;&nbsp;" + this.parent.numContacts + "<br>",
  91888. "ct-point &nbsp;" + this.parent.numContactPoints + "<br>",
  91889. "paircheck " + this.parent.broadPhase.numPairChecks + "<br>",
  91890. "island &nbsp;&nbsp;&nbsp;" + this.parent.numIslands + "<br><br>",
  91891. "Time in milliseconde<br><br>",
  91892. "broad-phase &nbsp;" + OIMO.fix(this.broadPhaseTime) + "<br>",
  91893. "narrow-phase " + OIMO.fix(this.narrowPhaseTime) + "<br>",
  91894. "solving &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.solvingTime) + "<br>",
  91895. "total &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + OIMO.fix(this.totalTime) + "<br>",
  91896. "updating &nbsp;&nbsp;&nbsp;&nbsp;" + this.updatingTime() + "<br>"
  91897. ].join("\n");
  91898. return info;
  91899. },
  91900. toArray: function () {
  91901. this.infos[0] = this.parent.broadPhase.types;
  91902. this.infos[1] = this.parent.numRigidBodies;
  91903. this.infos[2] = this.parent.numContacts;
  91904. this.infos[3] = this.parent.broadPhase.numPairChecks;
  91905. this.infos[4] = this.parent.numContactPoints;
  91906. this.infos[5] = this.parent.numIslands;
  91907. this.infos[6] = this.broadPhaseTime;
  91908. this.infos[7] = this.narrowPhaseTime;
  91909. this.infos[8] = this.solvingTime;
  91910. this.infos[9] = this.updatingTime();
  91911. this.infos[10] = this.totalTime;
  91912. this.infos[11] = this.fps;
  91913. return this.infos;
  91914. }
  91915. };
  91916. OIMO.Mat44 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  91917. this.elements = new OIMO_ARRAY_TYPE(16);
  91918. var te = this.elements;
  91919. te[0] = (n11 !== undefined) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  91920. te[1] = n21 || 0; te[5] = (n22 !== undefined) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  91921. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = (n33 !== undefined) ? n33 : 1; te[14] = n34 || 0;
  91922. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = (n44 !== undefined) ? n44 : 1;
  91923. };
  91924. OIMO.Mat44.prototype = {
  91925. constructor: OIMO.Mat44,
  91926. set: function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44) {
  91927. var te = this.elements;
  91928. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  91929. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  91930. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  91931. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  91932. return this;
  91933. }/*,
  91934. extractRotation: function () {
  91935. var v1 = new THREE.Vector3();
  91936. return function ( m ) {
  91937. var te = this.elements;
  91938. var me = m.elements;
  91939. var scaleX = 1 / v1.set( me[ 0 ], me[ 1 ], me[ 2 ] ).length();
  91940. var scaleY = 1 / v1.set( me[ 4 ], me[ 5 ], me[ 6 ] ).length();
  91941. var scaleZ = 1 / v1.set( me[ 8 ], me[ 9 ], me[ 10 ] ).length();
  91942. te[ 0 ] = me[ 0 ] * scaleX;
  91943. te[ 1 ] = me[ 1 ] * scaleX;
  91944. te[ 2 ] = me[ 2 ] * scaleX;
  91945. te[ 4 ] = me[ 4 ] * scaleY;
  91946. te[ 5 ] = me[ 5 ] * scaleY;
  91947. te[ 6 ] = me[ 6 ] * scaleY;
  91948. te[ 8 ] = me[ 8 ] * scaleZ;
  91949. te[ 9 ] = me[ 9 ] * scaleZ;
  91950. te[ 10 ] = me[ 10 ] * scaleZ;
  91951. return this;
  91952. };
  91953. }() */
  91954. }
  91955. OIMO.Mat33 = function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91956. this.elements = new OIMO_ARRAY_TYPE(9);
  91957. var te = this.elements;
  91958. this.init(
  91959. (e00 !== undefined) ? e00 : 1, e01 || 0, e02 || 0,
  91960. e10 || 0, (e11 !== undefined) ? e11 : 1, e12 || 0,
  91961. e20 || 0, e21 || 0, (e22 !== undefined) ? e22 : 1
  91962. );
  91963. };
  91964. OIMO.Mat33.prototype = {
  91965. constructor: OIMO.Mat33,
  91966. set: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91967. var te = this.elements;
  91968. te[0] = e00; te[1] = e01; te[2] = e02;
  91969. te[3] = e10; te[4] = e11; te[5] = e12;
  91970. te[6] = e20; te[7] = e21; te[8] = e22;
  91971. return this;
  91972. },
  91973. init: function (e00, e01, e02, e10, e11, e12, e20, e21, e22) {
  91974. var te = this.elements;
  91975. te[0] = e00; te[1] = e01; te[2] = e02;
  91976. te[3] = e10; te[4] = e11; te[5] = e12;
  91977. te[6] = e20; te[7] = e21; te[8] = e22;
  91978. return this;
  91979. },
  91980. multiply: function (s) {
  91981. var te = this.elements;
  91982. te[0] *= s; te[1] *= s; te[2] *= s;
  91983. te[3] *= s; te[4] *= s; te[5] *= s;
  91984. te[6] *= s; te[7] *= s; te[8] *= s;
  91985. return this;
  91986. },
  91987. add: function (m1, m2) {
  91988. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  91989. te[0] = tem1[0] + tem2[0]; te[1] = tem1[1] + tem2[1]; te[2] = tem1[2] + tem2[2];
  91990. te[3] = tem1[3] + tem2[3]; te[4] = tem1[4] + tem2[4]; te[5] = tem1[5] + tem2[5];
  91991. te[6] = tem1[6] + tem2[6]; te[7] = tem1[7] + tem2[7]; te[8] = tem1[8] + tem2[8];
  91992. return this;
  91993. },
  91994. addEqual: function (m) {
  91995. var te = this.elements, tem = m.elements;
  91996. te[0] += tem[0]; te[1] += tem[1]; te[2] += tem[2];
  91997. te[3] += tem[3]; te[4] += tem[4]; te[5] += tem[5];
  91998. te[6] += tem[6]; te[7] += tem[7]; te[8] += tem[8];
  91999. return this;
  92000. },
  92001. sub: function (m1, m2) {
  92002. var te = this.elements, tem1 = m1.elements, tem2 = m2.elements;
  92003. te[0] = tem1[0] - tem2[0]; te[1] = tem1[1] - tem2[1]; te[2] = tem1[2] - tem2[2];
  92004. te[3] = tem1[3] - tem2[3]; te[4] = tem1[4] - tem2[4]; te[5] = tem1[5] - tem2[5];
  92005. te[6] = tem1[6] - tem2[6]; te[7] = tem1[7] - tem2[7]; te[8] = tem1[8] - tem2[8];
  92006. return this;
  92007. },
  92008. subEqual: function (m) {
  92009. var te = this.elements, tem = m.elements;
  92010. te[0] -= tem[0]; te[1] -= tem[1]; te[2] -= tem[2];
  92011. te[3] -= tem[3]; te[4] -= tem[4]; te[5] -= tem[5];
  92012. te[6] -= tem[6]; te[7] -= tem[7]; te[8] -= tem[8];
  92013. return this;
  92014. },
  92015. scale: function (m, s) {
  92016. var te = this.elements, tm = m.elements;
  92017. te[0] = tm[0] * s; te[1] = tm[1] * s; te[2] = tm[2] * s;
  92018. te[3] = tm[3] * s; te[4] = tm[4] * s; te[5] = tm[5] * s;
  92019. te[6] = tm[6] * s; te[7] = tm[7] * s; te[8] = tm[8] * s;
  92020. return this;
  92021. },
  92022. scaleEqual: function (s) {
  92023. var te = this.elements;
  92024. te[0] *= s; te[1] *= s; te[2] *= s;
  92025. te[3] *= s; te[4] *= s; te[5] *= s;
  92026. te[6] *= s; te[7] *= s; te[8] *= s;
  92027. return this;
  92028. },
  92029. mul: function (m1, m2) {
  92030. var te = this.elements, tm1 = m1.elements, tm2 = m2.elements,
  92031. a0 = tm1[0], a3 = tm1[3], a6 = tm1[6],
  92032. a1 = tm1[1], a4 = tm1[4], a7 = tm1[7],
  92033. a2 = tm1[2], a5 = tm1[5], a8 = tm1[8],
  92034. b0 = tm2[0], b3 = tm2[3], b6 = tm2[6],
  92035. b1 = tm2[1], b4 = tm2[4], b7 = tm2[7],
  92036. b2 = tm2[2], b5 = tm2[5], b8 = tm2[8];
  92037. te[0] = a0 * b0 + a1 * b3 + a2 * b6;
  92038. te[1] = a0 * b1 + a1 * b4 + a2 * b7;
  92039. te[2] = a0 * b2 + a1 * b5 + a2 * b8;
  92040. te[3] = a3 * b0 + a4 * b3 + a5 * b6;
  92041. te[4] = a3 * b1 + a4 * b4 + a5 * b7;
  92042. te[5] = a3 * b2 + a4 * b5 + a5 * b8;
  92043. te[6] = a6 * b0 + a7 * b3 + a8 * b6;
  92044. te[7] = a6 * b1 + a7 * b4 + a8 * b7;
  92045. te[8] = a6 * b2 + a7 * b5 + a8 * b8;
  92046. return this;
  92047. },
  92048. mulScale: function (m, sx, sy, sz, Prepend) {
  92049. var prepend = Prepend || false;
  92050. var te = this.elements, tm = m.elements;
  92051. if (prepend) {
  92052. te[0] = sx * tm[0]; te[1] = sx * tm[1]; te[2] = sx * tm[2];
  92053. te[3] = sy * tm[3]; te[4] = sy * tm[4]; te[5] = sy * tm[5];
  92054. te[6] = sz * tm[6]; te[7] = sz * tm[7]; te[8] = sz * tm[8];
  92055. } else {
  92056. te[0] = tm[0] * sx; te[1] = tm[1] * sy; te[2] = tm[2] * sz;
  92057. te[3] = tm[3] * sx; te[4] = tm[4] * sy; te[5] = tm[5] * sz;
  92058. te[6] = tm[6] * sx; te[7] = tm[7] * sy; te[8] = tm[8] * sz;
  92059. }
  92060. return this;
  92061. },
  92062. mulRotate: function (m, rad, ax, ay, az, Prepend) {
  92063. var prepend = Prepend || false;
  92064. var s = OIMO.sin(rad);
  92065. var c = OIMO.cos(rad);
  92066. var c1 = 1 - c;
  92067. var r00 = ax * ax * c1 + c;
  92068. var r01 = ax * ay * c1 - az * s;
  92069. var r02 = ax * az * c1 + ay * s;
  92070. var r10 = ay * ax * c1 + az * s;
  92071. var r11 = ay * ay * c1 + c;
  92072. var r12 = ay * az * c1 - ax * s;
  92073. var r20 = az * ax * c1 - ay * s;
  92074. var r21 = az * ay * c1 + ax * s;
  92075. var r22 = az * az * c1 + c;
  92076. var tm = m.elements;
  92077. var a0 = tm[0], a3 = tm[3], a6 = tm[6];
  92078. var a1 = tm[1], a4 = tm[4], a7 = tm[7];
  92079. var a2 = tm[2], a5 = tm[5], a8 = tm[8];
  92080. var te = this.elements;
  92081. if (prepend) {
  92082. te[0] = r00 * a0 + r01 * a3 + r02 * a6;
  92083. te[1] = r00 * a1 + r01 * a4 + r02 * a7;
  92084. te[2] = r00 * a2 + r01 * a5 + r02 * a8;
  92085. te[3] = r10 * a0 + r11 * a3 + r12 * a6;
  92086. te[4] = r10 * a1 + r11 * a4 + r12 * a7;
  92087. te[5] = r10 * a2 + r11 * a5 + r12 * a8;
  92088. te[6] = r20 * a0 + r21 * a3 + r22 * a6;
  92089. te[7] = r20 * a1 + r21 * a4 + r22 * a7;
  92090. te[8] = r20 * a2 + r21 * a5 + r22 * a8;
  92091. } else {
  92092. te[0] = a0 * r00 + a1 * r10 + a2 * r20;
  92093. te[1] = a0 * r01 + a1 * r11 + a2 * r21;
  92094. te[2] = a0 * r02 + a1 * r12 + a2 * r22;
  92095. te[3] = a3 * r00 + a4 * r10 + a5 * r20;
  92096. te[4] = a3 * r01 + a4 * r11 + a5 * r21;
  92097. te[5] = a3 * r02 + a4 * r12 + a5 * r22;
  92098. te[6] = a6 * r00 + a7 * r10 + a8 * r20;
  92099. te[7] = a6 * r01 + a7 * r11 + a8 * r21;
  92100. te[8] = a6 * r02 + a7 * r12 + a8 * r22;
  92101. }
  92102. return this;
  92103. },
  92104. transpose: function (m) {
  92105. var te = this.elements, tm = m.elements;
  92106. te[0] = tm[0]; te[1] = tm[3]; te[2] = tm[6];
  92107. te[3] = tm[1]; te[4] = tm[4]; te[5] = tm[7];
  92108. te[6] = tm[2]; te[7] = tm[5]; te[8] = tm[8];
  92109. return this;
  92110. },
  92111. setQuat: function (q) {
  92112. var te = this.elements,
  92113. x2 = 2 * q.x, y2 = 2 * q.y, z2 = 2 * q.z,
  92114. xx = q.x * x2, yy = q.y * y2, zz = q.z * z2,
  92115. xy = q.x * y2, yz = q.y * z2, xz = q.x * z2,
  92116. sx = q.s * x2, sy = q.s * y2, sz = q.s * z2;
  92117. te[0] = 1 - yy - zz;
  92118. te[1] = xy - sz;
  92119. te[2] = xz + sy;
  92120. te[3] = xy + sz;
  92121. te[4] = 1 - xx - zz;
  92122. te[5] = yz - sx;
  92123. te[6] = xz - sy;
  92124. te[7] = yz + sx;
  92125. te[8] = 1 - xx - yy;
  92126. return this;
  92127. },
  92128. invert: function (m) {
  92129. var te = this.elements, tm = m.elements,
  92130. a0 = tm[0], a3 = tm[3], a6 = tm[6],
  92131. a1 = tm[1], a4 = tm[4], a7 = tm[7],
  92132. a2 = tm[2], a5 = tm[5], a8 = tm[8],
  92133. b01 = a4 * a8 - a7 * a5,
  92134. b11 = a7 * a2 - a1 * a8,
  92135. b21 = a1 * a5 - a4 * a2,
  92136. dt = a0 * (b01) + a3 * (b11) + a6 * (b21);
  92137. if (dt != 0) { dt = 1.0 / dt; }
  92138. te[0] = dt * b01;//(a4*a8 - a5*a7);
  92139. te[1] = dt * b11;//(a2*a7 - a1*a8);
  92140. te[2] = dt * b21;//(a1*a5 - a2*a4);
  92141. te[3] = dt * (a5 * a6 - a3 * a8);
  92142. te[4] = dt * (a0 * a8 - a2 * a6);
  92143. te[5] = dt * (a2 * a3 - a0 * a5);
  92144. te[6] = dt * (a3 * a7 - a4 * a6);
  92145. te[7] = dt * (a1 * a6 - a0 * a7);
  92146. te[8] = dt * (a0 * a4 - a1 * a3);
  92147. return this;
  92148. },
  92149. /*copy: function(m){
  92150. var te = this.elements, tem = m.elements;
  92151. te[0] = tem[0]; te[1] = tem[1]; te[2] = tem[2];
  92152. te[3] = tem[3]; te[4] = tem[4]; te[5] = tem[5];
  92153. te[6] = tem[6]; te[7] = tem[7]; te[8] = tem[8];
  92154. return this;
  92155. },*/
  92156. toEuler: function () { // not work !!
  92157. function clamp(x) {
  92158. return OIMO.min(OIMO.max(x, -1), 1);
  92159. }
  92160. var te = this.elements;
  92161. var m11 = te[0], m12 = te[3], m13 = te[6];
  92162. var m21 = te[1], m22 = te[4], m23 = te[7];
  92163. var m31 = te[2], m32 = te[5], m33 = te[8];
  92164. var p = new OIMO.Vec3();
  92165. var d = new OIMO.Quat();
  92166. var s;
  92167. p.y = OIMO.asin(clamp(m13));
  92168. if (OIMO.abs(m13) < 0.99999) {
  92169. p.x = OIMO.atan2(-m23, m33);
  92170. p.z = OIMO.atan2(-m12, m11);
  92171. } else {
  92172. p.x = OIMO.atan2(m32, m22);
  92173. p.z = 0;
  92174. }
  92175. return p;
  92176. },
  92177. /*clone: function(){
  92178. var te = this.elements;
  92179. return new OIMO.Mat33(
  92180. te[0], te[1], te[2],
  92181. te[3], te[4], te[5],
  92182. te[6], te[7], te[8]
  92183. );
  92184. },*/
  92185. toString: function () {
  92186. var te = this.elements;
  92187. var text =
  92188. "Mat33|" + te[0].toFixed(4) + ", " + te[1].toFixed(4) + ", " + te[2].toFixed(4) + "|\n" +
  92189. " |" + te[3].toFixed(4) + ", " + te[4].toFixed(4) + ", " + te[5].toFixed(4) + "|\n" +
  92190. " |" + te[6].toFixed(4) + ", " + te[7].toFixed(4) + ", " + te[8].toFixed(4) + "|";
  92191. return text;
  92192. },
  92193. // OK
  92194. multiplyScalar: function (s) {
  92195. var te = this.elements;
  92196. te[0] *= s; te[3] *= s; te[6] *= s;
  92197. te[1] *= s; te[4] *= s; te[7] *= s;
  92198. te[2] *= s; te[5] *= s; te[8] *= s;
  92199. return this;
  92200. },
  92201. identity: function () {
  92202. this.set(1, 0, 0, 0, 1, 0, 0, 0, 1);
  92203. return this;
  92204. },
  92205. clone: function () {
  92206. return new this.constructor().fromArray(this.elements);
  92207. },
  92208. copy: function (m) {
  92209. var me = m.elements;
  92210. this.set(
  92211. me[0], me[3], me[6],
  92212. me[1], me[4], me[7],
  92213. me[2], me[5], me[8]
  92214. );
  92215. return this;
  92216. },
  92217. fromArray: function (array) {
  92218. this.elements.set(array);
  92219. return this;
  92220. },
  92221. toArray: function () {
  92222. var te = this.elements;
  92223. return [
  92224. te[0], te[1], te[2],
  92225. te[3], te[4], te[5],
  92226. te[6], te[7], te[8]
  92227. ];
  92228. }
  92229. };
  92230. OIMO.Quat = function (s, x, y, z) {
  92231. this.s = (s !== undefined) ? s : 1;
  92232. this.x = x || 0;
  92233. this.y = y || 0;
  92234. this.z = z || 0;
  92235. };
  92236. OIMO.Quat.prototype = {
  92237. constructor: OIMO.Quat,
  92238. set: function (x, y, z, w) {
  92239. this.x = x;
  92240. this.y = y;
  92241. this.z = z;
  92242. this.s = w;
  92243. return this;
  92244. },
  92245. init: function (s, x, y, z) {
  92246. this.s = (s !== undefined) ? s : 1;
  92247. this.x = x || 0;
  92248. this.y = y || 0;
  92249. this.z = z || 0;
  92250. return this;
  92251. },
  92252. add: function (q1, q2) {
  92253. this.s = q1.s + q2.s;
  92254. this.x = q1.x + q2.x;
  92255. this.y = q1.y + q2.y;
  92256. this.z = q1.z + q2.z;
  92257. return this;
  92258. },
  92259. addTime: function (v, t) {
  92260. var x = v.x;
  92261. var y = v.y;
  92262. var z = v.z;
  92263. var qs = this.s;
  92264. var qx = this.x;
  92265. var qy = this.y;
  92266. var qz = this.z;
  92267. t *= 0.5;
  92268. var ns = (-x * qx - y * qy - z * qz) * t;
  92269. var nx = (x * qs + y * qz - z * qy) * t;
  92270. var ny = (-x * qz + y * qs + z * qx) * t;
  92271. var nz = (x * qy - y * qx + z * qs) * t;
  92272. qs += ns;
  92273. qx += nx;
  92274. qy += ny;
  92275. qz += nz;
  92276. var s = 1 / OIMO.sqrt(qs * qs + qx * qx + qy * qy + qz * qz);
  92277. this.s = qs * s;
  92278. this.x = qx * s;
  92279. this.y = qy * s;
  92280. this.z = qz * s;
  92281. return this;
  92282. },
  92283. sub: function (q1, q2) {
  92284. this.s = q1.s - q2.s;
  92285. this.x = q1.x - q2.x;
  92286. this.y = q1.y - q2.y;
  92287. this.z = q1.z - q2.z;
  92288. return this;
  92289. },
  92290. scale: function (q, s) {
  92291. this.s = q.s * s;
  92292. this.x = q.x * s;
  92293. this.y = q.y * s;
  92294. this.z = q.z * s;
  92295. return this;
  92296. },
  92297. mul: function (q1, q2) {
  92298. var ax = q1.x, ay = q1.y, az = q1.z, as = q1.s,
  92299. bx = q2.x, by = q2.y, bz = q2.z, bs = q2.s;
  92300. this.x = ax * bs + as * bx + ay * bz - az * by;
  92301. this.y = ay * bs + as * by + az * bx - ax * bz;
  92302. this.z = az * bs + as * bz + ax * by - ay * bx;
  92303. this.s = as * bs - ax * bx - ay * by - az * bz;
  92304. return this;
  92305. },
  92306. arc: function (v1, v2) {
  92307. var x1 = v1.x;
  92308. var y1 = v1.y;
  92309. var z1 = v1.z;
  92310. var x2 = v2.x;
  92311. var y2 = v2.y;
  92312. var z2 = v2.z;
  92313. var d = x1 * x2 + y1 * y2 + z1 * z2;
  92314. if (d == -1) {
  92315. x2 = y1 * x1 - z1 * z1;
  92316. y2 = -z1 * y1 - x1 * x1;
  92317. z2 = x1 * z1 + y1 * y1;
  92318. d = 1 / OIMO.sqrt(x2 * x2 + y2 * y2 + z2 * z2);
  92319. this.s = 0;
  92320. this.x = x2 * d;
  92321. this.y = y2 * d;
  92322. this.z = z2 * d;
  92323. return this;
  92324. }
  92325. var cx = y1 * z2 - z1 * y2;
  92326. var cy = z1 * x2 - x1 * z2;
  92327. var cz = x1 * y2 - y1 * x2;
  92328. this.s = OIMO.sqrt((1 + d) * 0.5);
  92329. d = 0.5 / this.s;
  92330. this.x = cx * d;
  92331. this.y = cy * d;
  92332. this.z = cz * d;
  92333. return this;
  92334. },
  92335. normalize: function (q) {
  92336. var len = OIMO.sqrt(q.s * q.s + q.x * q.x + q.y * q.y + q.z * q.z);
  92337. if (len > 0) { len = 1 / len; }
  92338. this.s = q.s * len;
  92339. this.x = q.x * len;
  92340. this.y = q.y * len;
  92341. this.z = q.z * len;
  92342. return this;
  92343. },
  92344. invert: function (q) {
  92345. this.s = q.s;
  92346. this.x = -q.x;
  92347. this.y = -q.y;
  92348. this.z = -q.z;
  92349. return this;
  92350. },
  92351. length: function () {
  92352. return OIMO.sqrt(this.s * this.s + this.x * this.x + this.y * this.y + this.z * this.z);
  92353. },
  92354. copy: function (q) {
  92355. this.s = q.s;
  92356. this.x = q.x;
  92357. this.y = q.y;
  92358. this.z = q.z;
  92359. return this;
  92360. },
  92361. testDiff: function (q) {
  92362. if (this.s !== q.s || this.x !== q.x || this.y !== q.y || this.z !== q.z) return true;
  92363. else return false;
  92364. },
  92365. clone: function (q) {
  92366. return new OIMO.Quat(this.s, this.x, this.y, this.z);
  92367. },
  92368. toString: function () {
  92369. return "Quat[" + this.s.toFixed(4) + ", (" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + ")]";
  92370. }
  92371. }
  92372. // for three easy export
  92373. OIMO.Quaternion = function (x, y, z, w) {
  92374. this.x = x || 0;
  92375. this.y = y || 0;
  92376. this.z = z || 0;
  92377. this.w = (w !== undefined) ? w : 1;
  92378. };
  92379. OIMO.Quaternion.prototype = {
  92380. constructor: OIMO.Quaternion,
  92381. setFromRotationMatrix: function (m) {
  92382. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  92383. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  92384. var te = m.elements,
  92385. m11 = te[0], m12 = te[1], m13 = te[2],
  92386. m21 = te[3], m22 = te[4], m23 = te[5],
  92387. m31 = te[6], m32 = te[7], m33 = te[8],
  92388. trace = m11 + m22 + m33,
  92389. s;
  92390. if (trace > 0) {
  92391. s = 0.5 / OIMO.sqrt(trace + 1.0);
  92392. this.w = 0.25 / s;
  92393. this.x = (m32 - m23) * s;
  92394. this.y = (m13 - m31) * s;
  92395. this.z = (m21 - m12) * s;
  92396. } else if (m11 > m22 && m11 > m33) {
  92397. s = 2.0 * OIMO.sqrt(1.0 + m11 - m22 - m33);
  92398. this.w = (m32 - m23) / s;
  92399. this.x = 0.25 * s;
  92400. this.y = (m12 + m21) / s;
  92401. this.z = (m13 + m31) / s;
  92402. } else if (m22 > m33) {
  92403. s = 2.0 * OIMO.sqrt(1.0 + m22 - m11 - m33);
  92404. this.w = (m13 - m31) / s;
  92405. this.x = (m12 + m21) / s;
  92406. this.y = 0.25 * s;
  92407. this.z = (m23 + m32) / s;
  92408. } else {
  92409. s = 2.0 * OIMO.sqrt(1.0 + m33 - m11 - m22);
  92410. this.w = (m21 - m12) / s;
  92411. this.x = (m13 + m31) / s;
  92412. this.y = (m23 + m32) / s;
  92413. this.z = 0.25 * s;
  92414. }
  92415. //this.onChangeCallback();
  92416. return this;
  92417. }
  92418. }
  92419. OIMO.Vec3 = function (x, y, z) {
  92420. this.x = x || 0;
  92421. this.y = y || 0;
  92422. this.z = z || 0;
  92423. };
  92424. OIMO.Vec3.prototype = {
  92425. constructor: OIMO.Vec3,
  92426. init: function (x, y, z) {
  92427. this.x = x || 0;
  92428. this.y = y || 0;
  92429. this.z = z || 0;
  92430. return this;
  92431. },
  92432. set: function (x, y, z) {
  92433. this.x = x;
  92434. this.y = y;
  92435. this.z = z;
  92436. return this;
  92437. },
  92438. add: function (v1, v2) {
  92439. this.x = v1.x + v2.x;
  92440. this.y = v1.y + v2.y;
  92441. this.z = v1.z + v2.z;
  92442. return this;
  92443. },
  92444. addEqual: function (v) {
  92445. this.x += v.x;
  92446. this.y += v.y;
  92447. this.z += v.z;
  92448. return this;
  92449. },
  92450. addTime: function (v, t) {
  92451. this.x += v.x * t;
  92452. this.y += v.y * t;
  92453. this.z += v.z * t;
  92454. return this;
  92455. },
  92456. sub: function (v1, v2) {
  92457. this.x = v1.x - v2.x;
  92458. this.y = v1.y - v2.y;
  92459. this.z = v1.z - v2.z;
  92460. return this;
  92461. },
  92462. subEqual: function (v) {
  92463. this.x -= v.x;
  92464. this.y -= v.y;
  92465. this.z -= v.z;
  92466. return this;
  92467. },
  92468. addScale: function (v, s) {
  92469. this.x += v.x * s;
  92470. this.y += v.y * s;
  92471. this.z += v.z * s;
  92472. return this;
  92473. },
  92474. scale: function (v, s) {
  92475. this.x = v.x * s;
  92476. this.y = v.y * s;
  92477. this.z = v.z * s;
  92478. return this;
  92479. },
  92480. scaleEqual: function (s) {
  92481. this.x *= s;
  92482. this.y *= s;
  92483. this.z *= s;
  92484. return this;
  92485. },
  92486. /*dot: function(v){
  92487. return this.x*v.x+this.y*v.y+this.z*v.z;
  92488. },*/
  92489. cross: function (v1, v2) {
  92490. var ax = v1.x, ay = v1.y, az = v1.z,
  92491. bx = v2.x, by = v2.y, bz = v2.z;
  92492. this.x = ay * bz - az * by;
  92493. this.y = az * bx - ax * bz;
  92494. this.z = ax * by - ay * bx;
  92495. return this;
  92496. },
  92497. mul: function (o, v, m) {
  92498. var te = m.elements;
  92499. this.x = o.x + v.x * te[0] + v.y * te[1] + v.z * te[2];
  92500. this.y = o.y + v.x * te[3] + v.y * te[4] + v.z * te[5];
  92501. this.z = o.z + v.x * te[6] + v.y * te[7] + v.z * te[8];
  92502. return this;
  92503. },
  92504. mulMat: function (m, v) {
  92505. var te = m.elements;
  92506. this.x = te[0] * v.x + te[1] * v.y + te[2] * v.z;
  92507. this.y = te[3] * v.x + te[4] * v.y + te[5] * v.z;
  92508. this.z = te[6] * v.x + te[7] * v.y + te[8] * v.z;
  92509. return this;
  92510. },
  92511. normalize: function (v) {
  92512. var x = v.x, y = v.y, z = v.z;
  92513. var l = x * x + y * y + z * z;
  92514. if (l > 0) {
  92515. l = 1 / OIMO.sqrt(l);
  92516. this.x = x * l;
  92517. this.y = y * l;
  92518. this.z = z * l;
  92519. }
  92520. return this;
  92521. },
  92522. /*norm: function(){
  92523. var x = this.x, y = this.y, z = this.z;
  92524. var l = x*x + y*y + z*z;
  92525. if (l > 0) {
  92526. l = 1 / OIMO.sqrt(l);
  92527. this.x = x*l;
  92528. this.y = y*l;
  92529. this.z = z*l;
  92530. }
  92531. return this;
  92532. },*/
  92533. invert: function (v) {
  92534. this.x = -v.x;
  92535. this.y = -v.y;
  92536. this.z = -v.z;
  92537. return this;
  92538. },
  92539. /*length: function(){
  92540. var x = this.x, y = this.y, z = this.z;
  92541. return OIMO.sqrt(x*x + y*y + z*z);
  92542. },*/
  92543. negate: function () {
  92544. this.x = -this.x;
  92545. this.y = -this.y;
  92546. this.z = -this.z;
  92547. return this;
  92548. },
  92549. dot: function (v) {
  92550. return this.x * v.x + this.y * v.y + this.z * v.z;
  92551. },
  92552. lengthSq: function () {
  92553. return this.x * this.x + this.y * this.y + this.z * this.z;
  92554. },
  92555. length: function () {
  92556. return OIMO.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  92557. },
  92558. /*len: function(){
  92559. var x = this.x, y = this.y, z = this.z;
  92560. return x*x + y*y + z*z;
  92561. },*/
  92562. copy: function (v) {
  92563. this.x = v.x;
  92564. this.y = v.y;
  92565. this.z = v.z;
  92566. return this;
  92567. },
  92568. applyQuaternion: function (q) {
  92569. var x = this.x;
  92570. var y = this.y;
  92571. var z = this.z;
  92572. var qx = q.x;
  92573. var qy = q.y;
  92574. var qz = q.z;
  92575. var qs = q.s;
  92576. // calculate quat * vector
  92577. var ix = qs * x + qy * z - qz * y;
  92578. var iy = qs * y + qz * x - qx * z;
  92579. var iz = qs * z + qx * y - qy * x;
  92580. var iw = -qx * x - qy * y - qz * z;
  92581. // calculate result * inverse quat
  92582. this.x = ix * qs + iw * -qx + iy * -qz - iz * -qy;
  92583. this.y = iy * qs + iw * -qy + iz * -qx - ix * -qz;
  92584. this.z = iz * qs + iw * -qz + ix * -qy - iy * -qx;
  92585. return this;
  92586. },
  92587. testZero: function () {
  92588. if (this.x !== 0 || this.y !== 0 || this.z !== 0) return true;
  92589. else return false;
  92590. },
  92591. testDiff: function (v) {
  92592. return ((v.x !== this.x) || (v.y !== this.y) || (v.z !== this.z));
  92593. //if(this.x!==v.x || this.y!==v.y || this.z!==v.z) return true;
  92594. //else return false;
  92595. },
  92596. equals: function (v) {
  92597. return ((v.x === this.x) && (v.y === this.y) && (v.z === this.z));
  92598. },
  92599. clone: function () {
  92600. return new this.constructor(this.x, this.y, this.z);
  92601. },
  92602. toString: function () {
  92603. return "Vec3[" + this.x.toFixed(4) + ", " + this.y.toFixed(4) + ", " + this.z.toFixed(4) + "]";
  92604. },
  92605. multiplyScalar: function (scalar) {
  92606. if (isFinite(scalar)) {
  92607. this.x *= scalar;
  92608. this.y *= scalar;
  92609. this.z *= scalar;
  92610. } else {
  92611. this.x = 0;
  92612. this.y = 0;
  92613. this.z = 0;
  92614. }
  92615. return this;
  92616. },
  92617. divideScalar: function (scalar) {
  92618. return this.multiplyScalar(1 / scalar);
  92619. },
  92620. // TODO rename to normalize
  92621. norm: function () {
  92622. return this.divideScalar(this.length());
  92623. },
  92624. }
  92625. OIMO.Euler = function (x, y, z, order) {
  92626. this._x = x || 0;
  92627. this._y = y || 0;
  92628. this._z = z || 0;
  92629. this._order = order || OIMO.Euler.DefaultOrder;
  92630. };
  92631. OIMO.Euler.RotationOrders = ['XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX'];
  92632. OIMO.Euler.DefaultOrder = 'XYZ';
  92633. OIMO.clamp = function (x, a, b) {
  92634. return (x < a) ? a : ((x > b) ? b : x);
  92635. }
  92636. OIMO.Euler.prototype = {
  92637. constructor: OIMO.Euler,
  92638. _x: 0, _y: 0, _z: 0, _order: OIMO.Euler.DefaultOrder,
  92639. get x() {
  92640. return this._x;
  92641. },
  92642. set x(value) {
  92643. this._x = value;
  92644. this.onChangeCallback();
  92645. },
  92646. get y() {
  92647. return this._y;
  92648. },
  92649. set y(value) {
  92650. this._y = value;
  92651. this.onChangeCallback();
  92652. },
  92653. get z() {
  92654. return this._z;
  92655. },
  92656. set z(value) {
  92657. this._z = value;
  92658. this.onChangeCallback();
  92659. },
  92660. get order() {
  92661. return this._order;
  92662. },
  92663. set order(value) {
  92664. this._order = value;
  92665. this.onChangeCallback();
  92666. },
  92667. set: function (x, y, z, order) {
  92668. this._x = x;
  92669. this._y = y;
  92670. this._z = z;
  92671. this._order = order || this._order;
  92672. this.onChangeCallback();
  92673. return this;
  92674. },
  92675. copy: function (euler) {
  92676. this._x = euler._x;
  92677. this._y = euler._y;
  92678. this._z = euler._z;
  92679. this._order = euler._order;
  92680. this.onChangeCallback();
  92681. return this;
  92682. },
  92683. setFromRotationMatrix: function (m, order) {
  92684. var clamp = OIMO.clamp;
  92685. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  92686. var te = m.elements;
  92687. /*var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  92688. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  92689. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];*/
  92690. var m11 = te[0], m12 = te[1], m13 = te[2],
  92691. m21 = te[3], m22 = te[4], m23 = te[5],
  92692. m31 = te[6], m32 = te[7], m33 = te[8];
  92693. order = order || this._order;
  92694. if (order === 'XYZ') {
  92695. this._y = OIMO.asin(clamp(m13, -1, 1));
  92696. if (OIMO.abs(m13) < 0.99999) {
  92697. this._x = OIMO.atan2(-m23, m33);
  92698. this._z = OIMO.atan2(-m12, m11);
  92699. } else {
  92700. this._x = OIMO.atan2(m32, m22);
  92701. this._z = 0;
  92702. }
  92703. } else if (order === 'YXZ') {
  92704. this._x = OIMO.asin(-clamp(m23, -1, 1));
  92705. if (OIMO.abs(m23) < 0.99999) {
  92706. this._y = OIMO.atan2(m13, m33);
  92707. this._z = OIMO.atan2(m21, m22);
  92708. } else {
  92709. this._y = OIMO.atan2(-m31, m11);
  92710. this._z = 0;
  92711. }
  92712. } else if (order === 'ZXY') {
  92713. this._x = OIMO.asin(clamp(m32, -1, 1));
  92714. if (OIMO.abs(m32) < 0.99999) {
  92715. this._y = OIMO.atan2(-m31, m33);
  92716. this._z = OIMO.atan2(-m12, m22);
  92717. } else {
  92718. this._y = 0;
  92719. this._z = OIMO.atan2(m21, m11);
  92720. }
  92721. } else if (order === 'ZYX') {
  92722. this._y = OIMO.asin(-clamp(m31, -1, 1));
  92723. if (OIMO.abs(m31) < 0.99999) {
  92724. this._x = OIMO.atan2(m32, m33);
  92725. this._z = OIMO.atan2(m21, m11);
  92726. } else {
  92727. this._x = 0;
  92728. this._z = OIMO.atan2(-m12, m22);
  92729. }
  92730. } else if (order === 'YZX') {
  92731. this._z = OIMO.asin(clamp(m21, -1, 1));
  92732. if (OIMO.abs(m21) < 0.99999) {
  92733. this._x = OIMO.atan2(-m23, m22);
  92734. this._y = OIMO.atan2(-m31, m11);
  92735. } else {
  92736. this._x = 0;
  92737. this._y = OIMO.atan2(m13, m33);
  92738. }
  92739. } else if (order === 'XZY') {
  92740. this._z = OIMO.asin(-clamp(m12, -1, 1));
  92741. if (OIMO.abs(m12) < 0.99999) {
  92742. this._x = OIMO.atan2(m32, m22);
  92743. this._y = OIMO.atan2(m13, m11);
  92744. } else {
  92745. this._x = OIMO.atan2(-m23, m33);
  92746. this._y = 0;
  92747. }
  92748. } else {
  92749. console.warn('THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order)
  92750. }
  92751. this._order = order;
  92752. this.onChangeCallback();
  92753. return this;
  92754. },
  92755. setFromQuaternion: function (q, order, update) {
  92756. var clamp = OIMO.clamp;
  92757. // q is assumed to be normalized
  92758. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  92759. var sqx = q.x * q.x;
  92760. var sqy = q.y * q.y;
  92761. var sqz = q.z * q.z;
  92762. var sqw = q.s * q.s;
  92763. order = order || this._order;
  92764. if (order === 'XYZ') {
  92765. this._x = OIMO.atan2(2 * (q.x * q.s - q.y * q.z), (sqw - sqx - sqy + sqz));
  92766. this._y = OIMO.asin(clamp(2 * (q.x * q.z + q.y * q.s), -1, 1));
  92767. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw + sqx - sqy - sqz));
  92768. } else if (order === 'YXZ') {
  92769. this._x = OIMO.asin(clamp(2 * (q.x * q.s - q.y * q.z), -1, 1));
  92770. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw - sqx - sqy + sqz));
  92771. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw - sqx + sqy - sqz));
  92772. } else if (order === 'ZXY') {
  92773. this._x = OIMO.asin(clamp(2 * (q.x * q.s + q.y * q.z), -1, 1));
  92774. this._y = OIMO.atan2(2 * (q.y * q.s - q.z * q.x), (sqw - sqx - sqy + sqz));
  92775. this._z = OIMO.atan2(2 * (q.z * q.s - q.x * q.y), (sqw - sqx + sqy - sqz));
  92776. } else if (order === 'ZYX') {
  92777. this._x = OIMO.atan2(2 * (q.x * q.s + q.z * q.y), (sqw - sqx - sqy + sqz));
  92778. this._y = OIMO.asin(clamp(2 * (q.y * q.s - q.x * q.z), -1, 1));
  92779. this._z = OIMO.atan2(2 * (q.x * q.y + q.z * q.s), (sqw + sqx - sqy - sqz));
  92780. } else if (order === 'YZX') {
  92781. this._x = OIMO.atan2(2 * (q.x * q.s - q.z * q.y), (sqw - sqx + sqy - sqz));
  92782. this._y = OIMO.atan2(2 * (q.y * q.s - q.x * q.z), (sqw + sqx - sqy - sqz));
  92783. this._z = OIMO.asin(clamp(2 * (q.x * q.y + q.z * q.s), -1, 1));
  92784. } else if (order === 'XZY') {
  92785. this._x = OIMO.atan2(2 * (q.x * q.s + q.y * q.z), (sqw - sqx + sqy - sqz));
  92786. this._y = OIMO.atan2(2 * (q.x * q.z + q.y * q.s), (sqw + sqx - sqy - sqz));
  92787. this._z = OIMO.asin(clamp(2 * (q.z * q.s - q.x * q.y), -1, 1));
  92788. } else {
  92789. console.warn('OIMO.Euler: .setFromQuaternion() given unsupported order: ' + order)
  92790. }
  92791. this._order = order;
  92792. if (update !== false) this.onChangeCallback();
  92793. return this;
  92794. },
  92795. reorder: function () {
  92796. // WARNING: this discards revolution information -bhouston
  92797. var q = new OIMO.Quat();
  92798. return function (newOrder) {
  92799. q.setFromEuler(this);
  92800. this.setFromQuaternion(q, newOrder);
  92801. };
  92802. }(),
  92803. equals: function (euler) {
  92804. return (euler._x === this._x) && (euler._y === this._y) && (euler._z === this._z) && (euler._order === this._order);
  92805. },
  92806. fromArray: function (array) {
  92807. this._x = array[0];
  92808. this._y = array[1];
  92809. this._z = array[2];
  92810. if (array[3] !== undefined) this._order = array[3];
  92811. this.onChangeCallback();
  92812. return this;
  92813. },
  92814. toArray: function () {
  92815. return [this._x, this._y, this._z, this._order];
  92816. },
  92817. onChange: function (callback) {
  92818. this.onChangeCallback = callback;
  92819. return this;
  92820. },
  92821. onChangeCallback: function () { },
  92822. clone: function () {
  92823. return new OIMO.Euler(this._x, this._y, this._z, this._order);
  92824. }
  92825. };
  92826. OIMO.EulerToAxis = function (ox, oy, oz) {// angles in radians
  92827. var c1 = OIMO.cos(oy * 0.5);//heading
  92828. var s1 = OIMO.sin(oy * 0.5);
  92829. var c2 = OIMO.cos(oz * 0.5);//altitude
  92830. var s2 = OIMO.sin(oz * 0.5);
  92831. var c3 = OIMO.cos(ox * 0.5);//bank
  92832. var s3 = OIMO.sin(ox * 0.5);
  92833. var c1c2 = c1 * c2;
  92834. var s1s2 = s1 * s2;
  92835. var w = c1c2 * c3 - s1s2 * s3;
  92836. var x = c1c2 * s3 + s1s2 * c3;
  92837. var y = s1 * c2 * c3 + c1 * s2 * s3;
  92838. var z = c1 * s2 * c3 - s1 * c2 * s3;
  92839. var angle = 2 * OIMO.acos(w);
  92840. var norm = x * x + y * y + z * z;
  92841. if (norm < 0.001) {
  92842. x = 1;
  92843. y = z = 0;
  92844. } else {
  92845. norm = OIMO.sqrt(norm);
  92846. x /= norm;
  92847. y /= norm;
  92848. z /= norm;
  92849. }
  92850. return [angle, x, y, z];
  92851. }
  92852. OIMO.EulerToMatrix = function (ox, oy, oz) {// angles in radians
  92853. var ch = OIMO.cos(oy);//heading
  92854. var sh = OIMO.sin(oy);
  92855. var ca = OIMO.cos(oz);//altitude
  92856. var sa = OIMO.sin(oz);
  92857. var cb = OIMO.cos(ox);//bank
  92858. var sb = OIMO.sin(ox);
  92859. var mtx = new OIMO.Mat33();
  92860. var te = mtx.elements;
  92861. te[0] = ch * ca;
  92862. te[1] = sh * sb - ch * sa * cb;
  92863. te[2] = ch * sa * sb + sh * cb;
  92864. te[3] = sa;
  92865. te[4] = ca * cb;
  92866. te[5] = -ca * sb;
  92867. te[6] = -sh * ca;
  92868. te[7] = sh * sa * cb + ch * sb;
  92869. te[8] = -sh * sa * sb + ch * cb;
  92870. return mtx;
  92871. }
  92872. OIMO.MatrixToEuler = function (mtx) {// angles in radians
  92873. var te = mtx.elements;
  92874. var x, y, z;
  92875. if (te[3] > 0.998) { // singularity at north pole
  92876. y = OIMO.atan2(te[2], te[8]);
  92877. z = OIMO.PI / 2;
  92878. x = 0;
  92879. } else if (te[3] < -0.998) { // singularity at south pole
  92880. y = OIMO.atan2(te[2], te[8]);
  92881. z = -OIMO.PI / 2;
  92882. x = 0;
  92883. } else {
  92884. y = OIMO.atan2(-te[6], te[0]);
  92885. x = OIMO.atan2(-te[5], te[4]);
  92886. z = OIMO.asin(te[3]);
  92887. }
  92888. return [x, y, z];
  92889. }
  92890. OIMO.unwrapDegrees = function (r) {
  92891. r = r % 360;
  92892. if (r > 180) r -= 360;
  92893. if (r < -180) r += 360;
  92894. return r;
  92895. }
  92896. OIMO.unwrapRadian = function (r) {
  92897. r = r % OIMO.TwoPI;
  92898. if (r > OIMO.PI) r -= OIMO.TwoPI;
  92899. if (r < -OIMO.PI) r += OIMO.TwoPI;
  92900. return r;
  92901. }
  92902. OIMO.Distance3d = function (p1, p2) {
  92903. var xd = p2[0] - p1[0];
  92904. var yd = p2[1] - p1[1];
  92905. var zd = p2[2] - p1[2];
  92906. return OIMO.sqrt(xd * xd + yd * yd + zd * zd);
  92907. }
  92908. /**
  92909. * The base class of all type of the constraints.
  92910. * @author saharan
  92911. */
  92912. OIMO.Constraint = function () {
  92913. // The parent world of the constraint.
  92914. this.parent = null;
  92915. // The first body of the constraint.
  92916. this.body1 = null;
  92917. // The second body of the constraint.
  92918. this.body2 = null;
  92919. // Internal
  92920. this.addedToIsland = false;
  92921. }
  92922. OIMO.Constraint.prototype = {
  92923. constructor: OIMO.Constraint,
  92924. /**
  92925. * Prepare for solving the constraint.
  92926. * @param timeStep
  92927. * @param invTimeStep
  92928. */
  92929. preSolve: function (timeStep, invTimeStep) {
  92930. OIMO.Error("Constraint", "Inheritance error.");
  92931. },
  92932. /**
  92933. * Solve the constraint.
  92934. * This is usually called iteratively.
  92935. */
  92936. solve: function () {
  92937. OIMO.Error("Constraint", "Inheritance error.");
  92938. },
  92939. /**
  92940. * Do the post-processing.
  92941. */
  92942. postSolve: function () {
  92943. OIMO.Error("Constraint", "Inheritance error.");
  92944. }
  92945. }
  92946. /**
  92947. * Joints are used to constrain the motion between two rigid bodies.
  92948. * @author saharan
  92949. * @author lo-th
  92950. */
  92951. OIMO.Joint = function (config) {
  92952. OIMO.Constraint.call(this);
  92953. // joint name
  92954. this.name = "";
  92955. // The type of the joint.
  92956. this.type = OIMO.JOINT_NULL;
  92957. // The previous joint in the world.
  92958. this.prev = null;
  92959. // The next joint in the world.
  92960. this.next = null;
  92961. this.body1 = config.body1;
  92962. this.body2 = config.body2;
  92963. // The anchor point on the first rigid body in local coordinate system.
  92964. this.localAnchorPoint1 = new OIMO.Vec3().copy(config.localAnchorPoint1);
  92965. // The anchor point on the second rigid body in local coordinate system.
  92966. this.localAnchorPoint2 = new OIMO.Vec3().copy(config.localAnchorPoint2);
  92967. // The anchor point on the first rigid body in world coordinate system relative to the body's origin.
  92968. this.relativeAnchorPoint1 = new OIMO.Vec3();
  92969. // The anchor point on the second rigid body in world coordinate system relative to the body's origin.
  92970. this.relativeAnchorPoint2 = new OIMO.Vec3();
  92971. // The anchor point on the first rigid body in world coordinate system.
  92972. this.anchorPoint1 = new OIMO.Vec3();
  92973. // The anchor point on the second rigid body in world coordinate system.
  92974. this.anchorPoint2 = new OIMO.Vec3();
  92975. // Whether allow collision between connected rigid bodies or not.
  92976. this.allowCollision = config.allowCollision;
  92977. this.b1Link = new OIMO.JointLink(this);
  92978. this.b2Link = new OIMO.JointLink(this);
  92979. this.matrix = new OIMO.Mat44();
  92980. };
  92981. OIMO.Joint.prototype = Object.create(OIMO.Constraint.prototype);
  92982. OIMO.Joint.prototype.constructor = OIMO.Joint;
  92983. // Update all the anchor points.
  92984. OIMO.Joint.prototype.updateAnchorPoints = function () {
  92985. this.relativeAnchorPoint1.mulMat(this.body1.rotation, this.localAnchorPoint1);
  92986. this.relativeAnchorPoint2.mulMat(this.body2.rotation, this.localAnchorPoint2);
  92987. this.anchorPoint1.add(this.relativeAnchorPoint1, this.body1.position);
  92988. this.anchorPoint2.add(this.relativeAnchorPoint2, this.body2.position);
  92989. };
  92990. // Attach the joint from the bodies.
  92991. OIMO.Joint.prototype.attach = function () {
  92992. this.b1Link.body = this.body2;
  92993. this.b2Link.body = this.body1;
  92994. if (this.body1.jointLink != null) (this.b1Link.next = this.body1.jointLink).prev = this.b1Link;
  92995. else this.b1Link.next = null;
  92996. this.body1.jointLink = this.b1Link;
  92997. this.body1.numJoints++;
  92998. if (this.body2.jointLink != null) (this.b2Link.next = this.body2.jointLink).prev = this.b2Link;
  92999. else this.b2Link.next = null;
  93000. this.body2.jointLink = this.b2Link;
  93001. this.body2.numJoints++;
  93002. };
  93003. // Detach the joint from the bodies.
  93004. OIMO.Joint.prototype.detach = function () {
  93005. var prev = this.b1Link.prev;
  93006. var next = this.b1Link.next;
  93007. if (prev != null) prev.next = next;
  93008. if (next != null) next.prev = prev;
  93009. if (this.body1.jointLink == this.b1Link) this.body1.jointLink = next;
  93010. this.b1Link.prev = null;
  93011. this.b1Link.next = null;
  93012. this.b1Link.body = null;
  93013. this.body1.numJoints--;
  93014. prev = this.b2Link.prev;
  93015. next = this.b2Link.next;
  93016. if (prev != null) prev.next = next;
  93017. if (next != null) next.prev = prev;
  93018. if (this.body2.jointLink == this.b2Link) this.body2.jointLink = next;
  93019. this.b2Link.prev = null;
  93020. this.b2Link.next = null;
  93021. this.b2Link.body = null;
  93022. this.body2.numJoints--;
  93023. this.b1Link.body = null;
  93024. this.b2Link.body = null;
  93025. };
  93026. // Awake the bodies.
  93027. OIMO.Joint.prototype.awake = function () {
  93028. this.body1.awake();
  93029. this.body2.awake();
  93030. };
  93031. // calculation function
  93032. OIMO.Joint.prototype.preSolve = function (timeStep, invTimeStep) {
  93033. };
  93034. OIMO.Joint.prototype.solve = function () {
  93035. };
  93036. OIMO.Joint.prototype.postSolve = function () {
  93037. };
  93038. // Delete process
  93039. OIMO.Joint.prototype.remove = function () {
  93040. this.dispose();
  93041. };
  93042. OIMO.Joint.prototype.dispose = function () {
  93043. this.parent.removeJoint(this);
  93044. };
  93045. // Three js add
  93046. OIMO.Joint.prototype.getPosition = function () {
  93047. var p1 = new OIMO.Vec3().scale(this.anchorPoint1, OIMO.WORLD_SCALE);
  93048. var p2 = new OIMO.Vec3().scale(this.anchorPoint2, OIMO.WORLD_SCALE);
  93049. return [p1, p2];
  93050. };
  93051. OIMO.Joint.prototype.getMatrix = function () {
  93052. var m = this.matrix.elements;
  93053. var p1 = this.anchorPoint1;
  93054. var p2 = this.anchorPoint2;
  93055. m[0] = p1.x * OIMO.WORLD_SCALE;
  93056. m[1] = p1.y * OIMO.WORLD_SCALE;
  93057. m[2] = p1.z * OIMO.WORLD_SCALE;
  93058. m[3] = 0;
  93059. m[4] = p2.x * OIMO.WORLD_SCALE;
  93060. m[5] = p2.y * OIMO.WORLD_SCALE;
  93061. m[6] = p2.z * OIMO.WORLD_SCALE;
  93062. m[7] = 0;
  93063. return m;
  93064. };
  93065. /**
  93066. * A joint configuration holds all configuration data for constructing a joint.
  93067. * Joint configurations can be reused safely.
  93068. * @author saharan
  93069. */
  93070. OIMO.JointConfig = function () {
  93071. // The first rigid body of the joint.
  93072. this.body1 = null;
  93073. // The second rigid body of the joint.
  93074. this.body2 = null;
  93075. // The anchor point on the first rigid body in local coordinate system.
  93076. this.localAnchorPoint1 = new OIMO.Vec3();
  93077. // The anchor point on the second rigid body in local coordinate system.
  93078. this.localAnchorPoint2 = new OIMO.Vec3();
  93079. // The axis in the first body's coordinate system.
  93080. // his property is available in some joints.
  93081. this.localAxis1 = new OIMO.Vec3();
  93082. // The axis in the second body's coordinate system.
  93083. // This property is available in some joints.
  93084. this.localAxis2 = new OIMO.Vec3();
  93085. // Whether allow collision between connected rigid bodies or not.
  93086. this.allowCollision = false;
  93087. };
  93088. /**
  93089. * A link list of joints.
  93090. * @author saharan
  93091. */
  93092. OIMO.JointLink = function (joint) {
  93093. // The previous joint link.
  93094. this.prev = null;
  93095. // The next joint link.
  93096. this.next = null;
  93097. // The other rigid body connected to the joint.
  93098. this.body = null;
  93099. // The joint of the link.
  93100. this.joint = joint;
  93101. };
  93102. /**
  93103. * An information of limit and motor.
  93104. * @author saharan
  93105. */
  93106. OIMO.LimitMotor = function (axis, fixed) {
  93107. fixed = fixed || false;
  93108. // The axis of the constraint.
  93109. this.axis = axis;
  93110. // The current angle for rotational constraints.
  93111. this.angle = 0;
  93112. // The lower limit. Set lower > upper to disable
  93113. this.lowerLimit = fixed ? 0 : 1;
  93114. //if(fixed)this.lowerLimit = 0;
  93115. //else this.lowerLimit = 1;
  93116. // The upper limit. Set lower > upper to disable.
  93117. this.upperLimit = 0;
  93118. // The target motor speed.
  93119. this.motorSpeed = 0;
  93120. // The maximum motor force or torque. Set 0 to disable.
  93121. this.maxMotorForce = 0;
  93122. // The frequency of the spring. Set 0 to disable.
  93123. this.frequency = 0;
  93124. // The damping ratio of the spring. Set 0 for no damping, 1 for critical damping.
  93125. this.dampingRatio = 0;
  93126. };
  93127. OIMO.LimitMotor.prototype = {
  93128. constructor: OIMO.LimitMotor,
  93129. /**
  93130. * Set limit data into this constraint.
  93131. * @param lowerLimit
  93132. * @param upperLimit
  93133. */
  93134. setLimit: function (lowerLimit, upperLimit) {
  93135. this.lowerLimit = lowerLimit;
  93136. this.upperLimit = upperLimit;
  93137. },
  93138. /**
  93139. * Set motor data into this constraint.
  93140. * @param motorSpeed
  93141. * @param maxMotorForce
  93142. */
  93143. setMotor: function (motorSpeed, maxMotorForce) {
  93144. this.motorSpeed = motorSpeed;
  93145. this.maxMotorForce = maxMotorForce;
  93146. },
  93147. /**
  93148. * Set spring data into this constraint.
  93149. * @param frequency
  93150. * @param dampingRatio
  93151. */
  93152. setSpring: function (frequency, dampingRatio) {
  93153. this.frequency = frequency;
  93154. this.dampingRatio = dampingRatio;
  93155. }
  93156. };
  93157. /**
  93158. * A ball-and-socket joint limits relative translation on two anchor points on rigid bodies.
  93159. * @author saharan
  93160. * @author lo-th
  93161. */
  93162. OIMO.BallAndSocketJoint = function (config) {
  93163. OIMO.Joint.call(this, config);
  93164. this.type = OIMO.JOINT_BALL_AND_SOCKET;
  93165. this.lc = new OIMO.LinearConstraint(this);
  93166. };
  93167. OIMO.BallAndSocketJoint.prototype = Object.create(OIMO.Joint.prototype);
  93168. OIMO.BallAndSocketJoint.prototype.constructor = OIMO.BallAndSocketJoint;
  93169. OIMO.BallAndSocketJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93170. this.updateAnchorPoints();
  93171. this.lc.preSolve(timeStep, invTimeStep);
  93172. };
  93173. OIMO.BallAndSocketJoint.prototype.solve = function () {
  93174. this.lc.solve();
  93175. };
  93176. OIMO.BallAndSocketJoint.prototype.postSolve = function () {
  93177. };
  93178. /**
  93179. * A distance joint limits the distance between two anchor points on rigid bodies.
  93180. * @author saharan
  93181. * @author lo-th
  93182. */
  93183. OIMO.DistanceJoint = function (config, minDistance, maxDistance) {
  93184. OIMO.Joint.call(this, config);
  93185. this.type = OIMO.JOINT_DISTANCE;
  93186. this.normal = new OIMO.Vec3();
  93187. this.nr = new OIMO.Vec3();
  93188. // The limit and motor information of the joint.
  93189. this.limitMotor = new OIMO.LimitMotor(this.normal, true);
  93190. this.limitMotor.lowerLimit = minDistance;
  93191. this.limitMotor.upperLimit = maxDistance;
  93192. this.t = new OIMO.TranslationalConstraint(this, this.limitMotor);
  93193. };
  93194. OIMO.DistanceJoint.prototype = Object.create(OIMO.Joint.prototype);
  93195. OIMO.DistanceJoint.prototype.constructor = OIMO.DistanceJoint;
  93196. OIMO.DistanceJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93197. this.updateAnchorPoints();
  93198. //var nr = this.nr;
  93199. this.nr.sub(this.anchorPoint2, this.anchorPoint1);
  93200. //var len = OIMO.sqrt( nr.x*nr.x + nr.y*nr.y + nr.z*nr.z );
  93201. //if(len>0) len = 1/len;
  93202. //this.normal.scale( nr, len );
  93203. this.normal.normalize(this.nr);
  93204. this.t.preSolve(timeStep, invTimeStep);
  93205. };
  93206. OIMO.DistanceJoint.prototype.solve = function () {
  93207. this.t.solve();
  93208. };
  93209. OIMO.DistanceJoint.prototype.postSolve = function () {
  93210. };
  93211. /**
  93212. * A hinge joint allows only for relative rotation of rigid bodies along the axis.
  93213. * @author saharan
  93214. * @author lo-th
  93215. */
  93216. OIMO.HingeJoint = function (config, lowerAngleLimit, upperAngleLimit) {
  93217. OIMO.Joint.call(this, config);
  93218. this.type = OIMO.JOINT_HINGE;
  93219. // The axis in the first body's coordinate system.
  93220. this.localAxis1 = config.localAxis1.clone().norm();
  93221. // The axis in the second body's coordinate system.
  93222. this.localAxis2 = config.localAxis2.clone().norm();
  93223. // make angle axis 1
  93224. this.localAngle1 = new OIMO.Vec3(
  93225. this.localAxis1.y * this.localAxis1.x - this.localAxis1.z * this.localAxis1.z,
  93226. -this.localAxis1.z * this.localAxis1.y - this.localAxis1.x * this.localAxis1.x,
  93227. this.localAxis1.x * this.localAxis1.z + this.localAxis1.y * this.localAxis1.y
  93228. ).norm();
  93229. // make angle axis 2
  93230. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  93231. this.localAngle2 = new OIMO.Vec3().mulMat(arc, this.localAngle1);
  93232. this.nor = new OIMO.Vec3();
  93233. this.tan = new OIMO.Vec3();
  93234. this.bin = new OIMO.Vec3();
  93235. this.ax1 = new OIMO.Vec3();
  93236. this.ax2 = new OIMO.Vec3();
  93237. this.an1 = new OIMO.Vec3();
  93238. this.an2 = new OIMO.Vec3();
  93239. // The rotational limit and motor information of the joint.
  93240. this.limitMotor = new OIMO.LimitMotor(this.nor, false);
  93241. this.limitMotor.lowerLimit = lowerAngleLimit;
  93242. this.limitMotor.upperLimit = upperAngleLimit;
  93243. this.lc = new OIMO.LinearConstraint(this);
  93244. this.r3 = new OIMO.Rotational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  93245. };
  93246. OIMO.HingeJoint.prototype = Object.create(OIMO.Joint.prototype);
  93247. OIMO.HingeJoint.prototype.constructor = OIMO.HingeJoint;
  93248. OIMO.HingeJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93249. var tmp1X, tmp1Y, tmp1Z, limite;//, nx, ny, nz, tx, ty, tz, bx, by, bz;
  93250. this.updateAnchorPoints();
  93251. this.ax1.mulMat(this.body1.rotation, this.localAxis1);
  93252. this.ax2.mulMat(this.body2.rotation, this.localAxis2);
  93253. this.an1.mulMat(this.body1.rotation, this.localAngle1);
  93254. this.an2.mulMat(this.body2.rotation, this.localAngle2);
  93255. this.nor.set(
  93256. this.ax1.x * this.body2.inverseMass + this.ax2.x * this.body1.inverseMass,
  93257. this.ax1.y * this.body2.inverseMass + this.ax2.y * this.body1.inverseMass,
  93258. this.ax1.z * this.body2.inverseMass + this.ax2.z * this.body1.inverseMass
  93259. ).norm();
  93260. this.tan.set(
  93261. this.nor.y * this.nor.x - this.nor.z * this.nor.z,
  93262. -this.nor.z * this.nor.y - this.nor.x * this.nor.x,
  93263. this.nor.x * this.nor.z + this.nor.y * this.nor.y
  93264. ).norm();
  93265. this.bin.set(
  93266. this.nor.y * this.tan.z - this.nor.z * this.tan.y,
  93267. this.nor.z * this.tan.x - this.nor.x * this.tan.z,
  93268. this.nor.x * this.tan.y - this.nor.y * this.tan.x
  93269. );
  93270. // calculate hinge angle
  93271. limite = this.acosClamp(this.an1.x * this.an2.x + this.an1.y * this.an2.y + this.an1.z * this.an2.z)
  93272. if (
  93273. this.nor.x * (this.an1.y * this.an2.z - this.an1.z * this.an2.y) +
  93274. this.nor.y * (this.an1.z * this.an2.x - this.an1.x * this.an2.z) +
  93275. this.nor.z * (this.an1.x * this.an2.y - this.an1.y * this.an2.x) < 0
  93276. ) {
  93277. this.limitMotor.angle = -limite;
  93278. } else {
  93279. this.limitMotor.angle = limite;
  93280. }
  93281. tmp1X = this.ax1.y * this.ax2.z - this.ax1.z * this.ax2.y;
  93282. tmp1Y = this.ax1.z * this.ax2.x - this.ax1.x * this.ax2.z;
  93283. tmp1Z = this.ax1.x * this.ax2.y - this.ax1.y * this.ax2.x;
  93284. this.r3.limitMotor2.angle = this.tan.x * tmp1X + this.tan.y * tmp1Y + this.tan.z * tmp1Z;
  93285. this.r3.limitMotor3.angle = this.bin.x * tmp1X + this.bin.y * tmp1Y + this.bin.z * tmp1Z;
  93286. this.r3.preSolve(timeStep, invTimeStep);
  93287. this.lc.preSolve(timeStep, invTimeStep);
  93288. };
  93289. OIMO.HingeJoint.prototype.solve = function () {
  93290. this.r3.solve();
  93291. this.lc.solve();
  93292. };
  93293. OIMO.HingeJoint.prototype.postSolve = function () {
  93294. };
  93295. OIMO.HingeJoint.prototype.acosClamp = function (cos) {
  93296. if (cos > 1) return 0;
  93297. else if (cos < -1) return OIMO.PI;
  93298. else return OIMO.acos(cos);
  93299. };
  93300. /**
  93301. * A prismatic joint allows only for relative translation of rigid bodies along the axis.
  93302. * @author saharan
  93303. * @author lo-th
  93304. */
  93305. OIMO.PrismaticJoint = function (config, lowerTranslation, upperTranslation) {
  93306. OIMO.Joint.call(this, config);
  93307. this.type = OIMO.JOINT_PRISMATIC;
  93308. // The axis in the first body's coordinate system.
  93309. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  93310. // The axis in the second body's coordinate system.
  93311. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  93312. this.localAxis1X = this.localAxis1.x;
  93313. this.localAxis1Y = this.localAxis1.y;
  93314. this.localAxis1Z = this.localAxis1.z;
  93315. this.localAxis2X = this.localAxis2.x;
  93316. this.localAxis2Y = this.localAxis2.y;
  93317. this.localAxis2Z = this.localAxis2.z;
  93318. this.nor = new OIMO.Vec3();
  93319. this.tan = new OIMO.Vec3();
  93320. this.bin = new OIMO.Vec3();
  93321. this.ac = new OIMO.AngularConstraint(this, new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  93322. // The translational limit and motor information of the joint.
  93323. this.limitMotor = new OIMO.LimitMotor(this.nor, true);
  93324. this.limitMotor.lowerLimit = lowerTranslation;
  93325. this.limitMotor.upperLimit = upperTranslation;
  93326. this.t3 = new OIMO.Translational3Constraint(this, this.limitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  93327. };
  93328. OIMO.PrismaticJoint.prototype = Object.create(OIMO.Joint.prototype);
  93329. OIMO.PrismaticJoint.prototype.constructor = OIMO.PrismaticJoint;
  93330. OIMO.PrismaticJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93331. var tmpM;
  93332. var tmp1X;
  93333. var tmp1Y;
  93334. var tmp1Z;
  93335. this.updateAnchorPoints();
  93336. tmpM = this.body1.rotation.elements;
  93337. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  93338. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  93339. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  93340. tmpM = this.body2.rotation.elements;
  93341. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  93342. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  93343. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  93344. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  93345. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  93346. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  93347. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  93348. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93349. nx *= tmp1X;
  93350. ny *= tmp1X;
  93351. nz *= tmp1X;
  93352. var tx = ny * nx - nz * nz;
  93353. var ty = -nz * ny - nx * nx;
  93354. var tz = nx * nz + ny * ny;
  93355. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  93356. tx *= tmp1X;
  93357. ty *= tmp1X;
  93358. tz *= tmp1X;
  93359. var bx = ny * tz - nz * ty;
  93360. var by = nz * tx - nx * tz;
  93361. var bz = nx * ty - ny * tx;
  93362. this.nor.init(nx, ny, nz);
  93363. this.tan.init(tx, ty, tz);
  93364. this.bin.init(bx, by, bz);
  93365. this.ac.preSolve(timeStep, invTimeStep);
  93366. this.t3.preSolve(timeStep, invTimeStep);
  93367. };
  93368. OIMO.PrismaticJoint.prototype.solve = function () {
  93369. this.ac.solve();
  93370. this.t3.solve();
  93371. };
  93372. OIMO.PrismaticJoint.prototype.postSolve = function () {
  93373. };
  93374. /**
  93375. * A slider joint allows for relative translation and relative rotation between two rigid bodies along the axis.
  93376. * @author saharan
  93377. * @author lo-th
  93378. */
  93379. OIMO.SliderJoint = function (config, lowerTranslation, upperTranslation) {
  93380. OIMO.Joint.call(this, config);
  93381. this.type = OIMO.JOINT_SLIDER;
  93382. // The first axis in local coordinate system.
  93383. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  93384. // The second axis in local coordinate system.
  93385. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  93386. var len;
  93387. this.localAxis1X = this.localAxis1.x;
  93388. this.localAxis1Y = this.localAxis1.y;
  93389. this.localAxis1Z = this.localAxis1.z;
  93390. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  93391. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  93392. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  93393. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  93394. this.localAngAxis1X *= len;
  93395. this.localAngAxis1Y *= len;
  93396. this.localAngAxis1Z *= len;
  93397. this.localAxis2X = this.localAxis2.x;
  93398. this.localAxis2Y = this.localAxis2.y;
  93399. this.localAxis2Z = this.localAxis2.z;
  93400. // make angle axis 2
  93401. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  93402. var tarc = arc.elements;
  93403. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  93404. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  93405. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  93406. this.nor = new OIMO.Vec3();
  93407. this.tan = new OIMO.Vec3();
  93408. this.bin = new OIMO.Vec3();
  93409. // The limit and motor for the rotation
  93410. this.rotationalLimitMotor = new OIMO.LimitMotor(this.nor, false);
  93411. this.r3 = new OIMO.Rotational3Constraint(this, this.rotationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  93412. // The limit and motor for the translation.
  93413. this.translationalLimitMotor = new OIMO.LimitMotor(this.nor, true);
  93414. this.translationalLimitMotor.lowerLimit = lowerTranslation;
  93415. this.translationalLimitMotor.upperLimit = upperTranslation;
  93416. this.t3 = new OIMO.Translational3Constraint(this, this.translationalLimitMotor, new OIMO.LimitMotor(this.tan, true), new OIMO.LimitMotor(this.bin, true));
  93417. };
  93418. OIMO.SliderJoint.prototype = Object.create(OIMO.Joint.prototype);
  93419. OIMO.SliderJoint.prototype.constructor = OIMO.SliderJoint;
  93420. OIMO.SliderJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93421. var tmpM;
  93422. var tmp1X;
  93423. var tmp1Y;
  93424. var tmp1Z;
  93425. this.updateAnchorPoints();
  93426. tmpM = this.body1.rotation.elements;
  93427. var axis1X = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  93428. var axis1Y = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  93429. var axis1Z = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  93430. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  93431. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  93432. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  93433. tmpM = this.body2.rotation.elements;
  93434. var axis2X = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  93435. var axis2Y = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  93436. var axis2Z = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  93437. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  93438. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  93439. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  93440. var nx = axis1X * this.body2.inverseMass + axis2X * this.body1.inverseMass;
  93441. var ny = axis1Y * this.body2.inverseMass + axis2Y * this.body1.inverseMass;
  93442. var nz = axis1Z * this.body2.inverseMass + axis2Z * this.body1.inverseMass;
  93443. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  93444. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93445. nx *= tmp1X;
  93446. ny *= tmp1X;
  93447. nz *= tmp1X;
  93448. var tx = ny * nx - nz * nz;
  93449. var ty = -nz * ny - nx * nx;
  93450. var tz = nx * nz + ny * ny;
  93451. tmp1X = 1 / OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  93452. tx *= tmp1X;
  93453. ty *= tmp1X;
  93454. tz *= tmp1X;
  93455. var bx = ny * tz - nz * ty;
  93456. var by = nz * tx - nx * tz;
  93457. var bz = nx * ty - ny * tx;
  93458. this.nor.init(nx, ny, nz);
  93459. this.tan.init(tx, ty, tz);
  93460. this.bin.init(bx, by, bz);
  93461. // ----------------------------------------------
  93462. // calculate hinge angle
  93463. // ----------------------------------------------
  93464. if (
  93465. nx * (angAxis1Y * angAxis2Z - angAxis1Z * angAxis2Y) +
  93466. ny * (angAxis1Z * angAxis2X - angAxis1X * angAxis2Z) +
  93467. nz * (angAxis1X * angAxis2Y - angAxis1Y * angAxis2X) < 0
  93468. ) {
  93469. this.rotationalLimitMotor.angle = -this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  93470. } else {
  93471. this.rotationalLimitMotor.angle = this.acosClamp(angAxis1X * angAxis2X + angAxis1Y * angAxis2Y + angAxis1Z * angAxis2Z);
  93472. }
  93473. // angular error
  93474. tmp1X = axis1Y * axis2Z - axis1Z * axis2Y;
  93475. tmp1Y = axis1Z * axis2X - axis1X * axis2Z;
  93476. tmp1Z = axis1X * axis2Y - axis1Y * axis2X;
  93477. this.r3.limitMotor2.angle = tx * tmp1X + ty * tmp1Y + tz * tmp1Z;
  93478. this.r3.limitMotor3.angle = bx * tmp1X + by * tmp1Y + bz * tmp1Z;
  93479. this.r3.preSolve(timeStep, invTimeStep);
  93480. this.t3.preSolve(timeStep, invTimeStep);
  93481. };
  93482. OIMO.SliderJoint.prototype.solve = function () {
  93483. this.r3.solve();
  93484. this.t3.solve();
  93485. };
  93486. OIMO.SliderJoint.prototype.postSolve = function () {
  93487. };
  93488. OIMO.SliderJoint.prototype.acosClamp = function (cos) {
  93489. if (cos > 1) return 0;
  93490. else if (cos < -1) return OIMO.PI;
  93491. else return OIMO.acos(cos);
  93492. };
  93493. /**
  93494. * A wheel joint allows for relative rotation between two rigid bodies along two axes.
  93495. * The wheel joint also allows for relative translation for the suspension.
  93496. * @author saharan
  93497. * @author lo-th
  93498. */
  93499. OIMO.WheelJoint = function (config) {
  93500. OIMO.Joint.call(this, config);
  93501. this.type = OIMO.JOINT_WHEEL;
  93502. // The first axis in local coordinate system.
  93503. this.localAxis1 = new OIMO.Vec3().normalize(config.localAxis1);
  93504. // The second axis in local coordinate system.
  93505. this.localAxis2 = new OIMO.Vec3().normalize(config.localAxis2);
  93506. var len;
  93507. this.localAxis1X = this.localAxis1.x;
  93508. this.localAxis1Y = this.localAxis1.y;
  93509. this.localAxis1Z = this.localAxis1.z;
  93510. this.localAxis2X = this.localAxis2.x;
  93511. this.localAxis2Y = this.localAxis2.y;
  93512. this.localAxis2Z = this.localAxis2.z;
  93513. var dot = this.localAxis1X * this.localAxis2X + this.localAxis1Y * this.localAxis2Y + this.localAxis1Z * this.localAxis2Z;
  93514. if (dot > -1 && dot < 1) {
  93515. this.localAngAxis1X = this.localAxis2X - dot * this.localAxis1X;
  93516. this.localAngAxis1Y = this.localAxis2Y - dot * this.localAxis1Y;
  93517. this.localAngAxis1Z = this.localAxis2Z - dot * this.localAxis1Z;
  93518. this.localAngAxis2X = this.localAxis1X - dot * this.localAxis2X;
  93519. this.localAngAxis2Y = this.localAxis1Y - dot * this.localAxis2Y;
  93520. this.localAngAxis2Z = this.localAxis1Z - dot * this.localAxis2Z;
  93521. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  93522. this.localAngAxis1X *= len;
  93523. this.localAngAxis1Y *= len;
  93524. this.localAngAxis1Z *= len;
  93525. len = 1 / OIMO.sqrt(this.localAngAxis2X * this.localAngAxis2X + this.localAngAxis2Y * this.localAngAxis2Y + this.localAngAxis2Z * this.localAngAxis2Z);
  93526. this.localAngAxis2X *= len;
  93527. this.localAngAxis2Y *= len;
  93528. this.localAngAxis2Z *= len;
  93529. } else {
  93530. this.localAngAxis1X = this.localAxis1Y * this.localAxis1X - this.localAxis1Z * this.localAxis1Z;
  93531. this.localAngAxis1Y = -this.localAxis1Z * this.localAxis1Y - this.localAxis1X * this.localAxis1X;
  93532. this.localAngAxis1Z = this.localAxis1X * this.localAxis1Z + this.localAxis1Y * this.localAxis1Y;
  93533. len = 1 / OIMO.sqrt(this.localAngAxis1X * this.localAngAxis1X + this.localAngAxis1Y * this.localAngAxis1Y + this.localAngAxis1Z * this.localAngAxis1Z);
  93534. this.localAngAxis1X *= len;
  93535. this.localAngAxis1Y *= len;
  93536. this.localAngAxis1Z *= len;
  93537. var arc = new OIMO.Mat33().setQuat(new OIMO.Quat().arc(this.localAxis1, this.localAxis2));
  93538. var tarc = arc.elements;
  93539. this.localAngAxis2X = this.localAngAxis1X * tarc[0] + this.localAngAxis1Y * tarc[1] + this.localAngAxis1Z * tarc[2];
  93540. this.localAngAxis2Y = this.localAngAxis1X * tarc[3] + this.localAngAxis1Y * tarc[4] + this.localAngAxis1Z * tarc[5];
  93541. this.localAngAxis2Z = this.localAngAxis1X * tarc[6] + this.localAngAxis1Y * tarc[7] + this.localAngAxis1Z * tarc[8];
  93542. }
  93543. this.nor = new OIMO.Vec3();
  93544. this.tan = new OIMO.Vec3();
  93545. this.bin = new OIMO.Vec3();
  93546. // The translational limit and motor information of the joint.
  93547. this.translationalLimitMotor = new OIMO.LimitMotor(this.tan, true);
  93548. this.translationalLimitMotor.frequency = 8;
  93549. this.translationalLimitMotor.dampingRatio = 1;
  93550. // The first rotational limit and motor information of the joint.
  93551. this.rotationalLimitMotor1 = new OIMO.LimitMotor(this.tan, false);
  93552. // The second rotational limit and motor information of the joint.
  93553. this.rotationalLimitMotor2 = new OIMO.LimitMotor(this.bin, false);
  93554. this.t3 = new OIMO.Translational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.translationalLimitMotor, new OIMO.LimitMotor(this.bin, true));
  93555. this.t3.weight = 1;
  93556. this.r3 = new OIMO.Rotational3Constraint(this, new OIMO.LimitMotor(this.nor, true), this.rotationalLimitMotor1, this.rotationalLimitMotor2);
  93557. };
  93558. OIMO.WheelJoint.prototype = Object.create(OIMO.Joint.prototype);
  93559. OIMO.WheelJoint.prototype.constructor = OIMO.WheelJoint;
  93560. OIMO.WheelJoint.prototype.preSolve = function (timeStep, invTimeStep) {
  93561. var tmpM;
  93562. var tmp1X;
  93563. var tmp1Y;
  93564. var tmp1Z;
  93565. this.updateAnchorPoints();
  93566. tmpM = this.body1.rotation.elements;
  93567. var x1 = this.localAxis1X * tmpM[0] + this.localAxis1Y * tmpM[1] + this.localAxis1Z * tmpM[2];
  93568. var y1 = this.localAxis1X * tmpM[3] + this.localAxis1Y * tmpM[4] + this.localAxis1Z * tmpM[5];
  93569. var z1 = this.localAxis1X * tmpM[6] + this.localAxis1Y * tmpM[7] + this.localAxis1Z * tmpM[8];
  93570. var angAxis1X = this.localAngAxis1X * tmpM[0] + this.localAngAxis1Y * tmpM[1] + this.localAngAxis1Z * tmpM[2];
  93571. var angAxis1Y = this.localAngAxis1X * tmpM[3] + this.localAngAxis1Y * tmpM[4] + this.localAngAxis1Z * tmpM[5];
  93572. var angAxis1Z = this.localAngAxis1X * tmpM[6] + this.localAngAxis1Y * tmpM[7] + this.localAngAxis1Z * tmpM[8];
  93573. tmpM = this.body2.rotation.elements;
  93574. var x2 = this.localAxis2X * tmpM[0] + this.localAxis2Y * tmpM[1] + this.localAxis2Z * tmpM[2];
  93575. var y2 = this.localAxis2X * tmpM[3] + this.localAxis2Y * tmpM[4] + this.localAxis2Z * tmpM[5];
  93576. var z2 = this.localAxis2X * tmpM[6] + this.localAxis2Y * tmpM[7] + this.localAxis2Z * tmpM[8];
  93577. var angAxis2X = this.localAngAxis2X * tmpM[0] + this.localAngAxis2Y * tmpM[1] + this.localAngAxis2Z * tmpM[2];
  93578. var angAxis2Y = this.localAngAxis2X * tmpM[3] + this.localAngAxis2Y * tmpM[4] + this.localAngAxis2Z * tmpM[5];
  93579. var angAxis2Z = this.localAngAxis2X * tmpM[6] + this.localAngAxis2Y * tmpM[7] + this.localAngAxis2Z * tmpM[8];
  93580. this.r3.limitMotor1.angle = x1 * x2 + y1 * y2 + z1 * z2;
  93581. if (x1 * (angAxis1Y * z2 - angAxis1Z * y2) + y1 * (angAxis1Z * x2 - angAxis1X * z2) + z1 * (angAxis1X * y2 - angAxis1Y * x2) < 0) {
  93582. this.rotationalLimitMotor1.angle = -this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  93583. } else {
  93584. this.rotationalLimitMotor1.angle = this.acosClamp(angAxis1X * x2 + angAxis1Y * y2 + angAxis1Z * z2);
  93585. }
  93586. if (x2 * (angAxis2Y * z1 - angAxis2Z * y1) + y2 * (angAxis2Z * x1 - angAxis2X * z1) + z2 * (angAxis2X * y1 - angAxis2Y * x1) < 0) {
  93587. this.rotationalLimitMotor2.angle = this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  93588. } else {
  93589. this.rotationalLimitMotor2.angle = -this.acosClamp(angAxis2X * x1 + angAxis2Y * y1 + angAxis2Z * z1);
  93590. }
  93591. var nx = y2 * z1 - z2 * y1;
  93592. var ny = z2 * x1 - x2 * z1;
  93593. var nz = x2 * y1 - y2 * x1;
  93594. tmp1X = OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  93595. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93596. nx *= tmp1X;
  93597. ny *= tmp1X;
  93598. nz *= tmp1X;
  93599. var tx = ny * z2 - nz * y2;
  93600. var ty = nz * x2 - nx * z2;
  93601. var tz = nx * y2 - ny * x2;
  93602. tmp1X = OIMO.sqrt(tx * tx + ty * ty + tz * tz);
  93603. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93604. tx *= tmp1X;
  93605. ty *= tmp1X;
  93606. tz *= tmp1X;
  93607. var bx = y1 * nz - z1 * ny;
  93608. var by = z1 * nx - x1 * nz;
  93609. var bz = x1 * ny - y1 * nx;
  93610. tmp1X = OIMO.sqrt(bx * bx + by * by + bz * bz);
  93611. if (tmp1X > 0) tmp1X = 1 / tmp1X;
  93612. bx *= tmp1X;
  93613. by *= tmp1X;
  93614. bz *= tmp1X;
  93615. this.nor.init(nx, ny, nz);
  93616. this.tan.init(tx, ty, tz);
  93617. this.bin.init(bx, by, bz);
  93618. this.r3.preSolve(timeStep, invTimeStep);
  93619. this.t3.preSolve(timeStep, invTimeStep);
  93620. };
  93621. OIMO.WheelJoint.prototype.solve = function () {
  93622. this.r3.solve();
  93623. this.t3.solve();
  93624. };
  93625. OIMO.WheelJoint.prototype.postSolve = function () {
  93626. };
  93627. OIMO.WheelJoint.prototype.acosClamp = function (cos) {
  93628. if (cos > 1) return 0;
  93629. else if (cos < -1) return OIMO.PI;
  93630. else return OIMO.acos(cos);
  93631. };
  93632. /**
  93633. * An angular constraint for all axes for various joints.
  93634. * @author saharan
  93635. */
  93636. OIMO.AngularConstraint = function (joint, targetOrientation) {
  93637. this.joint = joint;
  93638. this.targetOrientation = new OIMO.Quat().invert(targetOrientation);
  93639. this.relativeOrientation = new OIMO.Quat();
  93640. this.ii1 = null;
  93641. this.ii2 = null;
  93642. this.dd = null;
  93643. this.vel = new OIMO.Vec3();
  93644. this.imp = new OIMO.Vec3();
  93645. this.rn0 = new OIMO.Vec3();
  93646. this.rn1 = new OIMO.Vec3();
  93647. this.rn2 = new OIMO.Vec3();
  93648. this.b1 = joint.body1;
  93649. this.b2 = joint.body2;
  93650. this.a1 = this.b1.angularVelocity;
  93651. this.a2 = this.b2.angularVelocity;
  93652. this.i1 = this.b1.inverseInertia;
  93653. this.i2 = this.b2.inverseInertia;
  93654. };
  93655. OIMO.AngularConstraint.prototype = {
  93656. constructor: OIMO.AngularConstraint,
  93657. preSolve: function (timeStep, invTimeStep) {
  93658. var inv, len, v, vv;
  93659. this.ii1 = this.i1.clone();
  93660. this.ii2 = this.i2.clone();
  93661. v = new OIMO.Mat33().add(this.ii1, this.ii2).elements;
  93662. 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]));
  93663. this.dd = new OIMO.Mat33(
  93664. v[4] * v[8] - v[5] * v[7], v[2] * v[7] - v[1] * v[8], v[1] * v[5] - v[2] * v[4],
  93665. v[5] * v[6] - v[3] * v[8], v[0] * v[8] - v[2] * v[6], v[2] * v[3] - v[0] * v[5],
  93666. v[3] * v[7] - v[4] * v[6], v[1] * v[6] - v[0] * v[7], v[0] * v[4] - v[1] * v[3]
  93667. ).multiply(inv);
  93668. this.relativeOrientation.invert(this.b1.orientation);
  93669. this.relativeOrientation.mul(this.targetOrientation, this.relativeOrientation);
  93670. this.relativeOrientation.mul(this.b2.orientation, this.relativeOrientation);
  93671. inv = this.relativeOrientation.s * 2;
  93672. this.vel.scale(this.relativeOrientation, inv);
  93673. len = this.vel.length();
  93674. if (len > 0.02) {
  93675. len = (0.02 - len) / len * invTimeStep * 0.05;
  93676. this.vel.scaleEqual(len);
  93677. } else {
  93678. this.vel.init();
  93679. }
  93680. this.rn1.mulMat(this.ii1, this.imp);
  93681. this.rn2.mulMat(this.ii2, this.imp);
  93682. this.a1.addEqual(this.rn1);
  93683. this.a2.subEqual(this.rn2);
  93684. },
  93685. solve: function () {
  93686. var r = this.a2.clone().subEqual(this.a1).subEqual(this.vel);
  93687. this.rn0.mulMat(this.dd, r);
  93688. this.rn1.mulMat(this.ii1, this.rn0);
  93689. this.rn2.mulMat(this.ii2, this.rn0);
  93690. this.imp.addEqual(this.rn0);
  93691. this.a1.addEqual(this.rn1);
  93692. this.a2.subEqual(this.rn2);
  93693. }
  93694. };
  93695. /**
  93696. * A linear constraint for all axes for various joints.
  93697. * @author saharan
  93698. */
  93699. OIMO.LinearConstraint = function (joint) {
  93700. this.m1 = NaN;
  93701. this.m2 = NaN;
  93702. this.ii1 = null;
  93703. this.ii2 = null;
  93704. this.dd = null;
  93705. this.r1x = NaN;
  93706. this.r1y = NaN;
  93707. this.r1z = NaN;
  93708. this.r2x = NaN;
  93709. this.r2y = NaN;
  93710. this.r2z = NaN;
  93711. this.ax1x = NaN;
  93712. this.ax1y = NaN;
  93713. this.ax1z = NaN;
  93714. this.ay1x = NaN;
  93715. this.ay1y = NaN;
  93716. this.ay1z = NaN;
  93717. this.az1x = NaN;
  93718. this.az1y = NaN;
  93719. this.az1z = NaN;
  93720. this.ax2x = NaN;
  93721. this.ax2y = NaN;
  93722. this.ax2z = NaN;
  93723. this.ay2x = NaN;
  93724. this.ay2y = NaN;
  93725. this.ay2z = NaN;
  93726. this.az2x = NaN;
  93727. this.az2y = NaN;
  93728. this.az2z = NaN;
  93729. this.vel = NaN;
  93730. this.velx = NaN;
  93731. this.vely = NaN;
  93732. this.velz = NaN;
  93733. this.joint = joint;
  93734. this.r1 = joint.relativeAnchorPoint1;
  93735. this.r2 = joint.relativeAnchorPoint2;
  93736. this.p1 = joint.anchorPoint1;
  93737. this.p2 = joint.anchorPoint2;
  93738. this.b1 = joint.body1;
  93739. this.b2 = joint.body2;
  93740. this.l1 = this.b1.linearVelocity;
  93741. this.l2 = this.b2.linearVelocity;
  93742. this.a1 = this.b1.angularVelocity;
  93743. this.a2 = this.b2.angularVelocity;
  93744. this.i1 = this.b1.inverseInertia;
  93745. this.i2 = this.b2.inverseInertia;
  93746. this.impx = 0;
  93747. this.impy = 0;
  93748. this.impz = 0;
  93749. }
  93750. OIMO.LinearConstraint.prototype = {
  93751. constructor: OIMO.LinearConstraint,
  93752. preSolve: function (timeStep, invTimeStep) {
  93753. this.r1x = this.r1.x;
  93754. this.r1y = this.r1.y;
  93755. this.r1z = this.r1.z;
  93756. this.r2x = this.r2.x;
  93757. this.r2y = this.r2.y;
  93758. this.r2z = this.r2.z;
  93759. this.m1 = this.b1.inverseMass;
  93760. this.m2 = this.b2.inverseMass;
  93761. this.ii1 = this.i1.clone();
  93762. this.ii2 = this.i2.clone();
  93763. var ii1 = this.ii1.elements;
  93764. var ii2 = this.ii2.elements;
  93765. this.ax1x = this.r1z * ii1[1] + -this.r1y * ii1[2];
  93766. this.ax1y = this.r1z * ii1[4] + -this.r1y * ii1[5];
  93767. this.ax1z = this.r1z * ii1[7] + -this.r1y * ii1[8];
  93768. this.ay1x = -this.r1z * ii1[0] + this.r1x * ii1[2];
  93769. this.ay1y = -this.r1z * ii1[3] + this.r1x * ii1[5];
  93770. this.ay1z = -this.r1z * ii1[6] + this.r1x * ii1[8];
  93771. this.az1x = this.r1y * ii1[0] + -this.r1x * ii1[1];
  93772. this.az1y = this.r1y * ii1[3] + -this.r1x * ii1[4];
  93773. this.az1z = this.r1y * ii1[6] + -this.r1x * ii1[7];
  93774. this.ax2x = this.r2z * ii2[1] + -this.r2y * ii2[2];
  93775. this.ax2y = this.r2z * ii2[4] + -this.r2y * ii2[5];
  93776. this.ax2z = this.r2z * ii2[7] + -this.r2y * ii2[8];
  93777. this.ay2x = -this.r2z * ii2[0] + this.r2x * ii2[2];
  93778. this.ay2y = -this.r2z * ii2[3] + this.r2x * ii2[5];
  93779. this.ay2z = -this.r2z * ii2[6] + this.r2x * ii2[8];
  93780. this.az2x = this.r2y * ii2[0] + -this.r2x * ii2[1];
  93781. this.az2y = this.r2y * ii2[3] + -this.r2x * ii2[4];
  93782. this.az2z = this.r2y * ii2[6] + -this.r2x * ii2[7];
  93783. // calculate point-to-point mass matrix
  93784. // from impulse equation
  93785. //
  93786. // M = ([/m] - [r^][/I][r^]) ^ -1
  93787. //
  93788. // where
  93789. //
  93790. // [/m] = |1/m, 0, 0|
  93791. // |0, 1/m, 0|
  93792. // |0, 0, 1/m|
  93793. //
  93794. // [r^] = |0, -rz, ry|
  93795. // |rz, 0, -rx|
  93796. // |-ry, rx, 0|
  93797. //
  93798. // [/I] = Inverted moment inertia
  93799. var rxx = this.m1 + this.m2;
  93800. var kk = new OIMO.Mat33(rxx, 0, 0, 0, rxx, 0, 0, 0, rxx);
  93801. var k = kk.elements;
  93802. k[0] += ii1[4] * this.r1z * this.r1z - (ii1[7] + ii1[5]) * this.r1y * this.r1z + ii1[8] * this.r1y * this.r1y;
  93803. k[1] += (ii1[6] * this.r1y + ii1[5] * this.r1x) * this.r1z - ii1[3] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  93804. k[2] += (ii1[3] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[6] * this.r1y * this.r1y + ii1[7] * this.r1x * this.r1y;
  93805. k[3] += (ii1[2] * this.r1y + ii1[7] * this.r1x) * this.r1z - ii1[1] * this.r1z * this.r1z - ii1[8] * this.r1x * this.r1y;
  93806. k[4] += ii1[0] * this.r1z * this.r1z - (ii1[6] + ii1[2]) * this.r1x * this.r1z + ii1[8] * this.r1x * this.r1x;
  93807. k[5] += (ii1[1] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[7] * this.r1x * this.r1x + ii1[6] * this.r1x * this.r1y;
  93808. k[6] += (ii1[1] * this.r1y - ii1[4] * this.r1x) * this.r1z - ii1[2] * this.r1y * this.r1y + ii1[5] * this.r1x * this.r1y;
  93809. k[7] += (ii1[3] * this.r1x - ii1[0] * this.r1y) * this.r1z - ii1[5] * this.r1x * this.r1x + ii1[2] * this.r1x * this.r1y;
  93810. k[8] += ii1[0] * this.r1y * this.r1y - (ii1[3] + ii1[1]) * this.r1x * this.r1y + ii1[4] * this.r1x * this.r1x;
  93811. k[0] += ii2[4] * this.r2z * this.r2z - (ii2[7] + ii2[5]) * this.r2y * this.r2z + ii2[8] * this.r2y * this.r2y;
  93812. k[1] += (ii2[6] * this.r2y + ii2[5] * this.r2x) * this.r2z - ii2[3] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  93813. k[2] += (ii2[3] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[6] * this.r2y * this.r2y + ii2[7] * this.r2x * this.r2y;
  93814. k[3] += (ii2[2] * this.r2y + ii2[7] * this.r2x) * this.r2z - ii2[1] * this.r2z * this.r2z - ii2[8] * this.r2x * this.r2y;
  93815. k[4] += ii2[0] * this.r2z * this.r2z - (ii2[6] + ii2[2]) * this.r2x * this.r2z + ii2[8] * this.r2x * this.r2x;
  93816. k[5] += (ii2[1] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[7] * this.r2x * this.r2x + ii2[6] * this.r2x * this.r2y;
  93817. k[6] += (ii2[1] * this.r2y - ii2[4] * this.r2x) * this.r2z - ii2[2] * this.r2y * this.r2y + ii2[5] * this.r2x * this.r2y;
  93818. k[7] += (ii2[3] * this.r2x - ii2[0] * this.r2y) * this.r2z - ii2[5] * this.r2x * this.r2x + ii2[2] * this.r2x * this.r2y;
  93819. k[8] += ii2[0] * this.r2y * this.r2y - (ii2[3] + ii2[1]) * this.r2x * this.r2y + ii2[4] * this.r2x * this.r2x;
  93820. 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]));
  93821. this.dd = new OIMO.Mat33(
  93822. k[4] * k[8] - k[5] * k[7], k[2] * k[7] - k[1] * k[8], k[1] * k[5] - k[2] * k[4],
  93823. k[5] * k[6] - k[3] * k[8], k[0] * k[8] - k[2] * k[6], k[2] * k[3] - k[0] * k[5],
  93824. k[3] * k[7] - k[4] * k[6], k[1] * k[6] - k[0] * k[7], k[0] * k[4] - k[1] * k[3]
  93825. ).multiply(inv);
  93826. this.velx = this.p2.x - this.p1.x;
  93827. this.vely = this.p2.y - this.p1.y;
  93828. this.velz = this.p2.z - this.p1.z;
  93829. var len = OIMO.sqrt(this.velx * this.velx + this.vely * this.vely + this.velz * this.velz);
  93830. if (len > 0.005) {
  93831. len = (0.005 - len) / len * invTimeStep * 0.05;
  93832. this.velx *= len;
  93833. this.vely *= len;
  93834. this.velz *= len;
  93835. } else {
  93836. this.velx = 0;
  93837. this.vely = 0;
  93838. this.velz = 0;
  93839. }
  93840. this.impx *= 0.95;
  93841. this.impy *= 0.95;
  93842. this.impz *= 0.95;
  93843. this.l1.x += this.impx * this.m1;
  93844. this.l1.y += this.impy * this.m1;
  93845. this.l1.z += this.impz * this.m1;
  93846. this.a1.x += this.impx * this.ax1x + this.impy * this.ay1x + this.impz * this.az1x;
  93847. this.a1.y += this.impx * this.ax1y + this.impy * this.ay1y + this.impz * this.az1y;
  93848. this.a1.z += this.impx * this.ax1z + this.impy * this.ay1z + this.impz * this.az1z;
  93849. this.l2.x -= this.impx * this.m2;
  93850. this.l2.y -= this.impy * this.m2;
  93851. this.l2.z -= this.impz * this.m2;
  93852. this.a2.x -= this.impx * this.ax2x + this.impy * this.ay2x + this.impz * this.az2x;
  93853. this.a2.y -= this.impx * this.ax2y + this.impy * this.ay2y + this.impz * this.az2y;
  93854. this.a2.z -= this.impx * this.ax2z + this.impy * this.ay2z + this.impz * this.az2z;
  93855. },
  93856. solve: function () {
  93857. var d = this.dd.elements;
  93858. 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;
  93859. 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;
  93860. 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;
  93861. var nimpx = rvx * d[0] + rvy * d[1] + rvz * d[2];
  93862. var nimpy = rvx * d[3] + rvy * d[4] + rvz * d[5];
  93863. var nimpz = rvx * d[6] + rvy * d[7] + rvz * d[8];
  93864. this.impx += nimpx;
  93865. this.impy += nimpy;
  93866. this.impz += nimpz;
  93867. this.l1.x += nimpx * this.m1;
  93868. this.l1.y += nimpy * this.m1;
  93869. this.l1.z += nimpz * this.m1;
  93870. this.a1.x += nimpx * this.ax1x + nimpy * this.ay1x + nimpz * this.az1x;
  93871. this.a1.y += nimpx * this.ax1y + nimpy * this.ay1y + nimpz * this.az1y;
  93872. this.a1.z += nimpx * this.ax1z + nimpy * this.ay1z + nimpz * this.az1z;
  93873. this.l2.x -= nimpx * this.m2;
  93874. this.l2.y -= nimpy * this.m2;
  93875. this.l2.z -= nimpz * this.m2;
  93876. this.a2.x -= nimpx * this.ax2x + nimpy * this.ay2x + nimpz * this.az2x;
  93877. this.a2.y -= nimpx * this.ax2y + nimpy * this.ay2y + nimpz * this.az2y;
  93878. this.a2.z -= nimpx * this.ax2z + nimpy * this.ay2z + nimpz * this.az2z;
  93879. }
  93880. }
  93881. /**
  93882. * A three-axis rotational constraint for various joints.
  93883. * @author saharan
  93884. */
  93885. OIMO.Rotational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  93886. this.cfm1 = NaN;
  93887. this.cfm2 = NaN;
  93888. this.cfm3 = NaN;
  93889. this.i1e00 = NaN;
  93890. this.i1e01 = NaN;
  93891. this.i1e02 = NaN;
  93892. this.i1e10 = NaN;
  93893. this.i1e11 = NaN;
  93894. this.i1e12 = NaN;
  93895. this.i1e20 = NaN;
  93896. this.i1e21 = NaN;
  93897. this.i1e22 = NaN;
  93898. this.i2e00 = NaN;
  93899. this.i2e01 = NaN;
  93900. this.i2e02 = NaN;
  93901. this.i2e10 = NaN;
  93902. this.i2e11 = NaN;
  93903. this.i2e12 = NaN;
  93904. this.i2e20 = NaN;
  93905. this.i2e21 = NaN;
  93906. this.i2e22 = NaN;
  93907. this.ax1 = NaN;
  93908. this.ay1 = NaN;
  93909. this.az1 = NaN;
  93910. this.ax2 = NaN;
  93911. this.ay2 = NaN;
  93912. this.az2 = NaN;
  93913. this.ax3 = NaN;
  93914. this.ay3 = NaN;
  93915. this.az3 = NaN;
  93916. this.a1x1 = NaN; // jacoians
  93917. this.a1y1 = NaN;
  93918. this.a1z1 = NaN;
  93919. this.a2x1 = NaN;
  93920. this.a2y1 = NaN;
  93921. this.a2z1 = NaN;
  93922. this.a1x2 = NaN;
  93923. this.a1y2 = NaN;
  93924. this.a1z2 = NaN;
  93925. this.a2x2 = NaN;
  93926. this.a2y2 = NaN;
  93927. this.a2z2 = NaN;
  93928. this.a1x3 = NaN;
  93929. this.a1y3 = NaN;
  93930. this.a1z3 = NaN;
  93931. this.a2x3 = NaN;
  93932. this.a2y3 = NaN;
  93933. this.a2z3 = NaN;
  93934. this.lowerLimit1 = NaN;
  93935. this.upperLimit1 = NaN;
  93936. this.limitVelocity1 = NaN;
  93937. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93938. this.enableMotor1 = false;
  93939. this.motorSpeed1 = NaN;
  93940. this.maxMotorForce1 = NaN;
  93941. this.maxMotorImpulse1 = NaN;
  93942. this.lowerLimit2 = NaN;
  93943. this.upperLimit2 = NaN;
  93944. this.limitVelocity2 = NaN;
  93945. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93946. this.enableMotor2 = false;
  93947. this.motorSpeed2 = NaN;
  93948. this.maxMotorForce2 = NaN;
  93949. this.maxMotorImpulse2 = NaN;
  93950. this.lowerLimit3 = NaN;
  93951. this.upperLimit3 = NaN;
  93952. this.limitVelocity3 = NaN;
  93953. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  93954. this.enableMotor3 = false;
  93955. this.motorSpeed3 = NaN;
  93956. this.maxMotorForce3 = NaN;
  93957. this.maxMotorImpulse3 = NaN;
  93958. this.k00 = NaN; // K = J*M*JT
  93959. this.k01 = NaN;
  93960. this.k02 = NaN;
  93961. this.k10 = NaN;
  93962. this.k11 = NaN;
  93963. this.k12 = NaN;
  93964. this.k20 = NaN;
  93965. this.k21 = NaN;
  93966. this.k22 = NaN;
  93967. this.kv00 = NaN; // diagonals without CFMs
  93968. this.kv11 = NaN;
  93969. this.kv22 = NaN;
  93970. this.dv00 = NaN; // ...inverted
  93971. this.dv11 = NaN;
  93972. this.dv22 = NaN;
  93973. this.d00 = NaN; // K^-1
  93974. this.d01 = NaN;
  93975. this.d02 = NaN;
  93976. this.d10 = NaN;
  93977. this.d11 = NaN;
  93978. this.d12 = NaN;
  93979. this.d20 = NaN;
  93980. this.d21 = NaN;
  93981. this.d22 = NaN;
  93982. this.limitMotor1 = limitMotor1;
  93983. this.limitMotor2 = limitMotor2;
  93984. this.limitMotor3 = limitMotor3;
  93985. this.b1 = joint.body1;
  93986. this.b2 = joint.body2;
  93987. this.a1 = this.b1.angularVelocity;
  93988. this.a2 = this.b2.angularVelocity;
  93989. this.i1 = this.b1.inverseInertia;
  93990. this.i2 = this.b2.inverseInertia;
  93991. this.limitImpulse1 = 0;
  93992. this.motorImpulse1 = 0;
  93993. this.limitImpulse2 = 0;
  93994. this.motorImpulse2 = 0;
  93995. this.limitImpulse3 = 0;
  93996. this.motorImpulse3 = 0;
  93997. }
  93998. OIMO.Rotational3Constraint.prototype = {
  93999. constructor: OIMO.Rotational3Constraint,
  94000. preSolve: function (timeStep, invTimeStep) {
  94001. this.ax1 = this.limitMotor1.axis.x;
  94002. this.ay1 = this.limitMotor1.axis.y;
  94003. this.az1 = this.limitMotor1.axis.z;
  94004. this.ax2 = this.limitMotor2.axis.x;
  94005. this.ay2 = this.limitMotor2.axis.y;
  94006. this.az2 = this.limitMotor2.axis.z;
  94007. this.ax3 = this.limitMotor3.axis.x;
  94008. this.ay3 = this.limitMotor3.axis.y;
  94009. this.az3 = this.limitMotor3.axis.z;
  94010. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  94011. this.upperLimit1 = this.limitMotor1.upperLimit;
  94012. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  94013. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  94014. this.enableMotor1 = this.maxMotorForce1 > 0;
  94015. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  94016. this.upperLimit2 = this.limitMotor2.upperLimit;
  94017. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  94018. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  94019. this.enableMotor2 = this.maxMotorForce2 > 0;
  94020. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  94021. this.upperLimit3 = this.limitMotor3.upperLimit;
  94022. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  94023. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  94024. this.enableMotor3 = this.maxMotorForce3 > 0;
  94025. var ti1 = this.i1.elements;
  94026. var ti2 = this.i2.elements;
  94027. this.i1e00 = ti1[0];
  94028. this.i1e01 = ti1[1];
  94029. this.i1e02 = ti1[2];
  94030. this.i1e10 = ti1[3];
  94031. this.i1e11 = ti1[4];
  94032. this.i1e12 = ti1[5];
  94033. this.i1e20 = ti1[6];
  94034. this.i1e21 = ti1[7];
  94035. this.i1e22 = ti1[8];
  94036. this.i2e00 = ti2[0];
  94037. this.i2e01 = ti2[1];
  94038. this.i2e02 = ti2[2];
  94039. this.i2e10 = ti2[3];
  94040. this.i2e11 = ti2[4];
  94041. this.i2e12 = ti2[5];
  94042. this.i2e20 = ti2[6];
  94043. this.i2e21 = ti2[7];
  94044. this.i2e22 = ti2[8];
  94045. var frequency1 = this.limitMotor1.frequency;
  94046. var frequency2 = this.limitMotor2.frequency;
  94047. var frequency3 = this.limitMotor3.frequency;
  94048. var enableSpring1 = frequency1 > 0;
  94049. var enableSpring2 = frequency2 > 0;
  94050. var enableSpring3 = frequency3 > 0;
  94051. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  94052. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  94053. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  94054. var angle1 = this.limitMotor1.angle;
  94055. if (enableLimit1) {
  94056. if (this.lowerLimit1 == this.upperLimit1) {
  94057. if (this.limitState1 != 0) {
  94058. this.limitState1 = 0;
  94059. this.limitImpulse1 = 0;
  94060. }
  94061. this.limitVelocity1 = this.lowerLimit1 - angle1;
  94062. } else if (angle1 < this.lowerLimit1) {
  94063. if (this.limitState1 != -1) {
  94064. this.limitState1 = -1;
  94065. this.limitImpulse1 = 0;
  94066. }
  94067. this.limitVelocity1 = this.lowerLimit1 - angle1;
  94068. } else if (angle1 > this.upperLimit1) {
  94069. if (this.limitState1 != 1) {
  94070. this.limitState1 = 1;
  94071. this.limitImpulse1 = 0;
  94072. }
  94073. this.limitVelocity1 = this.upperLimit1 - angle1;
  94074. } else {
  94075. this.limitState1 = 2;
  94076. this.limitImpulse1 = 0;
  94077. this.limitVelocity1 = 0;
  94078. }
  94079. if (!enableSpring1) {
  94080. if (this.limitVelocity1 > 0.02) this.limitVelocity1 -= 0.02;
  94081. else if (this.limitVelocity1 < -0.02) this.limitVelocity1 += 0.02;
  94082. else this.limitVelocity1 = 0;
  94083. }
  94084. } else {
  94085. this.limitState1 = 2;
  94086. this.limitImpulse1 = 0;
  94087. }
  94088. var angle2 = this.limitMotor2.angle;
  94089. if (enableLimit2) {
  94090. if (this.lowerLimit2 == this.upperLimit2) {
  94091. if (this.limitState2 != 0) {
  94092. this.limitState2 = 0;
  94093. this.limitImpulse2 = 0;
  94094. }
  94095. this.limitVelocity2 = this.lowerLimit2 - angle2;
  94096. } else if (angle2 < this.lowerLimit2) {
  94097. if (this.limitState2 != -1) {
  94098. this.limitState2 = -1;
  94099. this.limitImpulse2 = 0;
  94100. }
  94101. this.limitVelocity2 = this.lowerLimit2 - angle2;
  94102. } else if (angle2 > this.upperLimit2) {
  94103. if (this.limitState2 != 1) {
  94104. this.limitState2 = 1;
  94105. this.limitImpulse2 = 0;
  94106. }
  94107. this.limitVelocity2 = this.upperLimit2 - angle2;
  94108. } else {
  94109. this.limitState2 = 2;
  94110. this.limitImpulse2 = 0;
  94111. this.limitVelocity2 = 0;
  94112. }
  94113. if (!enableSpring2) {
  94114. if (this.limitVelocity2 > 0.02) this.limitVelocity2 -= 0.02;
  94115. else if (this.limitVelocity2 < -0.02) this.limitVelocity2 += 0.02;
  94116. else this.limitVelocity2 = 0;
  94117. }
  94118. } else {
  94119. this.limitState2 = 2;
  94120. this.limitImpulse2 = 0;
  94121. }
  94122. var angle3 = this.limitMotor3.angle;
  94123. if (enableLimit3) {
  94124. if (this.lowerLimit3 == this.upperLimit3) {
  94125. if (this.limitState3 != 0) {
  94126. this.limitState3 = 0;
  94127. this.limitImpulse3 = 0;
  94128. }
  94129. this.limitVelocity3 = this.lowerLimit3 - angle3;
  94130. } else if (angle3 < this.lowerLimit3) {
  94131. if (this.limitState3 != -1) {
  94132. this.limitState3 = -1;
  94133. this.limitImpulse3 = 0;
  94134. }
  94135. this.limitVelocity3 = this.lowerLimit3 - angle3;
  94136. } else if (angle3 > this.upperLimit3) {
  94137. if (this.limitState3 != 1) {
  94138. this.limitState3 = 1;
  94139. this.limitImpulse3 = 0;
  94140. }
  94141. this.limitVelocity3 = this.upperLimit3 - angle3;
  94142. } else {
  94143. this.limitState3 = 2;
  94144. this.limitImpulse3 = 0;
  94145. this.limitVelocity3 = 0;
  94146. }
  94147. if (!enableSpring3) {
  94148. if (this.limitVelocity3 > 0.02) this.limitVelocity3 -= 0.02;
  94149. else if (this.limitVelocity3 < -0.02) this.limitVelocity3 += 0.02;
  94150. else this.limitVelocity3 = 0;
  94151. }
  94152. } else {
  94153. this.limitState3 = 2;
  94154. this.limitImpulse3 = 0;
  94155. }
  94156. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  94157. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  94158. } else {
  94159. this.motorImpulse1 = 0;
  94160. this.maxMotorImpulse1 = 0;
  94161. }
  94162. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  94163. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  94164. } else {
  94165. this.motorImpulse2 = 0;
  94166. this.maxMotorImpulse2 = 0;
  94167. }
  94168. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  94169. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  94170. } else {
  94171. this.motorImpulse3 = 0;
  94172. this.maxMotorImpulse3 = 0;
  94173. }
  94174. // build jacobians
  94175. this.a1x1 = this.ax1 * this.i1e00 + this.ay1 * this.i1e01 + this.az1 * this.i1e02;
  94176. this.a1y1 = this.ax1 * this.i1e10 + this.ay1 * this.i1e11 + this.az1 * this.i1e12;
  94177. this.a1z1 = this.ax1 * this.i1e20 + this.ay1 * this.i1e21 + this.az1 * this.i1e22;
  94178. this.a2x1 = this.ax1 * this.i2e00 + this.ay1 * this.i2e01 + this.az1 * this.i2e02;
  94179. this.a2y1 = this.ax1 * this.i2e10 + this.ay1 * this.i2e11 + this.az1 * this.i2e12;
  94180. this.a2z1 = this.ax1 * this.i2e20 + this.ay1 * this.i2e21 + this.az1 * this.i2e22;
  94181. this.a1x2 = this.ax2 * this.i1e00 + this.ay2 * this.i1e01 + this.az2 * this.i1e02;
  94182. this.a1y2 = this.ax2 * this.i1e10 + this.ay2 * this.i1e11 + this.az2 * this.i1e12;
  94183. this.a1z2 = this.ax2 * this.i1e20 + this.ay2 * this.i1e21 + this.az2 * this.i1e22;
  94184. this.a2x2 = this.ax2 * this.i2e00 + this.ay2 * this.i2e01 + this.az2 * this.i2e02;
  94185. this.a2y2 = this.ax2 * this.i2e10 + this.ay2 * this.i2e11 + this.az2 * this.i2e12;
  94186. this.a2z2 = this.ax2 * this.i2e20 + this.ay2 * this.i2e21 + this.az2 * this.i2e22;
  94187. this.a1x3 = this.ax3 * this.i1e00 + this.ay3 * this.i1e01 + this.az3 * this.i1e02;
  94188. this.a1y3 = this.ax3 * this.i1e10 + this.ay3 * this.i1e11 + this.az3 * this.i1e12;
  94189. this.a1z3 = this.ax3 * this.i1e20 + this.ay3 * this.i1e21 + this.az3 * this.i1e22;
  94190. this.a2x3 = this.ax3 * this.i2e00 + this.ay3 * this.i2e01 + this.az3 * this.i2e02;
  94191. this.a2y3 = this.ax3 * this.i2e10 + this.ay3 * this.i2e11 + this.az3 * this.i2e12;
  94192. this.a2z3 = this.ax3 * this.i2e20 + this.ay3 * this.i2e21 + this.az3 * this.i2e22;
  94193. // build an impulse matrix
  94194. this.k00 = this.ax1 * (this.a1x1 + this.a2x1) + this.ay1 * (this.a1y1 + this.a2y1) + this.az1 * (this.a1z1 + this.a2z1);
  94195. this.k01 = this.ax1 * (this.a1x2 + this.a2x2) + this.ay1 * (this.a1y2 + this.a2y2) + this.az1 * (this.a1z2 + this.a2z2);
  94196. this.k02 = this.ax1 * (this.a1x3 + this.a2x3) + this.ay1 * (this.a1y3 + this.a2y3) + this.az1 * (this.a1z3 + this.a2z3);
  94197. this.k10 = this.ax2 * (this.a1x1 + this.a2x1) + this.ay2 * (this.a1y1 + this.a2y1) + this.az2 * (this.a1z1 + this.a2z1);
  94198. this.k11 = this.ax2 * (this.a1x2 + this.a2x2) + this.ay2 * (this.a1y2 + this.a2y2) + this.az2 * (this.a1z2 + this.a2z2);
  94199. this.k12 = this.ax2 * (this.a1x3 + this.a2x3) + this.ay2 * (this.a1y3 + this.a2y3) + this.az2 * (this.a1z3 + this.a2z3);
  94200. this.k20 = this.ax3 * (this.a1x1 + this.a2x1) + this.ay3 * (this.a1y1 + this.a2y1) + this.az3 * (this.a1z1 + this.a2z1);
  94201. this.k21 = this.ax3 * (this.a1x2 + this.a2x2) + this.ay3 * (this.a1y2 + this.a2y2) + this.az3 * (this.a1z2 + this.a2z2);
  94202. this.k22 = this.ax3 * (this.a1x3 + this.a2x3) + this.ay3 * (this.a1y3 + this.a2y3) + this.az3 * (this.a1z3 + this.a2z3);
  94203. this.kv00 = this.k00;
  94204. this.kv11 = this.k11;
  94205. this.kv22 = this.k22;
  94206. this.dv00 = 1 / this.kv00;
  94207. this.dv11 = 1 / this.kv11;
  94208. this.dv22 = 1 / this.kv22;
  94209. if (enableSpring1 && this.limitState1 != 2) {
  94210. var omega = 6.2831853 * frequency1;
  94211. var k = omega * omega * timeStep;
  94212. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  94213. this.cfm1 = this.kv00 * dmp;
  94214. this.limitVelocity1 *= k * dmp;
  94215. } else {
  94216. this.cfm1 = 0;
  94217. this.limitVelocity1 *= invTimeStep * 0.05;
  94218. }
  94219. if (enableSpring2 && this.limitState2 != 2) {
  94220. omega = 6.2831853 * frequency2;
  94221. k = omega * omega * timeStep;
  94222. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  94223. this.cfm2 = this.kv11 * dmp;
  94224. this.limitVelocity2 *= k * dmp;
  94225. } else {
  94226. this.cfm2 = 0;
  94227. this.limitVelocity2 *= invTimeStep * 0.05;
  94228. }
  94229. if (enableSpring3 && this.limitState3 != 2) {
  94230. omega = 6.2831853 * frequency3;
  94231. k = omega * omega * timeStep;
  94232. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  94233. this.cfm3 = this.kv22 * dmp;
  94234. this.limitVelocity3 *= k * dmp;
  94235. } else {
  94236. this.cfm3 = 0;
  94237. this.limitVelocity3 *= invTimeStep * 0.05;
  94238. }
  94239. this.k00 += this.cfm1;
  94240. this.k11 += this.cfm2;
  94241. this.k22 += this.cfm3;
  94242. var inv = 1 / (
  94243. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  94244. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  94245. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  94246. );
  94247. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  94248. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  94249. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  94250. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  94251. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  94252. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  94253. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  94254. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  94255. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  94256. this.limitImpulse1 *= 0.95;
  94257. this.motorImpulse1 *= 0.95;
  94258. this.limitImpulse2 *= 0.95;
  94259. this.motorImpulse2 *= 0.95;
  94260. this.limitImpulse3 *= 0.95;
  94261. this.motorImpulse3 *= 0.95;
  94262. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  94263. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  94264. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  94265. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  94266. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  94267. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  94268. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  94269. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  94270. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  94271. },
  94272. solve_: function () {
  94273. var rvx = this.a2.x - this.a1.x;
  94274. var rvy = this.a2.y - this.a1.y;
  94275. var rvz = this.a2.z - this.a1.z;
  94276. this.limitVelocity3 = 30;
  94277. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1 - this.limitVelocity1;
  94278. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2 - this.limitVelocity2;
  94279. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3 - this.limitVelocity3;
  94280. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  94281. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  94282. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  94283. this.limitImpulse1 += dLimitImpulse1;
  94284. this.limitImpulse2 += dLimitImpulse2;
  94285. this.limitImpulse3 += dLimitImpulse3;
  94286. this.a1.x += dLimitImpulse1 * this.a1x1 + dLimitImpulse2 * this.a1x2 + dLimitImpulse3 * this.a1x3;
  94287. this.a1.y += dLimitImpulse1 * this.a1y1 + dLimitImpulse2 * this.a1y2 + dLimitImpulse3 * this.a1y3;
  94288. this.a1.z += dLimitImpulse1 * this.a1z1 + dLimitImpulse2 * this.a1z2 + dLimitImpulse3 * this.a1z3;
  94289. this.a2.x -= dLimitImpulse1 * this.a2x1 + dLimitImpulse2 * this.a2x2 + dLimitImpulse3 * this.a2x3;
  94290. this.a2.y -= dLimitImpulse1 * this.a2y1 + dLimitImpulse2 * this.a2y2 + dLimitImpulse3 * this.a2y3;
  94291. this.a2.z -= dLimitImpulse1 * this.a2z1 + dLimitImpulse2 * this.a2z2 + dLimitImpulse3 * this.a2z3;
  94292. },
  94293. solve: function () {
  94294. var rvx = this.a2.x - this.a1.x;
  94295. var rvy = this.a2.y - this.a1.y;
  94296. var rvz = this.a2.z - this.a1.z;
  94297. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  94298. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  94299. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  94300. var oldMotorImpulse1 = this.motorImpulse1;
  94301. var oldMotorImpulse2 = this.motorImpulse2;
  94302. var oldMotorImpulse3 = this.motorImpulse3;
  94303. var dMotorImpulse1 = 0;
  94304. var dMotorImpulse2 = 0;
  94305. var dMotorImpulse3 = 0;
  94306. if (this.enableMotor1) {
  94307. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  94308. this.motorImpulse1 += dMotorImpulse1;
  94309. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  94310. this.motorImpulse1 = this.maxMotorImpulse1;
  94311. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  94312. this.motorImpulse1 = -this.maxMotorImpulse1;
  94313. }
  94314. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  94315. }
  94316. if (this.enableMotor2) {
  94317. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  94318. this.motorImpulse2 += dMotorImpulse2;
  94319. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  94320. this.motorImpulse2 = this.maxMotorImpulse2;
  94321. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  94322. this.motorImpulse2 = -this.maxMotorImpulse2;
  94323. }
  94324. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  94325. }
  94326. if (this.enableMotor3) {
  94327. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  94328. this.motorImpulse3 += dMotorImpulse3;
  94329. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  94330. this.motorImpulse3 = this.maxMotorImpulse3;
  94331. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  94332. this.motorImpulse3 = -this.maxMotorImpulse3;
  94333. }
  94334. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  94335. }
  94336. // apply motor impulse to relative velocity
  94337. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  94338. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  94339. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  94340. // subtract target velocity and applied impulse
  94341. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  94342. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  94343. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  94344. var oldLimitImpulse1 = this.limitImpulse1;
  94345. var oldLimitImpulse2 = this.limitImpulse2;
  94346. var oldLimitImpulse3 = this.limitImpulse3;
  94347. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  94348. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  94349. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  94350. this.limitImpulse1 += dLimitImpulse1;
  94351. this.limitImpulse2 += dLimitImpulse2;
  94352. this.limitImpulse3 += dLimitImpulse3;
  94353. // clamp
  94354. var clampState = 0;
  94355. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  94356. dLimitImpulse1 = -oldLimitImpulse1;
  94357. rvn2 += dLimitImpulse1 * this.k10;
  94358. rvn3 += dLimitImpulse1 * this.k20;
  94359. clampState |= 1;
  94360. }
  94361. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  94362. dLimitImpulse2 = -oldLimitImpulse2;
  94363. rvn1 += dLimitImpulse2 * this.k01;
  94364. rvn3 += dLimitImpulse2 * this.k21;
  94365. clampState |= 2;
  94366. }
  94367. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  94368. dLimitImpulse3 = -oldLimitImpulse3;
  94369. rvn1 += dLimitImpulse3 * this.k02;
  94370. rvn2 += dLimitImpulse3 * this.k12;
  94371. clampState |= 4;
  94372. }
  94373. // update un-clamped impulse
  94374. // TODO: isolate division
  94375. var det;
  94376. switch (clampState) {
  94377. case 1: // update 2 3
  94378. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  94379. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  94380. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  94381. break;
  94382. case 2: // update 1 3
  94383. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  94384. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  94385. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  94386. break;
  94387. case 3: // update 3
  94388. dLimitImpulse3 = rvn3 / this.k22;
  94389. break;
  94390. case 4: // update 1 2
  94391. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  94392. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  94393. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  94394. break;
  94395. case 5: // update 2
  94396. dLimitImpulse2 = rvn2 / this.k11;
  94397. break;
  94398. case 6: // update 1
  94399. dLimitImpulse1 = rvn1 / this.k00;
  94400. break;
  94401. }
  94402. this.limitImpulse1 = dLimitImpulse1 + oldLimitImpulse1;
  94403. this.limitImpulse2 = dLimitImpulse2 + oldLimitImpulse2;
  94404. this.limitImpulse3 = dLimitImpulse3 + oldLimitImpulse3;
  94405. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  94406. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  94407. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  94408. // apply impulse
  94409. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  94410. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  94411. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  94412. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  94413. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  94414. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  94415. rvx = this.a2.x - this.a1.x;
  94416. rvy = this.a2.y - this.a1.y;
  94417. rvz = this.a2.z - this.a1.z;
  94418. rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  94419. }
  94420. }
  94421. /**
  94422. * A rotational constraint for various joints.
  94423. * @author saharan
  94424. */
  94425. OIMO.RotationalConstraint = function (joint, limitMotor) {
  94426. this.cfm = NaN;
  94427. this.i1e00 = NaN;
  94428. this.i1e01 = NaN;
  94429. this.i1e02 = NaN;
  94430. this.i1e10 = NaN;
  94431. this.i1e11 = NaN;
  94432. this.i1e12 = NaN;
  94433. this.i1e20 = NaN;
  94434. this.i1e21 = NaN;
  94435. this.i1e22 = NaN;
  94436. this.i2e00 = NaN;
  94437. this.i2e01 = NaN;
  94438. this.i2e02 = NaN;
  94439. this.i2e10 = NaN;
  94440. this.i2e11 = NaN;
  94441. this.i2e12 = NaN;
  94442. this.i2e20 = NaN;
  94443. this.i2e21 = NaN;
  94444. this.i2e22 = NaN;
  94445. this.motorDenom = NaN;
  94446. this.invMotorDenom = NaN;
  94447. this.invDenom = NaN;
  94448. this.ax = NaN;
  94449. this.ay = NaN;
  94450. this.az = NaN;
  94451. this.a1x = NaN;
  94452. this.a1y = NaN;
  94453. this.a1z = NaN;
  94454. this.a2x = NaN;
  94455. this.a2y = NaN;
  94456. this.a2z = NaN;
  94457. this.enableLimit = false;
  94458. this.lowerLimit = NaN;
  94459. this.upperLimit = NaN;
  94460. this.limitVelocity = NaN;
  94461. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  94462. this.enableMotor = false;
  94463. this.motorSpeed = NaN;
  94464. this.maxMotorForce = NaN;
  94465. this.maxMotorImpulse = NaN;
  94466. this.limitMotor = limitMotor;
  94467. this.b1 = joint.body1;
  94468. this.b2 = joint.body2;
  94469. this.a1 = this.b1.angularVelocity;
  94470. this.a2 = this.b2.angularVelocity;
  94471. this.i1 = this.b1.inverseInertia;
  94472. this.i2 = this.b2.inverseInertia;
  94473. this.limitImpulse = 0;
  94474. this.motorImpulse = 0;
  94475. }
  94476. OIMO.RotationalConstraint.prototype = {
  94477. constructor: OIMO.RotationalConstraint,
  94478. preSolve: function (timeStep, invTimeStep) {
  94479. this.ax = this.limitMotor.axis.x;
  94480. this.ay = this.limitMotor.axis.y;
  94481. this.az = this.limitMotor.axis.z;
  94482. this.lowerLimit = this.limitMotor.lowerLimit;
  94483. this.upperLimit = this.limitMotor.upperLimit;
  94484. this.motorSpeed = this.limitMotor.motorSpeed;
  94485. this.maxMotorForce = this.limitMotor.maxMotorForce;
  94486. this.enableMotor = this.maxMotorForce > 0;
  94487. var ti1 = this.i1.elements;
  94488. var ti2 = this.i2.elements;
  94489. this.i1e00 = ti1[0];
  94490. this.i1e01 = ti1[1];
  94491. this.i1e02 = ti1[2];
  94492. this.i1e10 = ti1[3];
  94493. this.i1e11 = ti1[4];
  94494. this.i1e12 = ti1[5];
  94495. this.i1e20 = ti1[6];
  94496. this.i1e21 = ti1[7];
  94497. this.i1e22 = ti1[8];
  94498. this.i2e00 = ti2[0];
  94499. this.i2e01 = ti2[1];
  94500. this.i2e02 = ti2[2];
  94501. this.i2e10 = ti2[3];
  94502. this.i2e11 = ti2[4];
  94503. this.i2e12 = ti2[5];
  94504. this.i2e20 = ti2[6];
  94505. this.i2e21 = ti2[7];
  94506. this.i2e22 = ti2[8];
  94507. var frequency = this.limitMotor.frequency;
  94508. var enableSpring = frequency > 0;
  94509. var enableLimit = this.lowerLimit <= this.upperLimit;
  94510. var angle = this.limitMotor.angle;
  94511. if (enableLimit) {
  94512. if (this.lowerLimit == this.upperLimit) {
  94513. if (this.limitState != 0) {
  94514. this.limitState = 0;
  94515. this.limitImpulse = 0;
  94516. }
  94517. this.limitVelocity = this.lowerLimit - angle;
  94518. } else if (angle < this.lowerLimit) {
  94519. if (this.limitState != -1) {
  94520. this.limitState = -1;
  94521. this.limitImpulse = 0;
  94522. }
  94523. this.limitVelocity = this.lowerLimit - angle;
  94524. } else if (angle > this.upperLimit) {
  94525. if (this.limitState != 1) {
  94526. this.limitState = 1;
  94527. this.limitImpulse = 0;
  94528. }
  94529. this.limitVelocity = this.upperLimit - angle;
  94530. } else {
  94531. this.limitState = 2;
  94532. this.limitImpulse = 0;
  94533. this.limitVelocity = 0;
  94534. }
  94535. if (!enableSpring) {
  94536. if (this.limitVelocity > 0.02) this.limitVelocity -= 0.02;
  94537. else if (this.limitVelocity < -0.02) this.limitVelocity += 0.02;
  94538. else this.limitVelocity = 0;
  94539. }
  94540. } else {
  94541. this.limitState = 2;
  94542. this.limitImpulse = 0;
  94543. }
  94544. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  94545. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  94546. } else {
  94547. this.motorImpulse = 0;
  94548. this.maxMotorImpulse = 0;
  94549. }
  94550. this.a1x = this.ax * this.i1e00 + this.ay * this.i1e01 + this.az * this.i1e02;
  94551. this.a1y = this.ax * this.i1e10 + this.ay * this.i1e11 + this.az * this.i1e12;
  94552. this.a1z = this.ax * this.i1e20 + this.ay * this.i1e21 + this.az * this.i1e22;
  94553. this.a2x = this.ax * this.i2e00 + this.ay * this.i2e01 + this.az * this.i2e02;
  94554. this.a2y = this.ax * this.i2e10 + this.ay * this.i2e11 + this.az * this.i2e12;
  94555. this.a2z = this.ax * this.i2e20 + this.ay * this.i2e21 + this.az * this.i2e22;
  94556. this.motorDenom = this.ax * (this.a1x + this.a2x) + this.ay * (this.a1y + this.a2y) + this.az * (this.a1z + this.a2z);
  94557. this.invMotorDenom = 1 / this.motorDenom;
  94558. if (enableSpring && this.limitState != 2) {
  94559. var omega = 6.2831853 * frequency;
  94560. var k = omega * omega * timeStep;
  94561. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  94562. this.cfm = this.motorDenom * dmp;
  94563. this.limitVelocity *= k * dmp;
  94564. } else {
  94565. this.cfm = 0;
  94566. this.limitVelocity *= invTimeStep * 0.05;
  94567. }
  94568. this.invDenom = 1 / (this.motorDenom + this.cfm);
  94569. this.limitImpulse *= 0.95;
  94570. this.motorImpulse *= 0.95;
  94571. var totalImpulse = this.limitImpulse + this.motorImpulse;
  94572. this.a1.x += totalImpulse * this.a1x;
  94573. this.a1.y += totalImpulse * this.a1y;
  94574. this.a1.z += totalImpulse * this.a1z;
  94575. this.a2.x -= totalImpulse * this.a2x;
  94576. this.a2.y -= totalImpulse * this.a2y;
  94577. this.a2.z -= totalImpulse * this.a2z;
  94578. },
  94579. solve: function () {
  94580. 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);
  94581. // motor part
  94582. var newMotorImpulse;
  94583. if (this.enableMotor) {
  94584. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  94585. var oldMotorImpulse = this.motorImpulse;
  94586. this.motorImpulse += newMotorImpulse;
  94587. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  94588. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  94589. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  94590. rvn -= newMotorImpulse * this.motorDenom;
  94591. } else newMotorImpulse = 0;
  94592. // limit part
  94593. var newLimitImpulse;
  94594. if (this.limitState != 2) {
  94595. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  94596. var oldLimitImpulse = this.limitImpulse;
  94597. this.limitImpulse += newLimitImpulse;
  94598. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  94599. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  94600. } else newLimitImpulse = 0;
  94601. var totalImpulse = newLimitImpulse + newMotorImpulse;
  94602. this.a1.x += totalImpulse * this.a1x;
  94603. this.a1.y += totalImpulse * this.a1y;
  94604. this.a1.z += totalImpulse * this.a1z;
  94605. this.a2.x -= totalImpulse * this.a2x;
  94606. this.a2.y -= totalImpulse * this.a2y;
  94607. this.a2.z -= totalImpulse * this.a2z;
  94608. }
  94609. }
  94610. /**
  94611. * A three-axis translational constraint for various joints.
  94612. * @author saharan
  94613. */
  94614. OIMO.Translational3Constraint = function (joint, limitMotor1, limitMotor2, limitMotor3) {
  94615. this.m1 = NaN;
  94616. this.m2 = NaN;
  94617. this.i1e00 = NaN;
  94618. this.i1e01 = NaN;
  94619. this.i1e02 = NaN;
  94620. this.i1e10 = NaN;
  94621. this.i1e11 = NaN;
  94622. this.i1e12 = NaN;
  94623. this.i1e20 = NaN;
  94624. this.i1e21 = NaN;
  94625. this.i1e22 = NaN;
  94626. this.i2e00 = NaN;
  94627. this.i2e01 = NaN;
  94628. this.i2e02 = NaN;
  94629. this.i2e10 = NaN;
  94630. this.i2e11 = NaN;
  94631. this.i2e12 = NaN;
  94632. this.i2e20 = NaN;
  94633. this.i2e21 = NaN;
  94634. this.i2e22 = NaN;
  94635. this.ax1 = NaN;
  94636. this.ay1 = NaN;
  94637. this.az1 = NaN;
  94638. this.ax2 = NaN;
  94639. this.ay2 = NaN;
  94640. this.az2 = NaN;
  94641. this.ax3 = NaN;
  94642. this.ay3 = NaN;
  94643. this.az3 = NaN;
  94644. this.r1x = NaN;
  94645. this.r1y = NaN;
  94646. this.r1z = NaN;
  94647. this.r2x = NaN;
  94648. this.r2y = NaN;
  94649. this.r2z = NaN;
  94650. this.t1x1 = NaN;// jacobians
  94651. this.t1y1 = NaN;
  94652. this.t1z1 = NaN;
  94653. this.t2x1 = NaN;
  94654. this.t2y1 = NaN;
  94655. this.t2z1 = NaN;
  94656. this.l1x1 = NaN;
  94657. this.l1y1 = NaN;
  94658. this.l1z1 = NaN;
  94659. this.l2x1 = NaN;
  94660. this.l2y1 = NaN;
  94661. this.l2z1 = NaN;
  94662. this.a1x1 = NaN;
  94663. this.a1y1 = NaN;
  94664. this.a1z1 = NaN;
  94665. this.a2x1 = NaN;
  94666. this.a2y1 = NaN;
  94667. this.a2z1 = NaN;
  94668. this.t1x2 = NaN;
  94669. this.t1y2 = NaN;
  94670. this.t1z2 = NaN;
  94671. this.t2x2 = NaN;
  94672. this.t2y2 = NaN;
  94673. this.t2z2 = NaN;
  94674. this.l1x2 = NaN;
  94675. this.l1y2 = NaN;
  94676. this.l1z2 = NaN;
  94677. this.l2x2 = NaN;
  94678. this.l2y2 = NaN;
  94679. this.l2z2 = NaN;
  94680. this.a1x2 = NaN;
  94681. this.a1y2 = NaN;
  94682. this.a1z2 = NaN;
  94683. this.a2x2 = NaN;
  94684. this.a2y2 = NaN;
  94685. this.a2z2 = NaN;
  94686. this.t1x3 = NaN;
  94687. this.t1y3 = NaN;
  94688. this.t1z3 = NaN;
  94689. this.t2x3 = NaN;
  94690. this.t2y3 = NaN;
  94691. this.t2z3 = NaN;
  94692. this.l1x3 = NaN;
  94693. this.l1y3 = NaN;
  94694. this.l1z3 = NaN;
  94695. this.l2x3 = NaN;
  94696. this.l2y3 = NaN;
  94697. this.l2z3 = NaN;
  94698. this.a1x3 = NaN;
  94699. this.a1y3 = NaN;
  94700. this.a1z3 = NaN;
  94701. this.a2x3 = NaN;
  94702. this.a2y3 = NaN;
  94703. this.a2z3 = NaN;
  94704. this.lowerLimit1 = NaN;
  94705. this.upperLimit1 = NaN;
  94706. this.limitVelocity1 = NaN;
  94707. this.limitState1 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  94708. this.enableMotor1 = false;
  94709. this.motorSpeed1 = NaN;
  94710. this.maxMotorForce1 = NaN;
  94711. this.maxMotorImpulse1 = NaN;
  94712. this.lowerLimit2 = NaN;
  94713. this.upperLimit2 = NaN;
  94714. this.limitVelocity2 = NaN;
  94715. this.limitState2 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  94716. this.enableMotor2 = false;
  94717. this.motorSpeed2 = NaN;
  94718. this.maxMotorForce2 = NaN;
  94719. this.maxMotorImpulse2 = NaN;
  94720. this.lowerLimit3 = NaN;
  94721. this.upperLimit3 = NaN;
  94722. this.limitVelocity3 = NaN;
  94723. this.limitState3 = 0; // -1: at lower, 0: locked, 1: at upper, 2: unlimited
  94724. this.enableMotor3 = false;
  94725. this.motorSpeed3 = NaN;
  94726. this.maxMotorForce3 = NaN;
  94727. this.maxMotorImpulse3 = NaN;
  94728. this.k00 = NaN; // K = J*M*JT
  94729. this.k01 = NaN;
  94730. this.k02 = NaN;
  94731. this.k10 = NaN;
  94732. this.k11 = NaN;
  94733. this.k12 = NaN;
  94734. this.k20 = NaN;
  94735. this.k21 = NaN;
  94736. this.k22 = NaN;
  94737. this.kv00 = NaN; // diagonals without CFMs
  94738. this.kv11 = NaN;
  94739. this.kv22 = NaN;
  94740. this.dv00 = NaN; // ...inverted
  94741. this.dv11 = NaN;
  94742. this.dv22 = NaN;
  94743. this.d00 = NaN; // K^-1
  94744. this.d01 = NaN;
  94745. this.d02 = NaN;
  94746. this.d10 = NaN;
  94747. this.d11 = NaN;
  94748. this.d12 = NaN;
  94749. this.d20 = NaN;
  94750. this.d21 = NaN;
  94751. this.d22 = NaN;
  94752. this.limitMotor1 = limitMotor1;
  94753. this.limitMotor2 = limitMotor2;
  94754. this.limitMotor3 = limitMotor3;
  94755. this.b1 = joint.body1;
  94756. this.b2 = joint.body2;
  94757. this.p1 = joint.anchorPoint1;
  94758. this.p2 = joint.anchorPoint2;
  94759. this.r1 = joint.relativeAnchorPoint1;
  94760. this.r2 = joint.relativeAnchorPoint2;
  94761. this.l1 = this.b1.linearVelocity;
  94762. this.l2 = this.b2.linearVelocity;
  94763. this.a1 = this.b1.angularVelocity;
  94764. this.a2 = this.b2.angularVelocity;
  94765. this.i1 = this.b1.inverseInertia;
  94766. this.i2 = this.b2.inverseInertia;
  94767. this.limitImpulse1 = 0;
  94768. this.motorImpulse1 = 0;
  94769. this.limitImpulse2 = 0;
  94770. this.motorImpulse2 = 0;
  94771. this.limitImpulse3 = 0;
  94772. this.motorImpulse3 = 0;
  94773. this.cfm1 = 0;// Constraint Force Mixing
  94774. this.cfm2 = 0;
  94775. this.cfm3 = 0;
  94776. this.weight = -1;
  94777. }
  94778. OIMO.Translational3Constraint.prototype = {
  94779. constructor: OIMO.Translational3Constraint,
  94780. preSolve: function (timeStep, invTimeStep) {
  94781. this.ax1 = this.limitMotor1.axis.x;
  94782. this.ay1 = this.limitMotor1.axis.y;
  94783. this.az1 = this.limitMotor1.axis.z;
  94784. this.ax2 = this.limitMotor2.axis.x;
  94785. this.ay2 = this.limitMotor2.axis.y;
  94786. this.az2 = this.limitMotor2.axis.z;
  94787. this.ax3 = this.limitMotor3.axis.x;
  94788. this.ay3 = this.limitMotor3.axis.y;
  94789. this.az3 = this.limitMotor3.axis.z;
  94790. this.lowerLimit1 = this.limitMotor1.lowerLimit;
  94791. this.upperLimit1 = this.limitMotor1.upperLimit;
  94792. this.motorSpeed1 = this.limitMotor1.motorSpeed;
  94793. this.maxMotorForce1 = this.limitMotor1.maxMotorForce;
  94794. this.enableMotor1 = this.maxMotorForce1 > 0;
  94795. this.lowerLimit2 = this.limitMotor2.lowerLimit;
  94796. this.upperLimit2 = this.limitMotor2.upperLimit;
  94797. this.motorSpeed2 = this.limitMotor2.motorSpeed;
  94798. this.maxMotorForce2 = this.limitMotor2.maxMotorForce;
  94799. this.enableMotor2 = this.maxMotorForce2 > 0;
  94800. this.lowerLimit3 = this.limitMotor3.lowerLimit;
  94801. this.upperLimit3 = this.limitMotor3.upperLimit;
  94802. this.motorSpeed3 = this.limitMotor3.motorSpeed;
  94803. this.maxMotorForce3 = this.limitMotor3.maxMotorForce;
  94804. this.enableMotor3 = this.maxMotorForce3 > 0;
  94805. this.m1 = this.b1.inverseMass;
  94806. this.m2 = this.b2.inverseMass;
  94807. var ti1 = this.i1.elements;
  94808. var ti2 = this.i2.elements;
  94809. this.i1e00 = ti1[0];
  94810. this.i1e01 = ti1[1];
  94811. this.i1e02 = ti1[2];
  94812. this.i1e10 = ti1[3];
  94813. this.i1e11 = ti1[4];
  94814. this.i1e12 = ti1[5];
  94815. this.i1e20 = ti1[6];
  94816. this.i1e21 = ti1[7];
  94817. this.i1e22 = ti1[8];
  94818. this.i2e00 = ti2[0];
  94819. this.i2e01 = ti2[1];
  94820. this.i2e02 = ti2[2];
  94821. this.i2e10 = ti2[3];
  94822. this.i2e11 = ti2[4];
  94823. this.i2e12 = ti2[5];
  94824. this.i2e20 = ti2[6];
  94825. this.i2e21 = ti2[7];
  94826. this.i2e22 = ti2[8];
  94827. var dx = this.p2.x - this.p1.x;
  94828. var dy = this.p2.y - this.p1.y;
  94829. var dz = this.p2.z - this.p1.z;
  94830. var d1 = dx * this.ax1 + dy * this.ay1 + dz * this.az1;
  94831. var d2 = dx * this.ax2 + dy * this.ay2 + dz * this.az2;
  94832. var d3 = dx * this.ax3 + dy * this.ay3 + dz * this.az3;
  94833. var frequency1 = this.limitMotor1.frequency;
  94834. var frequency2 = this.limitMotor2.frequency;
  94835. var frequency3 = this.limitMotor3.frequency;
  94836. var enableSpring1 = frequency1 > 0;
  94837. var enableSpring2 = frequency2 > 0;
  94838. var enableSpring3 = frequency3 > 0;
  94839. var enableLimit1 = this.lowerLimit1 <= this.upperLimit1;
  94840. var enableLimit2 = this.lowerLimit2 <= this.upperLimit2;
  94841. var enableLimit3 = this.lowerLimit3 <= this.upperLimit3;
  94842. // for stability
  94843. if (enableSpring1 && d1 > 20 || d1 < -20) {
  94844. enableSpring1 = false;
  94845. }
  94846. if (enableSpring2 && d2 > 20 || d2 < -20) {
  94847. enableSpring2 = false;
  94848. }
  94849. if (enableSpring3 && d3 > 20 || d3 < -20) {
  94850. enableSpring3 = false;
  94851. }
  94852. if (enableLimit1) {
  94853. if (this.lowerLimit1 == this.upperLimit1) {
  94854. if (this.limitState1 != 0) {
  94855. this.limitState1 = 0;
  94856. this.limitImpulse1 = 0;
  94857. }
  94858. this.limitVelocity1 = this.lowerLimit1 - d1;
  94859. if (!enableSpring1) d1 = this.lowerLimit1;
  94860. } else if (d1 < this.lowerLimit1) {
  94861. if (this.limitState1 != -1) {
  94862. this.limitState1 = -1;
  94863. this.limitImpulse1 = 0;
  94864. }
  94865. this.limitVelocity1 = this.lowerLimit1 - d1;
  94866. if (!enableSpring1) d1 = this.lowerLimit1;
  94867. } else if (d1 > this.upperLimit1) {
  94868. if (this.limitState1 != 1) {
  94869. this.limitState1 = 1;
  94870. this.limitImpulse1 = 0;
  94871. }
  94872. this.limitVelocity1 = this.upperLimit1 - d1;
  94873. if (!enableSpring1) d1 = this.upperLimit1;
  94874. } else {
  94875. this.limitState1 = 2;
  94876. this.limitImpulse1 = 0;
  94877. this.limitVelocity1 = 0;
  94878. }
  94879. if (!enableSpring1) {
  94880. if (this.limitVelocity1 > 0.005) this.limitVelocity1 -= 0.005;
  94881. else if (this.limitVelocity1 < -0.005) this.limitVelocity1 += 0.005;
  94882. else this.limitVelocity1 = 0;
  94883. }
  94884. } else {
  94885. this.limitState1 = 2;
  94886. this.limitImpulse1 = 0;
  94887. }
  94888. if (enableLimit2) {
  94889. if (this.lowerLimit2 == this.upperLimit2) {
  94890. if (this.limitState2 != 0) {
  94891. this.limitState2 = 0;
  94892. this.limitImpulse2 = 0;
  94893. }
  94894. this.limitVelocity2 = this.lowerLimit2 - d2;
  94895. if (!enableSpring2) d2 = this.lowerLimit2;
  94896. } else if (d2 < this.lowerLimit2) {
  94897. if (this.limitState2 != -1) {
  94898. this.limitState2 = -1;
  94899. this.limitImpulse2 = 0;
  94900. }
  94901. this.limitVelocity2 = this.lowerLimit2 - d2;
  94902. if (!enableSpring2) d2 = this.lowerLimit2;
  94903. } else if (d2 > this.upperLimit2) {
  94904. if (this.limitState2 != 1) {
  94905. this.limitState2 = 1;
  94906. this.limitImpulse2 = 0;
  94907. }
  94908. this.limitVelocity2 = this.upperLimit2 - d2;
  94909. if (!enableSpring2) d2 = this.upperLimit2;
  94910. } else {
  94911. this.limitState2 = 2;
  94912. this.limitImpulse2 = 0;
  94913. this.limitVelocity2 = 0;
  94914. }
  94915. if (!enableSpring2) {
  94916. if (this.limitVelocity2 > 0.005) this.limitVelocity2 -= 0.005;
  94917. else if (this.limitVelocity2 < -0.005) this.limitVelocity2 += 0.005;
  94918. else this.limitVelocity2 = 0;
  94919. }
  94920. } else {
  94921. this.limitState2 = 2;
  94922. this.limitImpulse2 = 0;
  94923. }
  94924. if (enableLimit3) {
  94925. if (this.lowerLimit3 == this.upperLimit3) {
  94926. if (this.limitState3 != 0) {
  94927. this.limitState3 = 0;
  94928. this.limitImpulse3 = 0;
  94929. }
  94930. this.limitVelocity3 = this.lowerLimit3 - d3;
  94931. if (!enableSpring3) d3 = this.lowerLimit3;
  94932. } else if (d3 < this.lowerLimit3) {
  94933. if (this.limitState3 != -1) {
  94934. this.limitState3 = -1;
  94935. this.limitImpulse3 = 0;
  94936. }
  94937. this.limitVelocity3 = this.lowerLimit3 - d3;
  94938. if (!enableSpring3) d3 = this.lowerLimit3;
  94939. } else if (d3 > this.upperLimit3) {
  94940. if (this.limitState3 != 1) {
  94941. this.limitState3 = 1;
  94942. this.limitImpulse3 = 0;
  94943. }
  94944. this.limitVelocity3 = this.upperLimit3 - d3;
  94945. if (!enableSpring3) d3 = this.upperLimit3;
  94946. } else {
  94947. this.limitState3 = 2;
  94948. this.limitImpulse3 = 0;
  94949. this.limitVelocity3 = 0;
  94950. }
  94951. if (!enableSpring3) {
  94952. if (this.limitVelocity3 > 0.005) this.limitVelocity3 -= 0.005;
  94953. else if (this.limitVelocity3 < -0.005) this.limitVelocity3 += 0.005;
  94954. else this.limitVelocity3 = 0;
  94955. }
  94956. } else {
  94957. this.limitState3 = 2;
  94958. this.limitImpulse3 = 0;
  94959. }
  94960. if (this.enableMotor1 && (this.limitState1 != 0 || enableSpring1)) {
  94961. this.maxMotorImpulse1 = this.maxMotorForce1 * timeStep;
  94962. } else {
  94963. this.motorImpulse1 = 0;
  94964. this.maxMotorImpulse1 = 0;
  94965. }
  94966. if (this.enableMotor2 && (this.limitState2 != 0 || enableSpring2)) {
  94967. this.maxMotorImpulse2 = this.maxMotorForce2 * timeStep;
  94968. } else {
  94969. this.motorImpulse2 = 0;
  94970. this.maxMotorImpulse2 = 0;
  94971. }
  94972. if (this.enableMotor3 && (this.limitState3 != 0 || enableSpring3)) {
  94973. this.maxMotorImpulse3 = this.maxMotorForce3 * timeStep;
  94974. } else {
  94975. this.motorImpulse3 = 0;
  94976. this.maxMotorImpulse3 = 0;
  94977. }
  94978. var rdx = d1 * this.ax1 + d2 * this.ax2 + d3 * this.ax2;
  94979. var rdy = d1 * this.ay1 + d2 * this.ay2 + d3 * this.ay2;
  94980. var rdz = d1 * this.az1 + d2 * this.az2 + d3 * this.az2;
  94981. var w1 = this.m2 / (this.m1 + this.m2);
  94982. if (this.weight >= 0) w1 = this.weight; // use given weight
  94983. var w2 = 1 - w1;
  94984. this.r1x = this.r1.x + rdx * w1;
  94985. this.r1y = this.r1.y + rdy * w1;
  94986. this.r1z = this.r1.z + rdz * w1;
  94987. this.r2x = this.r2.x - rdx * w2;
  94988. this.r2y = this.r2.y - rdy * w2;
  94989. this.r2z = this.r2.z - rdz * w2;
  94990. // build jacobians
  94991. this.t1x1 = this.r1y * this.az1 - this.r1z * this.ay1;
  94992. this.t1y1 = this.r1z * this.ax1 - this.r1x * this.az1;
  94993. this.t1z1 = this.r1x * this.ay1 - this.r1y * this.ax1;
  94994. this.t2x1 = this.r2y * this.az1 - this.r2z * this.ay1;
  94995. this.t2y1 = this.r2z * this.ax1 - this.r2x * this.az1;
  94996. this.t2z1 = this.r2x * this.ay1 - this.r2y * this.ax1;
  94997. this.l1x1 = this.ax1 * this.m1;
  94998. this.l1y1 = this.ay1 * this.m1;
  94999. this.l1z1 = this.az1 * this.m1;
  95000. this.l2x1 = this.ax1 * this.m2;
  95001. this.l2y1 = this.ay1 * this.m2;
  95002. this.l2z1 = this.az1 * this.m2;
  95003. this.a1x1 = this.t1x1 * this.i1e00 + this.t1y1 * this.i1e01 + this.t1z1 * this.i1e02;
  95004. this.a1y1 = this.t1x1 * this.i1e10 + this.t1y1 * this.i1e11 + this.t1z1 * this.i1e12;
  95005. this.a1z1 = this.t1x1 * this.i1e20 + this.t1y1 * this.i1e21 + this.t1z1 * this.i1e22;
  95006. this.a2x1 = this.t2x1 * this.i2e00 + this.t2y1 * this.i2e01 + this.t2z1 * this.i2e02;
  95007. this.a2y1 = this.t2x1 * this.i2e10 + this.t2y1 * this.i2e11 + this.t2z1 * this.i2e12;
  95008. this.a2z1 = this.t2x1 * this.i2e20 + this.t2y1 * this.i2e21 + this.t2z1 * this.i2e22;
  95009. this.t1x2 = this.r1y * this.az2 - this.r1z * this.ay2;
  95010. this.t1y2 = this.r1z * this.ax2 - this.r1x * this.az2;
  95011. this.t1z2 = this.r1x * this.ay2 - this.r1y * this.ax2;
  95012. this.t2x2 = this.r2y * this.az2 - this.r2z * this.ay2;
  95013. this.t2y2 = this.r2z * this.ax2 - this.r2x * this.az2;
  95014. this.t2z2 = this.r2x * this.ay2 - this.r2y * this.ax2;
  95015. this.l1x2 = this.ax2 * this.m1;
  95016. this.l1y2 = this.ay2 * this.m1;
  95017. this.l1z2 = this.az2 * this.m1;
  95018. this.l2x2 = this.ax2 * this.m2;
  95019. this.l2y2 = this.ay2 * this.m2;
  95020. this.l2z2 = this.az2 * this.m2;
  95021. this.a1x2 = this.t1x2 * this.i1e00 + this.t1y2 * this.i1e01 + this.t1z2 * this.i1e02;
  95022. this.a1y2 = this.t1x2 * this.i1e10 + this.t1y2 * this.i1e11 + this.t1z2 * this.i1e12;
  95023. this.a1z2 = this.t1x2 * this.i1e20 + this.t1y2 * this.i1e21 + this.t1z2 * this.i1e22;
  95024. this.a2x2 = this.t2x2 * this.i2e00 + this.t2y2 * this.i2e01 + this.t2z2 * this.i2e02;
  95025. this.a2y2 = this.t2x2 * this.i2e10 + this.t2y2 * this.i2e11 + this.t2z2 * this.i2e12;
  95026. this.a2z2 = this.t2x2 * this.i2e20 + this.t2y2 * this.i2e21 + this.t2z2 * this.i2e22;
  95027. this.t1x3 = this.r1y * this.az3 - this.r1z * this.ay3;
  95028. this.t1y3 = this.r1z * this.ax3 - this.r1x * this.az3;
  95029. this.t1z3 = this.r1x * this.ay3 - this.r1y * this.ax3;
  95030. this.t2x3 = this.r2y * this.az3 - this.r2z * this.ay3;
  95031. this.t2y3 = this.r2z * this.ax3 - this.r2x * this.az3;
  95032. this.t2z3 = this.r2x * this.ay3 - this.r2y * this.ax3;
  95033. this.l1x3 = this.ax3 * this.m1;
  95034. this.l1y3 = this.ay3 * this.m1;
  95035. this.l1z3 = this.az3 * this.m1;
  95036. this.l2x3 = this.ax3 * this.m2;
  95037. this.l2y3 = this.ay3 * this.m2;
  95038. this.l2z3 = this.az3 * this.m2;
  95039. this.a1x3 = this.t1x3 * this.i1e00 + this.t1y3 * this.i1e01 + this.t1z3 * this.i1e02;
  95040. this.a1y3 = this.t1x3 * this.i1e10 + this.t1y3 * this.i1e11 + this.t1z3 * this.i1e12;
  95041. this.a1z3 = this.t1x3 * this.i1e20 + this.t1y3 * this.i1e21 + this.t1z3 * this.i1e22;
  95042. this.a2x3 = this.t2x3 * this.i2e00 + this.t2y3 * this.i2e01 + this.t2z3 * this.i2e02;
  95043. this.a2y3 = this.t2x3 * this.i2e10 + this.t2y3 * this.i2e11 + this.t2z3 * this.i2e12;
  95044. this.a2z3 = this.t2x3 * this.i2e20 + this.t2y3 * this.i2e21 + this.t2z3 * this.i2e22;
  95045. // build an impulse matrix
  95046. var m12 = this.m1 + this.m2;
  95047. this.k00 = (this.ax1 * this.ax1 + this.ay1 * this.ay1 + this.az1 * this.az1) * m12;
  95048. this.k01 = (this.ax1 * this.ax2 + this.ay1 * this.ay2 + this.az1 * this.az2) * m12;
  95049. this.k02 = (this.ax1 * this.ax3 + this.ay1 * this.ay3 + this.az1 * this.az3) * m12;
  95050. this.k10 = (this.ax2 * this.ax1 + this.ay2 * this.ay1 + this.az2 * this.az1) * m12;
  95051. this.k11 = (this.ax2 * this.ax2 + this.ay2 * this.ay2 + this.az2 * this.az2) * m12;
  95052. this.k12 = (this.ax2 * this.ax3 + this.ay2 * this.ay3 + this.az2 * this.az3) * m12;
  95053. this.k20 = (this.ax3 * this.ax1 + this.ay3 * this.ay1 + this.az3 * this.az1) * m12;
  95054. this.k21 = (this.ax3 * this.ax2 + this.ay3 * this.ay2 + this.az3 * this.az2) * m12;
  95055. this.k22 = (this.ax3 * this.ax3 + this.ay3 * this.ay3 + this.az3 * this.az3) * m12;
  95056. this.k00 += this.t1x1 * this.a1x1 + this.t1y1 * this.a1y1 + this.t1z1 * this.a1z1;
  95057. this.k01 += this.t1x1 * this.a1x2 + this.t1y1 * this.a1y2 + this.t1z1 * this.a1z2;
  95058. this.k02 += this.t1x1 * this.a1x3 + this.t1y1 * this.a1y3 + this.t1z1 * this.a1z3;
  95059. this.k10 += this.t1x2 * this.a1x1 + this.t1y2 * this.a1y1 + this.t1z2 * this.a1z1;
  95060. this.k11 += this.t1x2 * this.a1x2 + this.t1y2 * this.a1y2 + this.t1z2 * this.a1z2;
  95061. this.k12 += this.t1x2 * this.a1x3 + this.t1y2 * this.a1y3 + this.t1z2 * this.a1z3;
  95062. this.k20 += this.t1x3 * this.a1x1 + this.t1y3 * this.a1y1 + this.t1z3 * this.a1z1;
  95063. this.k21 += this.t1x3 * this.a1x2 + this.t1y3 * this.a1y2 + this.t1z3 * this.a1z2;
  95064. this.k22 += this.t1x3 * this.a1x3 + this.t1y3 * this.a1y3 + this.t1z3 * this.a1z3;
  95065. this.k00 += this.t2x1 * this.a2x1 + this.t2y1 * this.a2y1 + this.t2z1 * this.a2z1;
  95066. this.k01 += this.t2x1 * this.a2x2 + this.t2y1 * this.a2y2 + this.t2z1 * this.a2z2;
  95067. this.k02 += this.t2x1 * this.a2x3 + this.t2y1 * this.a2y3 + this.t2z1 * this.a2z3;
  95068. this.k10 += this.t2x2 * this.a2x1 + this.t2y2 * this.a2y1 + this.t2z2 * this.a2z1;
  95069. this.k11 += this.t2x2 * this.a2x2 + this.t2y2 * this.a2y2 + this.t2z2 * this.a2z2;
  95070. this.k12 += this.t2x2 * this.a2x3 + this.t2y2 * this.a2y3 + this.t2z2 * this.a2z3;
  95071. this.k20 += this.t2x3 * this.a2x1 + this.t2y3 * this.a2y1 + this.t2z3 * this.a2z1;
  95072. this.k21 += this.t2x3 * this.a2x2 + this.t2y3 * this.a2y2 + this.t2z3 * this.a2z2;
  95073. this.k22 += this.t2x3 * this.a2x3 + this.t2y3 * this.a2y3 + this.t2z3 * this.a2z3;
  95074. this.kv00 = this.k00;
  95075. this.kv11 = this.k11;
  95076. this.kv22 = this.k22;
  95077. this.dv00 = 1 / this.kv00;
  95078. this.dv11 = 1 / this.kv11;
  95079. this.dv22 = 1 / this.kv22;
  95080. if (enableSpring1 && this.limitState1 != 2) {
  95081. var omega = 6.2831853 * frequency1;
  95082. var k = omega * omega * timeStep;
  95083. var dmp = invTimeStep / (k + 2 * this.limitMotor1.dampingRatio * omega);
  95084. this.cfm1 = this.kv00 * dmp;
  95085. this.limitVelocity1 *= k * dmp;
  95086. } else {
  95087. this.cfm1 = 0;
  95088. this.limitVelocity1 *= invTimeStep * 0.05;
  95089. }
  95090. if (enableSpring2 && this.limitState2 != 2) {
  95091. omega = 6.2831853 * frequency2;
  95092. k = omega * omega * timeStep;
  95093. dmp = invTimeStep / (k + 2 * this.limitMotor2.dampingRatio * omega);
  95094. this.cfm2 = this.kv11 * dmp;
  95095. this.limitVelocity2 *= k * dmp;
  95096. } else {
  95097. this.cfm2 = 0;
  95098. this.limitVelocity2 *= invTimeStep * 0.05;
  95099. }
  95100. if (enableSpring3 && this.limitState3 != 2) {
  95101. omega = 6.2831853 * frequency3;
  95102. k = omega * omega * timeStep;
  95103. dmp = invTimeStep / (k + 2 * this.limitMotor3.dampingRatio * omega);
  95104. this.cfm3 = this.kv22 * dmp;
  95105. this.limitVelocity3 *= k * dmp;
  95106. } else {
  95107. this.cfm3 = 0;
  95108. this.limitVelocity3 *= invTimeStep * 0.05;
  95109. }
  95110. this.k00 += this.cfm1;
  95111. this.k11 += this.cfm2;
  95112. this.k22 += this.cfm3;
  95113. var inv = 1 / (
  95114. this.k00 * (this.k11 * this.k22 - this.k21 * this.k12) +
  95115. this.k10 * (this.k21 * this.k02 - this.k01 * this.k22) +
  95116. this.k20 * (this.k01 * this.k12 - this.k11 * this.k02)
  95117. );
  95118. this.d00 = (this.k11 * this.k22 - this.k12 * this.k21) * inv;
  95119. this.d01 = (this.k02 * this.k21 - this.k01 * this.k22) * inv;
  95120. this.d02 = (this.k01 * this.k12 - this.k02 * this.k11) * inv;
  95121. this.d10 = (this.k12 * this.k20 - this.k10 * this.k22) * inv;
  95122. this.d11 = (this.k00 * this.k22 - this.k02 * this.k20) * inv;
  95123. this.d12 = (this.k02 * this.k10 - this.k00 * this.k12) * inv;
  95124. this.d20 = (this.k10 * this.k21 - this.k11 * this.k20) * inv;
  95125. this.d21 = (this.k01 * this.k20 - this.k00 * this.k21) * inv;
  95126. this.d22 = (this.k00 * this.k11 - this.k01 * this.k10) * inv;
  95127. // warm starting
  95128. var totalImpulse1 = this.limitImpulse1 + this.motorImpulse1;
  95129. var totalImpulse2 = this.limitImpulse2 + this.motorImpulse2;
  95130. var totalImpulse3 = this.limitImpulse3 + this.motorImpulse3;
  95131. this.l1.x += totalImpulse1 * this.l1x1 + totalImpulse2 * this.l1x2 + totalImpulse3 * this.l1x3;
  95132. this.l1.y += totalImpulse1 * this.l1y1 + totalImpulse2 * this.l1y2 + totalImpulse3 * this.l1y3;
  95133. this.l1.z += totalImpulse1 * this.l1z1 + totalImpulse2 * this.l1z2 + totalImpulse3 * this.l1z3;
  95134. this.a1.x += totalImpulse1 * this.a1x1 + totalImpulse2 * this.a1x2 + totalImpulse3 * this.a1x3;
  95135. this.a1.y += totalImpulse1 * this.a1y1 + totalImpulse2 * this.a1y2 + totalImpulse3 * this.a1y3;
  95136. this.a1.z += totalImpulse1 * this.a1z1 + totalImpulse2 * this.a1z2 + totalImpulse3 * this.a1z3;
  95137. this.l2.x -= totalImpulse1 * this.l2x1 + totalImpulse2 * this.l2x2 + totalImpulse3 * this.l2x3;
  95138. this.l2.y -= totalImpulse1 * this.l2y1 + totalImpulse2 * this.l2y2 + totalImpulse3 * this.l2y3;
  95139. this.l2.z -= totalImpulse1 * this.l2z1 + totalImpulse2 * this.l2z2 + totalImpulse3 * this.l2z3;
  95140. this.a2.x -= totalImpulse1 * this.a2x1 + totalImpulse2 * this.a2x2 + totalImpulse3 * this.a2x3;
  95141. this.a2.y -= totalImpulse1 * this.a2y1 + totalImpulse2 * this.a2y2 + totalImpulse3 * this.a2y3;
  95142. this.a2.z -= totalImpulse1 * this.a2z1 + totalImpulse2 * this.a2z2 + totalImpulse3 * this.a2z3;
  95143. },
  95144. solve: function () {
  95145. 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;
  95146. 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;
  95147. 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;
  95148. var rvn1 = rvx * this.ax1 + rvy * this.ay1 + rvz * this.az1;
  95149. var rvn2 = rvx * this.ax2 + rvy * this.ay2 + rvz * this.az2;
  95150. var rvn3 = rvx * this.ax3 + rvy * this.ay3 + rvz * this.az3;
  95151. var oldMotorImpulse1 = this.motorImpulse1;
  95152. var oldMotorImpulse2 = this.motorImpulse2;
  95153. var oldMotorImpulse3 = this.motorImpulse3;
  95154. var dMotorImpulse1 = 0;
  95155. var dMotorImpulse2 = 0;
  95156. var dMotorImpulse3 = 0;
  95157. if (this.enableMotor1) {
  95158. dMotorImpulse1 = (rvn1 - this.motorSpeed1) * this.dv00;
  95159. this.motorImpulse1 += dMotorImpulse1;
  95160. if (this.motorImpulse1 > this.maxMotorImpulse1) { // clamp motor impulse
  95161. this.motorImpulse1 = this.maxMotorImpulse1;
  95162. } else if (this.motorImpulse1 < -this.maxMotorImpulse1) {
  95163. this.motorImpulse1 = -this.maxMotorImpulse1;
  95164. }
  95165. dMotorImpulse1 = this.motorImpulse1 - oldMotorImpulse1;
  95166. }
  95167. if (this.enableMotor2) {
  95168. dMotorImpulse2 = (rvn2 - this.motorSpeed2) * this.dv11;
  95169. this.motorImpulse2 += dMotorImpulse2;
  95170. if (this.motorImpulse2 > this.maxMotorImpulse2) { // clamp motor impulse
  95171. this.motorImpulse2 = this.maxMotorImpulse2;
  95172. } else if (this.motorImpulse2 < -this.maxMotorImpulse2) {
  95173. this.motorImpulse2 = -this.maxMotorImpulse2;
  95174. }
  95175. dMotorImpulse2 = this.motorImpulse2 - oldMotorImpulse2;
  95176. }
  95177. if (this.enableMotor3) {
  95178. dMotorImpulse3 = (rvn3 - this.motorSpeed3) * this.dv22;
  95179. this.motorImpulse3 += dMotorImpulse3;
  95180. if (this.motorImpulse3 > this.maxMotorImpulse3) { // clamp motor impulse
  95181. this.motorImpulse3 = this.maxMotorImpulse3;
  95182. } else if (this.motorImpulse3 < -this.maxMotorImpulse3) {
  95183. this.motorImpulse3 = -this.maxMotorImpulse3;
  95184. }
  95185. dMotorImpulse3 = this.motorImpulse3 - oldMotorImpulse3;
  95186. }
  95187. // apply motor impulse to relative velocity
  95188. rvn1 += dMotorImpulse1 * this.kv00 + dMotorImpulse2 * this.k01 + dMotorImpulse3 * this.k02;
  95189. rvn2 += dMotorImpulse1 * this.k10 + dMotorImpulse2 * this.kv11 + dMotorImpulse3 * this.k12;
  95190. rvn3 += dMotorImpulse1 * this.k20 + dMotorImpulse2 * this.k21 + dMotorImpulse3 * this.kv22;
  95191. // subtract target velocity and applied impulse
  95192. rvn1 -= this.limitVelocity1 + this.limitImpulse1 * this.cfm1;
  95193. rvn2 -= this.limitVelocity2 + this.limitImpulse2 * this.cfm2;
  95194. rvn3 -= this.limitVelocity3 + this.limitImpulse3 * this.cfm3;
  95195. var oldLimitImpulse1 = this.limitImpulse1;
  95196. var oldLimitImpulse2 = this.limitImpulse2;
  95197. var oldLimitImpulse3 = this.limitImpulse3;
  95198. var dLimitImpulse1 = rvn1 * this.d00 + rvn2 * this.d01 + rvn3 * this.d02;
  95199. var dLimitImpulse2 = rvn1 * this.d10 + rvn2 * this.d11 + rvn3 * this.d12;
  95200. var dLimitImpulse3 = rvn1 * this.d20 + rvn2 * this.d21 + rvn3 * this.d22;
  95201. this.limitImpulse1 += dLimitImpulse1;
  95202. this.limitImpulse2 += dLimitImpulse2;
  95203. this.limitImpulse3 += dLimitImpulse3;
  95204. // clamp
  95205. var clampState = 0;
  95206. if (this.limitState1 == 2 || this.limitImpulse1 * this.limitState1 < 0) {
  95207. dLimitImpulse1 = -oldLimitImpulse1;
  95208. rvn2 += dLimitImpulse1 * this.k10;
  95209. rvn3 += dLimitImpulse1 * this.k20;
  95210. clampState |= 1;
  95211. }
  95212. if (this.limitState2 == 2 || this.limitImpulse2 * this.limitState2 < 0) {
  95213. dLimitImpulse2 = -oldLimitImpulse2;
  95214. rvn1 += dLimitImpulse2 * this.k01;
  95215. rvn3 += dLimitImpulse2 * this.k21;
  95216. clampState |= 2;
  95217. }
  95218. if (this.limitState3 == 2 || this.limitImpulse3 * this.limitState3 < 0) {
  95219. dLimitImpulse3 = -oldLimitImpulse3;
  95220. rvn1 += dLimitImpulse3 * this.k02;
  95221. rvn2 += dLimitImpulse3 * this.k12;
  95222. clampState |= 4;
  95223. }
  95224. // update un-clamped impulse
  95225. // TODO: isolate division
  95226. var det;
  95227. switch (clampState) {
  95228. case 1:// update 2 3
  95229. det = 1 / (this.k11 * this.k22 - this.k12 * this.k21);
  95230. dLimitImpulse2 = (this.k22 * rvn2 + -this.k12 * rvn3) * det;
  95231. dLimitImpulse3 = (-this.k21 * rvn2 + this.k11 * rvn3) * det;
  95232. break;
  95233. case 2:// update 1 3
  95234. det = 1 / (this.k00 * this.k22 - this.k02 * this.k20);
  95235. dLimitImpulse1 = (this.k22 * rvn1 + -this.k02 * rvn3) * det;
  95236. dLimitImpulse3 = (-this.k20 * rvn1 + this.k00 * rvn3) * det;
  95237. break;
  95238. case 3:// update 3
  95239. dLimitImpulse3 = rvn3 / this.k22;
  95240. break;
  95241. case 4:// update 1 2
  95242. det = 1 / (this.k00 * this.k11 - this.k01 * this.k10);
  95243. dLimitImpulse1 = (this.k11 * rvn1 + -this.k01 * rvn2) * det;
  95244. dLimitImpulse2 = (-this.k10 * rvn1 + this.k00 * rvn2) * det;
  95245. break;
  95246. case 5:// update 2
  95247. dLimitImpulse2 = rvn2 / this.k11;
  95248. break;
  95249. case 6:// update 1
  95250. dLimitImpulse1 = rvn1 / this.k00;
  95251. break;
  95252. }
  95253. this.limitImpulse1 = oldLimitImpulse1 + dLimitImpulse1;
  95254. this.limitImpulse2 = oldLimitImpulse2 + dLimitImpulse2;
  95255. this.limitImpulse3 = oldLimitImpulse3 + dLimitImpulse3;
  95256. var dImpulse1 = dMotorImpulse1 + dLimitImpulse1;
  95257. var dImpulse2 = dMotorImpulse2 + dLimitImpulse2;
  95258. var dImpulse3 = dMotorImpulse3 + dLimitImpulse3;
  95259. // apply impulse
  95260. this.l1.x += dImpulse1 * this.l1x1 + dImpulse2 * this.l1x2 + dImpulse3 * this.l1x3;
  95261. this.l1.y += dImpulse1 * this.l1y1 + dImpulse2 * this.l1y2 + dImpulse3 * this.l1y3;
  95262. this.l1.z += dImpulse1 * this.l1z1 + dImpulse2 * this.l1z2 + dImpulse3 * this.l1z3;
  95263. this.a1.x += dImpulse1 * this.a1x1 + dImpulse2 * this.a1x2 + dImpulse3 * this.a1x3;
  95264. this.a1.y += dImpulse1 * this.a1y1 + dImpulse2 * this.a1y2 + dImpulse3 * this.a1y3;
  95265. this.a1.z += dImpulse1 * this.a1z1 + dImpulse2 * this.a1z2 + dImpulse3 * this.a1z3;
  95266. this.l2.x -= dImpulse1 * this.l2x1 + dImpulse2 * this.l2x2 + dImpulse3 * this.l2x3;
  95267. this.l2.y -= dImpulse1 * this.l2y1 + dImpulse2 * this.l2y2 + dImpulse3 * this.l2y3;
  95268. this.l2.z -= dImpulse1 * this.l2z1 + dImpulse2 * this.l2z2 + dImpulse3 * this.l2z3;
  95269. this.a2.x -= dImpulse1 * this.a2x1 + dImpulse2 * this.a2x2 + dImpulse3 * this.a2x3;
  95270. this.a2.y -= dImpulse1 * this.a2y1 + dImpulse2 * this.a2y2 + dImpulse3 * this.a2y3;
  95271. this.a2.z -= dImpulse1 * this.a2z1 + dImpulse2 * this.a2z2 + dImpulse3 * this.a2z3;
  95272. }
  95273. }
  95274. /**
  95275. * A translational constraint for various joints.
  95276. * @author saharan
  95277. */
  95278. OIMO.TranslationalConstraint = function (joint, limitMotor) {
  95279. this.cfm = NaN;
  95280. this.m1 = NaN;
  95281. this.m2 = NaN;
  95282. this.i1e00 = NaN;
  95283. this.i1e01 = NaN;
  95284. this.i1e02 = NaN;
  95285. this.i1e10 = NaN;
  95286. this.i1e11 = NaN;
  95287. this.i1e12 = NaN;
  95288. this.i1e20 = NaN;
  95289. this.i1e21 = NaN;
  95290. this.i1e22 = NaN;
  95291. this.i2e00 = NaN;
  95292. this.i2e01 = NaN;
  95293. this.i2e02 = NaN;
  95294. this.i2e10 = NaN;
  95295. this.i2e11 = NaN;
  95296. this.i2e12 = NaN;
  95297. this.i2e20 = NaN;
  95298. this.i2e21 = NaN;
  95299. this.i2e22 = NaN;
  95300. this.motorDenom = NaN;
  95301. this.invMotorDenom = NaN;
  95302. this.invDenom = NaN;
  95303. this.ax = NaN;
  95304. this.ay = NaN;
  95305. this.az = NaN;
  95306. this.r1x = NaN;
  95307. this.r1y = NaN;
  95308. this.r1z = NaN;
  95309. this.r2x = NaN;
  95310. this.r2y = NaN;
  95311. this.r2z = NaN;
  95312. this.t1x = NaN;
  95313. this.t1y = NaN;
  95314. this.t1z = NaN;
  95315. this.t2x = NaN;
  95316. this.t2y = NaN;
  95317. this.t2z = NaN;
  95318. this.l1x = NaN;
  95319. this.l1y = NaN;
  95320. this.l1z = NaN;
  95321. this.l2x = NaN;
  95322. this.l2y = NaN;
  95323. this.l2z = NaN;
  95324. this.a1x = NaN;
  95325. this.a1y = NaN;
  95326. this.a1z = NaN;
  95327. this.a2x = NaN;
  95328. this.a2y = NaN;
  95329. this.a2z = NaN;
  95330. this.lowerLimit = NaN;
  95331. this.upperLimit = NaN;
  95332. this.limitVelocity = NaN;
  95333. this.limitState = 0; // -1: at lower, 0: locked, 1: at upper, 2: free
  95334. this.enableMotor = false;
  95335. this.motorSpeed = NaN;
  95336. this.maxMotorForce = NaN;
  95337. this.maxMotorImpulse = NaN;
  95338. this.limitMotor = limitMotor;
  95339. this.b1 = joint.body1;
  95340. this.b2 = joint.body2;
  95341. this.p1 = joint.anchorPoint1;
  95342. this.p2 = joint.anchorPoint2;
  95343. this.r1 = joint.relativeAnchorPoint1;
  95344. this.r2 = joint.relativeAnchorPoint2;
  95345. this.l1 = this.b1.linearVelocity;
  95346. this.l2 = this.b2.linearVelocity;
  95347. this.a1 = this.b1.angularVelocity;
  95348. this.a2 = this.b2.angularVelocity;
  95349. this.i1 = this.b1.inverseInertia;
  95350. this.i2 = this.b2.inverseInertia;
  95351. this.limitImpulse = 0;
  95352. this.motorImpulse = 0;
  95353. }
  95354. OIMO.TranslationalConstraint.prototype = {
  95355. constructor: OIMO.TranslationalConstraint,
  95356. preSolve: function (timeStep, invTimeStep) {
  95357. this.ax = this.limitMotor.axis.x;
  95358. this.ay = this.limitMotor.axis.y;
  95359. this.az = this.limitMotor.axis.z;
  95360. this.lowerLimit = this.limitMotor.lowerLimit;
  95361. this.upperLimit = this.limitMotor.upperLimit;
  95362. this.motorSpeed = this.limitMotor.motorSpeed;
  95363. this.maxMotorForce = this.limitMotor.maxMotorForce;
  95364. this.enableMotor = this.maxMotorForce > 0;
  95365. this.m1 = this.b1.inverseMass;
  95366. this.m2 = this.b2.inverseMass;
  95367. var ti1 = this.i1.elements;
  95368. var ti2 = this.i2.elements;
  95369. this.i1e00 = ti1[0];
  95370. this.i1e01 = ti1[1];
  95371. this.i1e02 = ti1[2];
  95372. this.i1e10 = ti1[3];
  95373. this.i1e11 = ti1[4];
  95374. this.i1e12 = ti1[5];
  95375. this.i1e20 = ti1[6];
  95376. this.i1e21 = ti1[7];
  95377. this.i1e22 = ti1[8];
  95378. this.i2e00 = ti2[0];
  95379. this.i2e01 = ti2[1];
  95380. this.i2e02 = ti2[2];
  95381. this.i2e10 = ti2[3];
  95382. this.i2e11 = ti2[4];
  95383. this.i2e12 = ti2[5];
  95384. this.i2e20 = ti2[6];
  95385. this.i2e21 = ti2[7];
  95386. this.i2e22 = ti2[8];
  95387. var dx = this.p2.x - this.p1.x;
  95388. var dy = this.p2.y - this.p1.y;
  95389. var dz = this.p2.z - this.p1.z;
  95390. var d = dx * this.ax + dy * this.ay + dz * this.az;
  95391. var frequency = this.limitMotor.frequency;
  95392. var enableSpring = frequency > 0;
  95393. var enableLimit = this.lowerLimit <= this.upperLimit;
  95394. if (enableSpring && d > 20 || d < -20) {
  95395. enableSpring = false;
  95396. }
  95397. if (enableLimit) {
  95398. if (this.lowerLimit == this.upperLimit) {
  95399. if (this.limitState != 0) {
  95400. this.limitState = 0;
  95401. this.limitImpulse = 0;
  95402. }
  95403. this.limitVelocity = this.lowerLimit - d;
  95404. if (!enableSpring) d = this.lowerLimit;
  95405. } else if (d < this.lowerLimit) {
  95406. if (this.limitState != -1) {
  95407. this.limitState = -1;
  95408. this.limitImpulse = 0;
  95409. }
  95410. this.limitVelocity = this.lowerLimit - d;
  95411. if (!enableSpring) d = this.lowerLimit;
  95412. } else if (d > this.upperLimit) {
  95413. if (this.limitState != 1) {
  95414. this.limitState = 1;
  95415. this.limitImpulse = 0;
  95416. }
  95417. this.limitVelocity = this.upperLimit - d;
  95418. if (!enableSpring) d = this.upperLimit;
  95419. } else {
  95420. this.limitState = 2;
  95421. this.limitImpulse = 0;
  95422. this.limitVelocity = 0;
  95423. }
  95424. if (!enableSpring) {
  95425. if (this.limitVelocity > 0.005) this.limitVelocity -= 0.005;
  95426. else if (this.limitVelocity < -0.005) this.limitVelocity += 0.005;
  95427. else this.limitVelocity = 0;
  95428. }
  95429. } else {
  95430. this.limitState = 2;
  95431. this.limitImpulse = 0;
  95432. }
  95433. if (this.enableMotor && (this.limitState != 0 || enableSpring)) {
  95434. this.maxMotorImpulse = this.maxMotorForce * timeStep;
  95435. } else {
  95436. this.motorImpulse = 0;
  95437. this.maxMotorImpulse = 0;
  95438. }
  95439. var rdx = d * this.ax;
  95440. var rdy = d * this.ay;
  95441. var rdz = d * this.az;
  95442. var w1 = this.m1 / (this.m1 + this.m2);
  95443. var w2 = 1 - w1;
  95444. this.r1x = this.r1.x + rdx * w1;
  95445. this.r1y = this.r1.y + rdy * w1;
  95446. this.r1z = this.r1.z + rdz * w1;
  95447. this.r2x = this.r2.x - rdx * w2;
  95448. this.r2y = this.r2.y - rdy * w2;
  95449. this.r2z = this.r2.z - rdz * w2;
  95450. this.t1x = this.r1y * this.az - this.r1z * this.ay;
  95451. this.t1y = this.r1z * this.ax - this.r1x * this.az;
  95452. this.t1z = this.r1x * this.ay - this.r1y * this.ax;
  95453. this.t2x = this.r2y * this.az - this.r2z * this.ay;
  95454. this.t2y = this.r2z * this.ax - this.r2x * this.az;
  95455. this.t2z = this.r2x * this.ay - this.r2y * this.ax;
  95456. this.l1x = this.ax * this.m1;
  95457. this.l1y = this.ay * this.m1;
  95458. this.l1z = this.az * this.m1;
  95459. this.l2x = this.ax * this.m2;
  95460. this.l2y = this.ay * this.m2;
  95461. this.l2z = this.az * this.m2;
  95462. this.a1x = this.t1x * this.i1e00 + this.t1y * this.i1e01 + this.t1z * this.i1e02;
  95463. this.a1y = this.t1x * this.i1e10 + this.t1y * this.i1e11 + this.t1z * this.i1e12;
  95464. this.a1z = this.t1x * this.i1e20 + this.t1y * this.i1e21 + this.t1z * this.i1e22;
  95465. this.a2x = this.t2x * this.i2e00 + this.t2y * this.i2e01 + this.t2z * this.i2e02;
  95466. this.a2y = this.t2x * this.i2e10 + this.t2y * this.i2e11 + this.t2z * this.i2e12;
  95467. this.a2z = this.t2x * this.i2e20 + this.t2y * this.i2e21 + this.t2z * this.i2e22;
  95468. this.motorDenom =
  95469. this.m1 + this.m2 +
  95470. this.ax * (this.a1y * this.r1z - this.a1z * this.r1y + this.a2y * this.r2z - this.a2z * this.r2y) +
  95471. this.ay * (this.a1z * this.r1x - this.a1x * this.r1z + this.a2z * this.r2x - this.a2x * this.r2z) +
  95472. this.az * (this.a1x * this.r1y - this.a1y * this.r1x + this.a2x * this.r2y - this.a2y * this.r2x);
  95473. this.invMotorDenom = 1 / this.motorDenom;
  95474. if (enableSpring && this.limitState != 2) {
  95475. var omega = 6.2831853 * frequency;
  95476. var k = omega * omega * timeStep;
  95477. var dmp = invTimeStep / (k + 2 * this.limitMotor.dampingRatio * omega);
  95478. this.cfm = this.motorDenom * dmp;
  95479. this.limitVelocity *= k * dmp;
  95480. } else {
  95481. this.cfm = 0;
  95482. this.limitVelocity *= invTimeStep * 0.05;
  95483. }
  95484. this.invDenom = 1 / (this.motorDenom + this.cfm);
  95485. var totalImpulse = this.limitImpulse + this.motorImpulse;
  95486. this.l1.x += totalImpulse * this.l1x;
  95487. this.l1.y += totalImpulse * this.l1y;
  95488. this.l1.z += totalImpulse * this.l1z;
  95489. this.a1.x += totalImpulse * this.a1x;
  95490. this.a1.y += totalImpulse * this.a1y;
  95491. this.a1.z += totalImpulse * this.a1z;
  95492. this.l2.x -= totalImpulse * this.l2x;
  95493. this.l2.y -= totalImpulse * this.l2y;
  95494. this.l2.z -= totalImpulse * this.l2z;
  95495. this.a2.x -= totalImpulse * this.a2x;
  95496. this.a2.y -= totalImpulse * this.a2y;
  95497. this.a2.z -= totalImpulse * this.a2z;
  95498. },
  95499. solve: function () {
  95500. var rvn =
  95501. this.ax * (this.l2.x - this.l1.x) + this.ay * (this.l2.y - this.l1.y) + this.az * (this.l2.z - this.l1.z) +
  95502. 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;
  95503. // motor part
  95504. var newMotorImpulse;
  95505. if (this.enableMotor) {
  95506. newMotorImpulse = (rvn - this.motorSpeed) * this.invMotorDenom;
  95507. var oldMotorImpulse = this.motorImpulse;
  95508. this.motorImpulse += newMotorImpulse;
  95509. if (this.motorImpulse > this.maxMotorImpulse) this.motorImpulse = this.maxMotorImpulse;
  95510. else if (this.motorImpulse < -this.maxMotorImpulse) this.motorImpulse = -this.maxMotorImpulse;
  95511. newMotorImpulse = this.motorImpulse - oldMotorImpulse;
  95512. rvn -= newMotorImpulse * this.motorDenom;
  95513. } else newMotorImpulse = 0;
  95514. // limit part
  95515. var newLimitImpulse;
  95516. if (this.limitState != 2) {
  95517. newLimitImpulse = (rvn - this.limitVelocity - this.limitImpulse * this.cfm) * this.invDenom;
  95518. var oldLimitImpulse = this.limitImpulse;
  95519. this.limitImpulse += newLimitImpulse;
  95520. if (this.limitImpulse * this.limitState < 0) this.limitImpulse = 0;
  95521. newLimitImpulse = this.limitImpulse - oldLimitImpulse;
  95522. } else newLimitImpulse = 0;
  95523. var totalImpulse = newLimitImpulse + newMotorImpulse;
  95524. this.l1.x += totalImpulse * this.l1x;
  95525. this.l1.y += totalImpulse * this.l1y;
  95526. this.l1.z += totalImpulse * this.l1z;
  95527. this.a1.x += totalImpulse * this.a1x;
  95528. this.a1.y += totalImpulse * this.a1y;
  95529. this.a1.z += totalImpulse * this.a1z;
  95530. this.l2.x -= totalImpulse * this.l2x;
  95531. this.l2.y -= totalImpulse * this.l2y;
  95532. this.l2.z -= totalImpulse * this.l2z;
  95533. this.a2.x -= totalImpulse * this.a2x;
  95534. this.a2.y -= totalImpulse * this.a2y;
  95535. this.a2.z -= totalImpulse * this.a2z;
  95536. }
  95537. }
  95538. /**
  95539. * A contact is a pair of shapes whose axis-aligned bounding boxes are overlapping.
  95540. * @author saharan
  95541. */
  95542. OIMO.Contact = function () {
  95543. // The first shape.
  95544. this.shape1 = null;
  95545. // The second shape.
  95546. this.shape2 = null;
  95547. // The first rigid body.
  95548. this.body1 = null;
  95549. // The second rigid body.
  95550. this.body2 = null;
  95551. // The previous contact in the world.
  95552. this.prev = null;
  95553. // The next contact in the world.
  95554. this.next = null;
  95555. // Internal
  95556. this.persisting = false;
  95557. // Whether both the rigid bodies are sleeping or not.
  95558. this.sleeping = false;
  95559. // The collision detector between two shapes.
  95560. this.detector = null;
  95561. // The contact constraint of the contact.
  95562. this.constraint = null;
  95563. // Whether the shapes are touching or not.
  95564. this.touching = false;
  95565. this.b1Link = new OIMO.ContactLink(this);
  95566. this.b2Link = new OIMO.ContactLink(this);
  95567. this.s1Link = new OIMO.ContactLink(this);
  95568. this.s2Link = new OIMO.ContactLink(this);
  95569. // The contact manifold of the contact.
  95570. this.manifold = new OIMO.ContactManifold();
  95571. this.buffer = [];// vector 4
  95572. this.buffer.length = 4;
  95573. this.buffer[0] = new OIMO.ImpulseDataBuffer();
  95574. this.buffer[1] = new OIMO.ImpulseDataBuffer();
  95575. this.buffer[2] = new OIMO.ImpulseDataBuffer();
  95576. this.buffer[3] = new OIMO.ImpulseDataBuffer();
  95577. this.points = this.manifold.points;
  95578. this.constraint = new OIMO.ContactConstraint(this.manifold);
  95579. }
  95580. OIMO.Contact.prototype = {
  95581. constructor: OIMO.Contact,
  95582. mixRestitution: function (restitution1, restitution2) {
  95583. return OIMO.sqrt(restitution1 * restitution2);
  95584. },
  95585. mixFriction: function (friction1, friction2) {
  95586. return OIMO.sqrt(friction1 * friction2);
  95587. },
  95588. /**
  95589. * Update the contact manifold.
  95590. */
  95591. updateManifold: function () {
  95592. this.constraint.restitution = this.mixRestitution(this.shape1.restitution, this.shape2.restitution);
  95593. this.constraint.friction = this.mixFriction(this.shape1.friction, this.shape2.friction);
  95594. var numBuffers = this.manifold.numPoints;
  95595. var i = numBuffers;
  95596. while (i--) {
  95597. //for(var i=0;i<numBuffers;i++){
  95598. var b = this.buffer[i];
  95599. var p = this.points[i];
  95600. b.lp1X = p.localPoint1.x;
  95601. b.lp1Y = p.localPoint1.y;
  95602. b.lp1Z = p.localPoint1.z;
  95603. b.lp2X = p.localPoint2.x;
  95604. b.lp2Y = p.localPoint2.y;
  95605. b.lp2Z = p.localPoint2.z;
  95606. b.impulse = p.normalImpulse;
  95607. }
  95608. this.manifold.numPoints = 0;
  95609. this.detector.detectCollision(this.shape1, this.shape2, this.manifold);
  95610. var num = this.manifold.numPoints;
  95611. if (num == 0) {
  95612. this.touching = false;
  95613. return;
  95614. }
  95615. this.touching = true;
  95616. i = num;
  95617. while (i--) {
  95618. //for(i=0; i<num; i++){
  95619. p = this.points[i];
  95620. var lp1x = p.localPoint1.x;
  95621. var lp1y = p.localPoint1.y;
  95622. var lp1z = p.localPoint1.z;
  95623. var lp2x = p.localPoint2.x;
  95624. var lp2y = p.localPoint2.y;
  95625. var lp2z = p.localPoint2.z;
  95626. var index = -1;
  95627. var minDistance = 0.0004;
  95628. var j = numBuffers;
  95629. while (j--) {
  95630. //for(var j=0;j<numBuffers;j++){
  95631. b = this.buffer[j];
  95632. var dx = b.lp1X - lp1x;
  95633. var dy = b.lp1Y - lp1y;
  95634. var dz = b.lp1Z - lp1z;
  95635. var distance1 = dx * dx + dy * dy + dz * dz;
  95636. dx = b.lp2X - lp2x;
  95637. dy = b.lp2Y - lp2y;
  95638. dz = b.lp2Z - lp2z;
  95639. var distance2 = dx * dx + dy * dy + dz * dz;
  95640. if (distance1 < distance2) {
  95641. if (distance1 < minDistance) {
  95642. minDistance = distance1;
  95643. index = j;
  95644. }
  95645. } else {
  95646. if (distance2 < minDistance) {
  95647. minDistance = distance2;
  95648. index = j;
  95649. }
  95650. }
  95651. }
  95652. if (index != -1) {
  95653. var tmp = this.buffer[index];
  95654. this.buffer[index] = this.buffer[--numBuffers];
  95655. this.buffer[numBuffers] = tmp;
  95656. p.normalImpulse = tmp.impulse;
  95657. p.warmStarted = true;
  95658. } else {
  95659. p.normalImpulse = 0;
  95660. p.warmStarted = false;
  95661. }
  95662. }
  95663. },
  95664. /**
  95665. * Attach the contact to the shapes.
  95666. * @param shape1
  95667. * @param shape2
  95668. */
  95669. attach: function (shape1, shape2) {
  95670. this.shape1 = shape1;
  95671. this.shape2 = shape2;
  95672. this.body1 = shape1.parent;
  95673. this.body2 = shape2.parent;
  95674. this.manifold.body1 = this.body1;
  95675. this.manifold.body2 = this.body2;
  95676. this.constraint.body1 = this.body1;
  95677. this.constraint.body2 = this.body2;
  95678. this.constraint.attach();
  95679. this.s1Link.shape = shape2;
  95680. this.s1Link.body = this.body2;
  95681. this.s2Link.shape = shape1;
  95682. this.s2Link.body = this.body1;
  95683. if (shape1.contactLink != null) (this.s1Link.next = shape1.contactLink).prev = this.s1Link;
  95684. else this.s1Link.next = null;
  95685. shape1.contactLink = this.s1Link;
  95686. shape1.numContacts++;
  95687. if (shape2.contactLink != null) (this.s2Link.next = shape2.contactLink).prev = this.s2Link;
  95688. else this.s2Link.next = null;
  95689. shape2.contactLink = this.s2Link;
  95690. shape2.numContacts++;
  95691. this.b1Link.shape = shape2;
  95692. this.b1Link.body = this.body2;
  95693. this.b2Link.shape = shape1;
  95694. this.b2Link.body = this.body1;
  95695. if (this.body1.contactLink != null) (this.b1Link.next = this.body1.contactLink).prev = this.b1Link;
  95696. else this.b1Link.next = null;
  95697. this.body1.contactLink = this.b1Link;
  95698. this.body1.numContacts++;
  95699. if (this.body2.contactLink != null) (this.b2Link.next = this.body2.contactLink).prev = this.b2Link;
  95700. else this.b2Link.next = null;
  95701. this.body2.contactLink = this.b2Link;
  95702. this.body2.numContacts++;
  95703. this.prev = null;
  95704. this.next = null;
  95705. this.persisting = true;
  95706. this.sleeping = this.body1.sleeping && this.body2.sleeping;
  95707. this.manifold.numPoints = 0;
  95708. },
  95709. /**
  95710. * Detach the contact from the shapes.
  95711. */
  95712. detach: function () {
  95713. var prev = this.s1Link.prev;
  95714. var next = this.s1Link.next;
  95715. if (prev !== null) prev.next = next;
  95716. if (next !== null) next.prev = prev;
  95717. if (this.shape1.contactLink == this.s1Link) this.shape1.contactLink = next;
  95718. this.s1Link.prev = null;
  95719. this.s1Link.next = null;
  95720. this.s1Link.shape = null;
  95721. this.s1Link.body = null;
  95722. this.shape1.numContacts--;
  95723. prev = this.s2Link.prev;
  95724. next = this.s2Link.next;
  95725. if (prev !== null) prev.next = next;
  95726. if (next !== null) next.prev = prev;
  95727. if (this.shape2.contactLink == this.s2Link) this.shape2.contactLink = next;
  95728. this.s2Link.prev = null;
  95729. this.s2Link.next = null;
  95730. this.s2Link.shape = null;
  95731. this.s2Link.body = null;
  95732. this.shape2.numContacts--;
  95733. prev = this.b1Link.prev;
  95734. next = this.b1Link.next;
  95735. if (prev !== null) prev.next = next;
  95736. if (next !== null) next.prev = prev;
  95737. if (this.body1.contactLink == this.b1Link) this.body1.contactLink = next;
  95738. this.b1Link.prev = null;
  95739. this.b1Link.next = null;
  95740. this.b1Link.shape = null;
  95741. this.b1Link.body = null;
  95742. this.body1.numContacts--;
  95743. prev = this.b2Link.prev;
  95744. next = this.b2Link.next;
  95745. if (prev !== null) prev.next = next;
  95746. if (next !== null) next.prev = prev;
  95747. if (this.body2.contactLink == this.b2Link) this.body2.contactLink = next;
  95748. this.b2Link.prev = null;
  95749. this.b2Link.next = null;
  95750. this.b2Link.shape = null;
  95751. this.b2Link.body = null;
  95752. this.body2.numContacts--;
  95753. this.manifold.body1 = null;
  95754. this.manifold.body2 = null;
  95755. this.constraint.body1 = null;
  95756. this.constraint.body2 = null;
  95757. this.constraint.detach();
  95758. this.shape1 = null;
  95759. this.shape2 = null;
  95760. this.body1 = null;
  95761. this.body2 = null;
  95762. }
  95763. }
  95764. /**
  95765. * ...
  95766. * @author saharan
  95767. */
  95768. OIMO.ContactConstraint = function (manifold) {
  95769. OIMO.Constraint.call(this);
  95770. // The contact manifold of the constraint.
  95771. this.manifold = manifold;
  95772. // The coefficient of restitution of the constraint.
  95773. this.restitution = NaN;
  95774. // The coefficient of friction of the constraint.
  95775. this.friction = NaN;
  95776. this.p1 = null;
  95777. this.p2 = null;
  95778. this.lv1 = null;
  95779. this.lv2 = null;
  95780. this.av1 = null;
  95781. this.av2 = null;
  95782. this.i1 = null;
  95783. this.i2 = null;
  95784. this.ii1 = null;
  95785. this.ii2 = null;
  95786. this.m1 = NaN;
  95787. this.m2 = NaN;
  95788. this.num = 0;
  95789. this.ps = manifold.points;
  95790. this.cs = new OIMO.ContactPointDataBuffer();
  95791. this.cs.next = new OIMO.ContactPointDataBuffer();
  95792. this.cs.next.next = new OIMO.ContactPointDataBuffer();
  95793. this.cs.next.next.next = new OIMO.ContactPointDataBuffer();
  95794. }
  95795. OIMO.ContactConstraint.prototype = Object.create(OIMO.Constraint.prototype);
  95796. /**
  95797. * Attach the constraint to the bodies.
  95798. */
  95799. OIMO.ContactConstraint.prototype.attach = function () {
  95800. this.p1 = this.body1.position;
  95801. this.p2 = this.body2.position;
  95802. this.lv1 = this.body1.linearVelocity;
  95803. this.av1 = this.body1.angularVelocity;
  95804. this.lv2 = this.body2.linearVelocity;
  95805. this.av2 = this.body2.angularVelocity;
  95806. this.i1 = this.body1.inverseInertia;
  95807. this.i2 = this.body2.inverseInertia;
  95808. }
  95809. /**
  95810. * Detach the constraint from the bodies.
  95811. */
  95812. OIMO.ContactConstraint.prototype.detach = function () {
  95813. this.p1 = null;
  95814. this.p2 = null;
  95815. this.lv1 = null;
  95816. this.lv2 = null;
  95817. this.av1 = null;
  95818. this.av2 = null;
  95819. this.i1 = null;
  95820. this.i2 = null;
  95821. }
  95822. OIMO.ContactConstraint.prototype.preSolve = function (timeStep, invTimeStep) {
  95823. this.m1 = this.body1.inverseMass;
  95824. this.m2 = this.body2.inverseMass;
  95825. this.ii1 = this.i1.clone();
  95826. this.ii2 = this.i2.clone();
  95827. var ii1 = this.ii1.elements;
  95828. var ii2 = this.ii2.elements;
  95829. var p1x = this.p1.x;
  95830. var p1y = this.p1.y;
  95831. var p1z = this.p1.z;
  95832. var p2x = this.p2.x;
  95833. var p2y = this.p2.y;
  95834. var p2z = this.p2.z;
  95835. var m1m2 = this.m1 + this.m2;
  95836. this.num = this.manifold.numPoints;
  95837. var c = this.cs;
  95838. for (var i = 0; i < this.num; i++) {
  95839. var p = this.ps[i];
  95840. var tmp1X;
  95841. var tmp1Y;
  95842. var tmp1Z;
  95843. var tmp2X;
  95844. var tmp2Y;
  95845. var tmp2Z;
  95846. tmp1X = p.position.x;
  95847. tmp1Y = p.position.y;
  95848. tmp1Z = p.position.z;
  95849. var rp1X = tmp1X - p1x;
  95850. var rp1Y = tmp1Y - p1y;
  95851. var rp1Z = tmp1Z - p1z;
  95852. var rp2X = tmp1X - p2x;
  95853. var rp2Y = tmp1Y - p2y;
  95854. var rp2Z = tmp1Z - p2z;
  95855. c.rp1X = rp1X;
  95856. c.rp1Y = rp1Y;
  95857. c.rp1Z = rp1Z;
  95858. c.rp2X = rp2X;
  95859. c.rp2Y = rp2Y;
  95860. c.rp2Z = rp2Z;
  95861. c.norImp = p.normalImpulse;
  95862. c.tanImp = p.tangentImpulse;
  95863. c.binImp = p.binormalImpulse;
  95864. var norX = p.normal.x;
  95865. var norY = p.normal.y;
  95866. var norZ = p.normal.z;
  95867. var rvX = (this.lv2.x + this.av2.y * rp2Z - this.av2.z * rp2Y) - (this.lv1.x + this.av1.y * rp1Z - this.av1.z * rp1Y);
  95868. var rvY = (this.lv2.y + this.av2.z * rp2X - this.av2.x * rp2Z) - (this.lv1.y + this.av1.z * rp1X - this.av1.x * rp1Z);
  95869. var rvZ = (this.lv2.z + this.av2.x * rp2Y - this.av2.y * rp2X) - (this.lv1.z + this.av1.x * rp1Y - this.av1.y * rp1X);
  95870. var rvn = norX * rvX + norY * rvY + norZ * rvZ;
  95871. var tanX = rvX - rvn * norX;
  95872. var tanY = rvY - rvn * norY;
  95873. var tanZ = rvZ - rvn * norZ;
  95874. var len = tanX * tanX + tanY * tanY + tanZ * tanZ;
  95875. if (len > 0.04) {
  95876. len = 1 / OIMO.sqrt(len);
  95877. } else {
  95878. tanX = norY * norX - norZ * norZ;
  95879. tanY = -norZ * norY - norX * norX;
  95880. tanZ = norX * norZ + norY * norY;
  95881. len = 1 / OIMO.sqrt(tanX * tanX + tanY * tanY + tanZ * tanZ);
  95882. }
  95883. tanX *= len;
  95884. tanY *= len;
  95885. tanZ *= len;
  95886. var binX = norY * tanZ - norZ * tanY;
  95887. var binY = norZ * tanX - norX * tanZ;
  95888. var binZ = norX * tanY - norY * tanX;
  95889. c.norX = norX;
  95890. c.norY = norY;
  95891. c.norZ = norZ;
  95892. c.tanX = tanX;
  95893. c.tanY = tanY;
  95894. c.tanZ = tanZ;
  95895. c.binX = binX;
  95896. c.binY = binY;
  95897. c.binZ = binZ;
  95898. c.norU1X = norX * this.m1;
  95899. c.norU1Y = norY * this.m1;
  95900. c.norU1Z = norZ * this.m1;
  95901. c.norU2X = norX * this.m2;
  95902. c.norU2Y = norY * this.m2;
  95903. c.norU2Z = norZ * this.m2;
  95904. c.tanU1X = tanX * this.m1;
  95905. c.tanU1Y = tanY * this.m1;
  95906. c.tanU1Z = tanZ * this.m1;
  95907. c.tanU2X = tanX * this.m2;
  95908. c.tanU2Y = tanY * this.m2;
  95909. c.tanU2Z = tanZ * this.m2;
  95910. c.binU1X = binX * this.m1;
  95911. c.binU1Y = binY * this.m1;
  95912. c.binU1Z = binZ * this.m1;
  95913. c.binU2X = binX * this.m2;
  95914. c.binU2Y = binY * this.m2;
  95915. c.binU2Z = binZ * this.m2;
  95916. var norT1X = rp1Y * norZ - rp1Z * norY;
  95917. var norT1Y = rp1Z * norX - rp1X * norZ;
  95918. var norT1Z = rp1X * norY - rp1Y * norX;
  95919. var norT2X = rp2Y * norZ - rp2Z * norY;
  95920. var norT2Y = rp2Z * norX - rp2X * norZ;
  95921. var norT2Z = rp2X * norY - rp2Y * norX;
  95922. var tanT1X = rp1Y * tanZ - rp1Z * tanY;
  95923. var tanT1Y = rp1Z * tanX - rp1X * tanZ;
  95924. var tanT1Z = rp1X * tanY - rp1Y * tanX;
  95925. var tanT2X = rp2Y * tanZ - rp2Z * tanY;
  95926. var tanT2Y = rp2Z * tanX - rp2X * tanZ;
  95927. var tanT2Z = rp2X * tanY - rp2Y * tanX;
  95928. var binT1X = rp1Y * binZ - rp1Z * binY;
  95929. var binT1Y = rp1Z * binX - rp1X * binZ;
  95930. var binT1Z = rp1X * binY - rp1Y * binX;
  95931. var binT2X = rp2Y * binZ - rp2Z * binY;
  95932. var binT2Y = rp2Z * binX - rp2X * binZ;
  95933. var binT2Z = rp2X * binY - rp2Y * binX;
  95934. var norTU1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  95935. var norTU1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  95936. var norTU1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  95937. var norTU2X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  95938. var norTU2Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  95939. var norTU2Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  95940. var tanTU1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  95941. var tanTU1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  95942. var tanTU1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  95943. var tanTU2X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  95944. var tanTU2Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  95945. var tanTU2Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  95946. var binTU1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  95947. var binTU1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  95948. var binTU1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  95949. var binTU2X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  95950. var binTU2Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  95951. var binTU2Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  95952. c.norT1X = norT1X;
  95953. c.norT1Y = norT1Y;
  95954. c.norT1Z = norT1Z;
  95955. c.tanT1X = tanT1X;
  95956. c.tanT1Y = tanT1Y;
  95957. c.tanT1Z = tanT1Z;
  95958. c.binT1X = binT1X;
  95959. c.binT1Y = binT1Y;
  95960. c.binT1Z = binT1Z;
  95961. c.norT2X = norT2X;
  95962. c.norT2Y = norT2Y;
  95963. c.norT2Z = norT2Z;
  95964. c.tanT2X = tanT2X;
  95965. c.tanT2Y = tanT2Y;
  95966. c.tanT2Z = tanT2Z;
  95967. c.binT2X = binT2X;
  95968. c.binT2Y = binT2Y;
  95969. c.binT2Z = binT2Z;
  95970. c.norTU1X = norTU1X;
  95971. c.norTU1Y = norTU1Y;
  95972. c.norTU1Z = norTU1Z;
  95973. c.tanTU1X = tanTU1X;
  95974. c.tanTU1Y = tanTU1Y;
  95975. c.tanTU1Z = tanTU1Z;
  95976. c.binTU1X = binTU1X;
  95977. c.binTU1Y = binTU1Y;
  95978. c.binTU1Z = binTU1Z;
  95979. c.norTU2X = norTU2X;
  95980. c.norTU2Y = norTU2Y;
  95981. c.norTU2Z = norTU2Z;
  95982. c.tanTU2X = tanTU2X;
  95983. c.tanTU2Y = tanTU2Y;
  95984. c.tanTU2Z = tanTU2Z;
  95985. c.binTU2X = binTU2X;
  95986. c.binTU2Y = binTU2Y;
  95987. c.binTU2Z = binTU2Z;
  95988. tmp1X = norT1X * ii1[0] + norT1Y * ii1[1] + norT1Z * ii1[2];
  95989. tmp1Y = norT1X * ii1[3] + norT1Y * ii1[4] + norT1Z * ii1[5];
  95990. tmp1Z = norT1X * ii1[6] + norT1Y * ii1[7] + norT1Z * ii1[8];
  95991. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  95992. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  95993. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  95994. tmp1X = norT2X * ii2[0] + norT2Y * ii2[1] + norT2Z * ii2[2];
  95995. tmp1Y = norT2X * ii2[3] + norT2Y * ii2[4] + norT2Z * ii2[5];
  95996. tmp1Z = norT2X * ii2[6] + norT2Y * ii2[7] + norT2Z * ii2[8];
  95997. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  95998. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  95999. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  96000. var norDen = 1 / (m1m2 + norX * tmp2X + norY * tmp2Y + norZ * tmp2Z);
  96001. tmp1X = tanT1X * ii1[0] + tanT1Y * ii1[1] + tanT1Z * ii1[2];
  96002. tmp1Y = tanT1X * ii1[3] + tanT1Y * ii1[4] + tanT1Z * ii1[5];
  96003. tmp1Z = tanT1X * ii1[6] + tanT1Y * ii1[7] + tanT1Z * ii1[8];
  96004. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  96005. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  96006. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  96007. tmp1X = tanT2X * ii2[0] + tanT2Y * ii2[1] + tanT2Z * ii2[2];
  96008. tmp1Y = tanT2X * ii2[3] + tanT2Y * ii2[4] + tanT2Z * ii2[5];
  96009. tmp1Z = tanT2X * ii2[6] + tanT2Y * ii2[7] + tanT2Z * ii2[8];
  96010. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  96011. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  96012. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  96013. var tanDen = 1 / (m1m2 + tanX * tmp2X + tanY * tmp2Y + tanZ * tmp2Z);
  96014. tmp1X = binT1X * ii1[0] + binT1Y * ii1[1] + binT1Z * ii1[2];
  96015. tmp1Y = binT1X * ii1[3] + binT1Y * ii1[4] + binT1Z * ii1[5];
  96016. tmp1Z = binT1X * ii1[6] + binT1Y * ii1[7] + binT1Z * ii1[8];
  96017. tmp2X = tmp1Y * rp1Z - tmp1Z * rp1Y;
  96018. tmp2Y = tmp1Z * rp1X - tmp1X * rp1Z;
  96019. tmp2Z = tmp1X * rp1Y - tmp1Y * rp1X;
  96020. tmp1X = binT2X * ii2[0] + binT2Y * ii2[1] + binT2Z * ii2[2];
  96021. tmp1Y = binT2X * ii2[3] + binT2Y * ii2[4] + binT2Z * ii2[5];
  96022. tmp1Z = binT2X * ii2[6] + binT2Y * ii2[7] + binT2Z * ii2[8];
  96023. tmp2X += tmp1Y * rp2Z - tmp1Z * rp2Y;
  96024. tmp2Y += tmp1Z * rp2X - tmp1X * rp2Z;
  96025. tmp2Z += tmp1X * rp2Y - tmp1Y * rp2X;
  96026. var binDen = 1 / (m1m2 + binX * tmp2X + binY * tmp2Y + binZ * tmp2Z);
  96027. c.norDen = norDen;
  96028. c.tanDen = tanDen;
  96029. c.binDen = binDen;
  96030. if (p.warmStarted) {
  96031. var norImp = p.normalImpulse;
  96032. this.lv1.x += c.norU1X * norImp;
  96033. this.lv1.y += c.norU1Y * norImp;
  96034. this.lv1.z += c.norU1Z * norImp;
  96035. this.av1.x += norTU1X * norImp;
  96036. this.av1.y += norTU1Y * norImp;
  96037. this.av1.z += norTU1Z * norImp;
  96038. this.lv2.x -= c.norU2X * norImp;
  96039. this.lv2.y -= c.norU2Y * norImp;
  96040. this.lv2.z -= c.norU2Z * norImp;
  96041. this.av2.x -= norTU2X * norImp;
  96042. this.av2.y -= norTU2Y * norImp;
  96043. this.av2.z -= norTU2Z * norImp;
  96044. c.norImp = norImp;
  96045. c.tanImp = 0;
  96046. c.binImp = 0;
  96047. rvn = 0; // disable bouncing
  96048. } else {
  96049. c.norImp = 0;
  96050. c.tanImp = 0;
  96051. c.binImp = 0;
  96052. }
  96053. if (rvn > -1) {
  96054. rvn = 0; // disable bouncing
  96055. }
  96056. var norTar = this.restitution * -rvn;
  96057. var sepV = -(p.penetration + 0.005) * invTimeStep * 0.05; // allow 0.5cm error
  96058. if (norTar < sepV) norTar = sepV;
  96059. c.norTar = norTar;
  96060. c.last = i == this.num - 1;
  96061. c = c.next;
  96062. }
  96063. }
  96064. OIMO.ContactConstraint.prototype.solve = function () {
  96065. var lv1x = this.lv1.x;
  96066. var lv1y = this.lv1.y;
  96067. var lv1z = this.lv1.z;
  96068. var lv2x = this.lv2.x;
  96069. var lv2y = this.lv2.y;
  96070. var lv2z = this.lv2.z;
  96071. var av1x = this.av1.x;
  96072. var av1y = this.av1.y;
  96073. var av1z = this.av1.z;
  96074. var av2x = this.av2.x;
  96075. var av2y = this.av2.y;
  96076. var av2z = this.av2.z;
  96077. var c = this.cs;
  96078. while (true) {
  96079. var oldImp1;
  96080. var newImp1;
  96081. var oldImp2;
  96082. var newImp2;
  96083. var rvn;
  96084. var norImp = c.norImp;
  96085. var tanImp = c.tanImp;
  96086. var binImp = c.binImp;
  96087. var max = -norImp * this.friction;
  96088. var rvX = lv2x - lv1x;
  96089. var rvY = lv2y - lv1y;
  96090. var rvZ = lv2z - lv1z;
  96091. rvn =
  96092. rvX * c.tanX + rvY * c.tanY + rvZ * c.tanZ +
  96093. av2x * c.tanT2X + av2y * c.tanT2Y + av2z * c.tanT2Z -
  96094. av1x * c.tanT1X - av1y * c.tanT1Y - av1z * c.tanT1Z
  96095. ;
  96096. oldImp1 = tanImp;
  96097. newImp1 = rvn * c.tanDen;
  96098. tanImp += newImp1;
  96099. rvn =
  96100. rvX * c.binX + rvY * c.binY + rvZ * c.binZ +
  96101. av2x * c.binT2X + av2y * c.binT2Y + av2z * c.binT2Z -
  96102. av1x * c.binT1X - av1y * c.binT1Y - av1z * c.binT1Z
  96103. ;
  96104. oldImp2 = binImp;
  96105. newImp2 = rvn * c.binDen;
  96106. binImp += newImp2;
  96107. // cone friction clamp
  96108. var len = tanImp * tanImp + binImp * binImp;
  96109. if (len > max * max) {
  96110. len = max / OIMO.sqrt(len);
  96111. tanImp *= len;
  96112. binImp *= len;
  96113. }
  96114. newImp1 = tanImp - oldImp1;
  96115. newImp2 = binImp - oldImp2;
  96116. lv1x += c.tanU1X * newImp1 + c.binU1X * newImp2;
  96117. lv1y += c.tanU1Y * newImp1 + c.binU1Y * newImp2;
  96118. lv1z += c.tanU1Z * newImp1 + c.binU1Z * newImp2;
  96119. av1x += c.tanTU1X * newImp1 + c.binTU1X * newImp2;
  96120. av1y += c.tanTU1Y * newImp1 + c.binTU1Y * newImp2;
  96121. av1z += c.tanTU1Z * newImp1 + c.binTU1Z * newImp2;
  96122. lv2x -= c.tanU2X * newImp1 + c.binU2X * newImp2;
  96123. lv2y -= c.tanU2Y * newImp1 + c.binU2Y * newImp2;
  96124. lv2z -= c.tanU2Z * newImp1 + c.binU2Z * newImp2;
  96125. av2x -= c.tanTU2X * newImp1 + c.binTU2X * newImp2;
  96126. av2y -= c.tanTU2Y * newImp1 + c.binTU2Y * newImp2;
  96127. av2z -= c.tanTU2Z * newImp1 + c.binTU2Z * newImp2;
  96128. // restitution part
  96129. rvn =
  96130. (lv2x - lv1x) * c.norX + (lv2y - lv1y) * c.norY + (lv2z - lv1z) * c.norZ +
  96131. av2x * c.norT2X + av2y * c.norT2Y + av2z * c.norT2Z -
  96132. av1x * c.norT1X - av1y * c.norT1Y - av1z * c.norT1Z;
  96133. oldImp1 = norImp;
  96134. newImp1 = (rvn - c.norTar) * c.norDen;
  96135. norImp += newImp1;
  96136. if (norImp > 0) norImp = 0;
  96137. newImp1 = norImp - oldImp1;
  96138. lv1x += c.norU1X * newImp1;
  96139. lv1y += c.norU1Y * newImp1;
  96140. lv1z += c.norU1Z * newImp1;
  96141. av1x += c.norTU1X * newImp1;
  96142. av1y += c.norTU1Y * newImp1;
  96143. av1z += c.norTU1Z * newImp1;
  96144. lv2x -= c.norU2X * newImp1;
  96145. lv2y -= c.norU2Y * newImp1;
  96146. lv2z -= c.norU2Z * newImp1;
  96147. av2x -= c.norTU2X * newImp1;
  96148. av2y -= c.norTU2Y * newImp1;
  96149. av2z -= c.norTU2Z * newImp1;
  96150. c.norImp = norImp;
  96151. c.tanImp = tanImp;
  96152. c.binImp = binImp;
  96153. if (c.last) break;
  96154. c = c.next;
  96155. }
  96156. this.lv1.x = lv1x;
  96157. this.lv1.y = lv1y;
  96158. this.lv1.z = lv1z;
  96159. this.lv2.x = lv2x;
  96160. this.lv2.y = lv2y;
  96161. this.lv2.z = lv2z;
  96162. this.av1.x = av1x;
  96163. this.av1.y = av1y;
  96164. this.av1.z = av1z;
  96165. this.av2.x = av2x;
  96166. this.av2.y = av2y;
  96167. this.av2.z = av2z;
  96168. }
  96169. OIMO.ContactConstraint.prototype.postSolve = function () {
  96170. var c = this.cs;
  96171. var i = this.num;
  96172. while (i--) {
  96173. //for(var i=0;i<this.num;i++){
  96174. var p = this.ps[i];
  96175. p.normal.x = c.norX;
  96176. p.normal.y = c.norY;
  96177. p.normal.z = c.norZ;
  96178. p.tangent.x = c.tanX;
  96179. p.tangent.y = c.tanY;
  96180. p.tangent.z = c.tanZ;
  96181. p.binormal.x = c.binX;
  96182. p.binormal.y = c.binY;
  96183. p.binormal.z = c.binZ;
  96184. p.normalImpulse = c.norImp;
  96185. p.tangentImpulse = c.tanImp;
  96186. p.binormalImpulse = c.binImp;
  96187. p.normalDenominator = c.norDen;
  96188. p.tangentDenominator = c.tanDen;
  96189. p.binormalDenominator = c.binDen;
  96190. c = c.next;
  96191. }
  96192. }
  96193. /**
  96194. * A link list of contacts.
  96195. * @author saharan
  96196. */
  96197. OIMO.ContactLink = function (contact) {
  96198. // The previous contact link.
  96199. this.prev = null;
  96200. // The next contact link.
  96201. this.next = null;
  96202. // The shape of the contact.
  96203. this.shape = null;
  96204. // The other rigid body.
  96205. this.body = null;
  96206. // The contact of the link.
  96207. this.contact = contact;
  96208. }
  96209. /**
  96210. * A contact manifold between two shapes.
  96211. * @author saharan
  96212. */
  96213. OIMO.ContactManifold = function () {
  96214. // The first rigid body.
  96215. this.body1 = null;
  96216. // The second rigid body.
  96217. this.body2 = null;
  96218. // The number of manifold points.
  96219. this.numPoints = 0;
  96220. // The manifold points.
  96221. this.points = [];
  96222. this.points.length = 4;
  96223. this.points[0] = new OIMO.ManifoldPoint();
  96224. this.points[1] = new OIMO.ManifoldPoint();
  96225. this.points[2] = new OIMO.ManifoldPoint();
  96226. this.points[3] = new OIMO.ManifoldPoint();
  96227. }
  96228. OIMO.ContactManifold.prototype = {
  96229. constructor: OIMO.ContactManifold,
  96230. /**
  96231. * Reset the manifold.
  96232. * @param shape1
  96233. * @param shape2
  96234. */
  96235. reset: function (shape1, shape2) {
  96236. this.body1 = shape1.parent;
  96237. this.body2 = shape2.parent;
  96238. this.numPoints = 0;
  96239. },
  96240. /**
  96241. * Add a point into this manifold.
  96242. * @param x
  96243. * @param y
  96244. * @param z
  96245. * @param normalX
  96246. * @param normalY
  96247. * @param normalZ
  96248. * @param penetration
  96249. * @param flip
  96250. */
  96251. addPoint: function (x, y, z, normalX, normalY, normalZ, penetration, flip) {
  96252. var p = this.points[this.numPoints++];
  96253. p.position.x = x;
  96254. p.position.y = y;
  96255. p.position.z = z;
  96256. var r = this.body1.rotation;
  96257. var rx = x - this.body1.position.x;
  96258. var ry = y - this.body1.position.y;
  96259. var rz = z - this.body1.position.z;
  96260. var tr = r.elements;
  96261. p.localPoint1.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  96262. p.localPoint1.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  96263. p.localPoint1.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  96264. r = this.body2.rotation;
  96265. rx = x - this.body2.position.x;
  96266. ry = y - this.body2.position.y;
  96267. rz = z - this.body2.position.z;
  96268. p.localPoint2.x = rx * tr[0] + ry * tr[3] + rz * tr[6];
  96269. p.localPoint2.y = rx * tr[1] + ry * tr[4] + rz * tr[7];
  96270. p.localPoint2.z = rx * tr[2] + ry * tr[5] + rz * tr[8];
  96271. p.normalImpulse = 0;
  96272. if (flip) {
  96273. p.normal.x = -normalX;
  96274. p.normal.y = -normalY;
  96275. p.normal.z = -normalZ;
  96276. } else {
  96277. p.normal.x = normalX;
  96278. p.normal.y = normalY;
  96279. p.normal.z = normalZ;
  96280. }
  96281. p.penetration = penetration;
  96282. p.warmStarted = false;
  96283. }
  96284. }
  96285. OIMO.ContactPointDataBuffer = function () {
  96286. this.norX = NaN;
  96287. this.norY = NaN;
  96288. this.norZ = NaN;
  96289. this.tanX = NaN;
  96290. this.tanY = NaN;
  96291. this.tanZ = NaN;
  96292. this.binX = NaN;
  96293. this.binY = NaN;
  96294. this.binZ = NaN;
  96295. this.rp1X = NaN;
  96296. this.rp1Y = NaN;
  96297. this.rp1Z = NaN;
  96298. this.rp2X = NaN;
  96299. this.rp2Y = NaN;
  96300. this.rp2Z = NaN;
  96301. this.norU1X = NaN;
  96302. this.norU1Y = NaN;
  96303. this.norU1Z = NaN;
  96304. this.norU2X = NaN;
  96305. this.norU2Y = NaN;
  96306. this.norU2Z = NaN;
  96307. this.tanU1X = NaN;
  96308. this.tanU1Y = NaN;
  96309. this.tanU1Z = NaN;
  96310. this.tanU2X = NaN;
  96311. this.tanU2Y = NaN;
  96312. this.tanU2Z = NaN;
  96313. this.binU1X = NaN;
  96314. this.binU1Y = NaN;
  96315. this.binU1Z = NaN;
  96316. this.binU2X = NaN;
  96317. this.binU2Y = NaN;
  96318. this.binU2Z = NaN;
  96319. this.norT1X = NaN;
  96320. this.norT1Y = NaN;
  96321. this.norT1Z = NaN;
  96322. this.norT2X = NaN;
  96323. this.norT2Y = NaN;
  96324. this.norT2Z = NaN;
  96325. this.tanT1X = NaN;
  96326. this.tanT1Y = NaN;
  96327. this.tanT1Z = NaN;
  96328. this.tanT2X = NaN;
  96329. this.tanT2Y = NaN;
  96330. this.tanT2Z = NaN;
  96331. this.binT1X = NaN;
  96332. this.binT1Y = NaN;
  96333. this.binT1Z = NaN;
  96334. this.binT2X = NaN;
  96335. this.binT2Y = NaN;
  96336. this.binT2Z = NaN;
  96337. this.norTU1X = NaN;
  96338. this.norTU1Y = NaN;
  96339. this.norTU1Z = NaN;
  96340. this.norTU2X = NaN;
  96341. this.norTU2Y = NaN;
  96342. this.norTU2Z = NaN;
  96343. this.tanTU1X = NaN;
  96344. this.tanTU1Y = NaN;
  96345. this.tanTU1Z = NaN;
  96346. this.tanTU2X = NaN;
  96347. this.tanTU2Y = NaN;
  96348. this.tanTU2Z = NaN;
  96349. this.binTU1X = NaN;
  96350. this.binTU1Y = NaN;
  96351. this.binTU1Z = NaN;
  96352. this.binTU2X = NaN;
  96353. this.binTU2Y = NaN;
  96354. this.binTU2Z = NaN;
  96355. this.norImp = NaN;
  96356. this.tanImp = NaN;
  96357. this.binImp = NaN;
  96358. this.norDen = NaN;
  96359. this.tanDen = NaN;
  96360. this.binDen = NaN;
  96361. this.norTar = NaN;
  96362. this.next = null;
  96363. this.last = false;
  96364. }
  96365. OIMO.ImpulseDataBuffer = function () {
  96366. this.lp1X = NaN;
  96367. this.lp1Y = NaN;
  96368. this.lp1Z = NaN;
  96369. this.lp2X = NaN;
  96370. this.lp2Y = NaN;
  96371. this.lp2Z = NaN;
  96372. this.impulse = NaN;
  96373. }
  96374. /**
  96375. * The class holds details of the contact point.
  96376. * @author saharan
  96377. */
  96378. OIMO.ManifoldPoint = function () {
  96379. // Whether this manifold point is persisting or not.
  96380. this.warmStarted = false;
  96381. // The position of this manifold point.
  96382. this.position = new OIMO.Vec3();
  96383. // The position in the first shape's coordinate.
  96384. this.localPoint1 = new OIMO.Vec3();
  96385. // The position in the second shape's coordinate.
  96386. this.localPoint2 = new OIMO.Vec3();
  96387. // The normal vector of this manifold point.
  96388. this.normal = new OIMO.Vec3();
  96389. // The tangent vector of this manifold point.
  96390. this.tangent = new OIMO.Vec3();
  96391. // The binormal vector of this manifold point.
  96392. this.binormal = new OIMO.Vec3();
  96393. // The impulse in normal direction.
  96394. this.normalImpulse = 0;
  96395. // The impulse in tangent direction.
  96396. this.tangentImpulse = 0;
  96397. // The impulse in binormal direction.
  96398. this.binormalImpulse = 0;
  96399. // The denominator in normal direction.
  96400. this.normalDenominator = 0;
  96401. // The denominator in tangent direction.
  96402. this.tangentDenominator = 0;
  96403. // The denominator in binormal direction.
  96404. this.binormalDenominator = 0;
  96405. // The depth of penetration.
  96406. this.penetration = 0;
  96407. }
  96408. /**
  96409. * This class holds mass information of a shape.
  96410. * @author saharan
  96411. */
  96412. OIMO.MassInfo = function () {
  96413. // Mass of the shape.
  96414. this.mass = 0;
  96415. // The moment inertia of the shape.
  96416. this.inertia = new OIMO.Mat33();
  96417. };
  96418. /**
  96419. * A shape is used to detect collisions of rigid bodies.
  96420. * @author saharan
  96421. * @author lo-th
  96422. */
  96423. OIMO.Shape = function (config) {
  96424. this.type = OIMO.SHAPE_NULL;
  96425. // The global identification of the shape should be unique to the shape.
  96426. this.id = OIMO.nextID++;
  96427. // The previous shape in parent rigid body.
  96428. this.prev = null;
  96429. // The next shape in parent rigid body.
  96430. this.next = null;
  96431. // The proxy of the shape used for broad-phase collision detection.
  96432. this.proxy = null;
  96433. // The parent rigid body of the shape.
  96434. this.parent = null;
  96435. // The linked list of the contacts with the shape.
  96436. this.contactLink = null;
  96437. // The number of the contacts with the shape.
  96438. this.numContacts = 0;
  96439. // The center of gravity of the shape in world coordinate system.
  96440. this.position = new OIMO.Vec3();
  96441. // The rotation matrix of the shape in world coordinate system
  96442. this.rotation = new OIMO.Mat33();
  96443. // The position of the shape in parent's coordinate system.
  96444. this.relativePosition = new OIMO.Vec3().copy(config.relativePosition);
  96445. // The rotation matrix of the shape in parent's coordinate system.
  96446. this.relativeRotation = new OIMO.Mat33().copy(config.relativeRotation);
  96447. // The axis-aligned bounding box of the shape.
  96448. this.aabb = new OIMO.AABB();
  96449. // The density of the shape.
  96450. this.density = config.density;
  96451. // The coefficient of friction of the shape.
  96452. this.friction = config.friction;
  96453. // The coefficient of restitution of the shape.
  96454. this.restitution = config.restitution;
  96455. // The bits of the collision groups to which the shape belongs.
  96456. this.belongsTo = config.belongsTo;
  96457. // The bits of the collision groups with which the shape collides.
  96458. this.collidesWith = config.collidesWith;
  96459. };
  96460. OIMO.Shape.prototype = {
  96461. constructor: OIMO.Shape,
  96462. // Calculate the mass information of the shape.
  96463. calculateMassInfo: function (out) {
  96464. OIMO.Error("Shape", "Inheritance error.");
  96465. },
  96466. // Update the proxy of the shape.
  96467. updateProxy: function () {
  96468. OIMO.Error("Shape", "Inheritance error.");
  96469. }
  96470. };
  96471. /**
  96472. * A shape configuration holds common configuration data for constructing a shape.
  96473. * Shape configurations can be reused safely.
  96474. * @author saharan
  96475. */
  96476. OIMO.ShapeConfig = function () {
  96477. // The position of the shape in parent's coordinate system.
  96478. this.relativePosition = new OIMO.Vec3();
  96479. // The rotation matrix of the shape in parent's coordinate system.
  96480. this.relativeRotation = new OIMO.Mat33();
  96481. // The coefficient of friction of the shape.
  96482. this.friction = 0.4;
  96483. // The coefficient of restitution of the shape.
  96484. this.restitution = 0.2;
  96485. // The density of the shape.
  96486. this.density = 1;
  96487. // The bits of the collision groups to which the shape belongs.
  96488. this.belongsTo = 1;
  96489. // The bits of the collision groups with which the shape collides.
  96490. this.collidesWith = 0xffffffff;
  96491. };
  96492. /**
  96493. * A box shape.
  96494. * @author saharan
  96495. * @author lo-th
  96496. */
  96497. OIMO.BoxShape = function (config, Width, Height, Depth) {
  96498. OIMO.Shape.call(this, config);
  96499. this.type = OIMO.SHAPE_BOX;
  96500. // The width of the box.
  96501. this.width = Width;
  96502. // The height of the box.
  96503. this.height = Height;
  96504. // The depth of the box.
  96505. this.depth = Depth;
  96506. // The half-width of the box.
  96507. this.halfWidth = Width * 0.5;
  96508. // The half-height of the box.
  96509. this.halfHeight = Height * 0.5;
  96510. // The half-depth of the box.
  96511. this.halfDepth = Depth * 0.5;
  96512. this.dimentions = new OIMO_ARRAY_TYPE(18);
  96513. this.elements = new OIMO_ARRAY_TYPE(24);
  96514. };
  96515. OIMO.BoxShape.prototype = Object.create(OIMO.Shape.prototype);
  96516. OIMO.BoxShape.prototype.constructor = OIMO.BoxShape;
  96517. OIMO.BoxShape.prototype.calculateMassInfo = function (out) {
  96518. var mass = this.width * this.height * this.depth * this.density;
  96519. var divid = 1 / 12;
  96520. out.mass = mass;
  96521. out.inertia.set(
  96522. mass * (this.height * this.height + this.depth * this.depth) * divid, 0, 0,
  96523. 0, mass * (this.width * this.width + this.depth * this.depth) * divid, 0,
  96524. 0, 0, mass * (this.width * this.width + this.height * this.height) * divid
  96525. );
  96526. };
  96527. OIMO.BoxShape.prototype.updateProxy = function () {
  96528. var te = this.rotation.elements;
  96529. var di = this.dimentions;
  96530. // Width
  96531. di[0] = te[0];
  96532. di[1] = te[3];
  96533. di[2] = te[6];
  96534. // Height
  96535. di[3] = te[1];
  96536. di[4] = te[4];
  96537. di[5] = te[7];
  96538. // Depth
  96539. di[6] = te[2];
  96540. di[7] = te[5];
  96541. di[8] = te[8];
  96542. // halp Width
  96543. di[9] = te[0] * this.halfWidth;
  96544. di[10] = te[3] * this.halfWidth;
  96545. di[11] = te[6] * this.halfWidth;
  96546. // halp Height
  96547. di[12] = te[1] * this.halfHeight;
  96548. di[13] = te[4] * this.halfHeight;
  96549. di[14] = te[7] * this.halfHeight;
  96550. // halp Depth
  96551. di[15] = te[2] * this.halfDepth;
  96552. di[16] = te[5] * this.halfDepth;
  96553. di[17] = te[8] * this.halfDepth;
  96554. var wx = di[9];
  96555. var wy = di[10];
  96556. var wz = di[11];
  96557. var hx = di[12];
  96558. var hy = di[13];
  96559. var hz = di[14];
  96560. var dx = di[15];
  96561. var dy = di[16];
  96562. var dz = di[17];
  96563. var x = this.position.x;
  96564. var y = this.position.y;
  96565. var z = this.position.z;
  96566. var v = this.elements;
  96567. //v1
  96568. v[0] = x + wx + hx + dx;
  96569. v[1] = y + wy + hy + dy;
  96570. v[2] = z + wz + hz + dz;
  96571. //v2
  96572. v[3] = x + wx + hx - dx;
  96573. v[4] = y + wy + hy - dy;
  96574. v[5] = z + wz + hz - dz;
  96575. //v3
  96576. v[6] = x + wx - hx + dx;
  96577. v[7] = y + wy - hy + dy;
  96578. v[8] = z + wz - hz + dz;
  96579. //v4
  96580. v[9] = x + wx - hx - dx;
  96581. v[10] = y + wy - hy - dy;
  96582. v[11] = z + wz - hz - dz;
  96583. //v5
  96584. v[12] = x - wx + hx + dx;
  96585. v[13] = y - wy + hy + dy;
  96586. v[14] = z - wz + hz + dz;
  96587. //v6
  96588. v[15] = x - wx + hx - dx;
  96589. v[16] = y - wy + hy - dy;
  96590. v[17] = z - wz + hz - dz;
  96591. //v7
  96592. v[18] = x - wx - hx + dx;
  96593. v[19] = y - wy - hy + dy;
  96594. v[20] = z - wz - hz + dz;
  96595. //v8
  96596. v[21] = x - wx - hx - dx;
  96597. v[22] = y - wy - hy - dy;
  96598. v[23] = z - wz - hz - dz;
  96599. var w = di[9] < 0 ? -di[9] : di[9];
  96600. var h = di[10] < 0 ? -di[10] : di[10];
  96601. var d = di[11] < 0 ? -di[11] : di[11];
  96602. w = di[12] < 0 ? w - di[12] : w + di[12];
  96603. h = di[13] < 0 ? h - di[13] : h + di[13];
  96604. d = di[14] < 0 ? d - di[14] : d + di[14];
  96605. w = di[15] < 0 ? w - di[15] : w + di[15];
  96606. h = di[16] < 0 ? h - di[16] : h + di[16];
  96607. d = di[17] < 0 ? d - di[17] : d + di[17];
  96608. var p = OIMO.AABB_PROX;
  96609. this.aabb.set(
  96610. this.position.x - w - p, this.position.x + w + p,
  96611. this.position.y - h - p, this.position.y + h + p,
  96612. this.position.z - d - p, this.position.z + d + p
  96613. );
  96614. if (this.proxy != null) this.proxy.update();
  96615. };
  96616. /**
  96617. * A sphere shape.
  96618. * @author saharan
  96619. * @author lo-th
  96620. */
  96621. OIMO.SphereShape = function (config, radius) {
  96622. OIMO.Shape.call(this, config);
  96623. this.type = OIMO.SHAPE_SPHERE;
  96624. // The radius of the shape.
  96625. this.radius = radius;
  96626. };
  96627. OIMO.SphereShape.prototype = Object.create(OIMO.Shape.prototype);
  96628. OIMO.SphereShape.prototype.constructor = OIMO.SphereShape;
  96629. OIMO.SphereShape.prototype.calculateMassInfo = function (out) {
  96630. var mass = 1.333 * OIMO.PI * this.radius * this.radius * this.radius * this.density;
  96631. out.mass = mass;
  96632. var inertia = mass * this.radius * this.radius * 0.4;
  96633. out.inertia.set(inertia, 0, 0, 0, inertia, 0, 0, 0, inertia);
  96634. };
  96635. OIMO.SphereShape.prototype.updateProxy = function () {
  96636. var p = OIMO.AABB_PROX;
  96637. this.aabb.set(
  96638. this.position.x - this.radius - p, this.position.x + this.radius + p,
  96639. this.position.y - this.radius - p, this.position.y + this.radius + p,
  96640. this.position.z - this.radius - p, this.position.z + this.radius + p
  96641. );
  96642. if (this.proxy != null) this.proxy.update();
  96643. };
  96644. /**
  96645. * A cylinder shap.
  96646. * @author saharan
  96647. * @author lo-th
  96648. */
  96649. OIMO.CylinderShape = function (config, radius, height) {
  96650. OIMO.Shape.call(this, config);
  96651. this.type = OIMO.SHAPE_CYLINDER;
  96652. this.radius = radius;
  96653. this.height = height;
  96654. this.halfHeight = height * 0.5;
  96655. this.normalDirection = new OIMO.Vec3();
  96656. this.halfDirection = new OIMO.Vec3();
  96657. };
  96658. OIMO.CylinderShape.prototype = Object.create(OIMO.Shape.prototype);
  96659. OIMO.CylinderShape.prototype.constructor = OIMO.CylinderShape;
  96660. OIMO.CylinderShape.prototype.calculateMassInfo = function (out) {
  96661. var rsq = this.radius * this.radius;
  96662. var mass = OIMO.PI * rsq * this.height * this.density;
  96663. var inertiaXZ = ((0.25 * rsq) + (0.0833 * this.height * this.height)) * mass;
  96664. var inertiaY = 0.5 * rsq;
  96665. out.mass = mass;
  96666. out.inertia.set(inertiaXZ, 0, 0, 0, inertiaY, 0, 0, 0, inertiaXZ);
  96667. };
  96668. OIMO.CylinderShape.prototype.updateProxy = function () {
  96669. var te = this.rotation.elements;
  96670. var len, wx, hy, dz, xx, yy, zz, w, h, d, p;
  96671. xx = te[1] * te[1];
  96672. yy = te[4] * te[4];
  96673. zz = te[7] * te[7];
  96674. this.normalDirection.set(te[1], te[4], te[7]);
  96675. this.halfDirection.scale(this.normalDirection, this.halfHeight);
  96676. wx = 1 - xx;
  96677. len = OIMO.sqrt(wx * wx + xx * yy + xx * zz);
  96678. if (len > 0) len = this.radius / len;
  96679. wx *= len;
  96680. hy = 1 - yy;
  96681. len = OIMO.sqrt(yy * xx + hy * hy + yy * zz);
  96682. if (len > 0) len = this.radius / len;
  96683. hy *= len;
  96684. dz = 1 - zz;
  96685. len = OIMO.sqrt(zz * xx + zz * yy + dz * dz);
  96686. if (len > 0) len = this.radius / len;
  96687. dz *= len;
  96688. w = this.halfDirection.x < 0 ? -this.halfDirection.x : this.halfDirection.x;
  96689. h = this.halfDirection.y < 0 ? -this.halfDirection.y : this.halfDirection.y;
  96690. d = this.halfDirection.z < 0 ? -this.halfDirection.z : this.halfDirection.z;
  96691. w = wx < 0 ? w - wx : w + wx;
  96692. h = hy < 0 ? h - hy : h + hy;
  96693. d = dz < 0 ? d - dz : d + dz;
  96694. p = OIMO.AABB_PROX;
  96695. this.aabb.set(
  96696. this.position.x - w - p, this.position.x + w + p,
  96697. this.position.y - h - p, this.position.y + h + p,
  96698. this.position.z - d - p, this.position.z + d + p
  96699. );
  96700. if (this.proxy != null) this.proxy.update();
  96701. };
  96702. /**
  96703. * A tetra shape.
  96704. * @author xprogram
  96705. */
  96706. OIMO.TetraShape = function (config, p1, p2, p3, p4) {
  96707. OIMO.Shape.call(this, config);
  96708. this.type = OIMO.SHAPE_TETRA;
  96709. // Vertices and faces of tetra
  96710. this.verts = [p1, p2, p3, p4];
  96711. this.faces = [
  96712. mtri(0, 1, 2),
  96713. mtri(1, 2, 3),
  96714. mtri(2, 3, 4),
  96715. mtri(4, 0, 1),
  96716. ];
  96717. };
  96718. OIMO.TetraShape.prototype = Object.create(OIMO.Shape.prototype);
  96719. OIMO.TetraShape.prototype.constructor = OIMO.TetraShape;
  96720. OIMO.TetraShape.prototype.calculateMassInfo = function () {
  96721. // I guess you could calculate box mass and split it
  96722. // in half for the tetra...
  96723. };
  96724. OIMO.TetraShape.prototype.updateProxy = function () {
  96725. this.aabb.setFromPoints(this.verts);
  96726. if (this.proxy !== null)
  96727. this.proxy.update();
  96728. };
  96729. function mtri(a, b, c) {
  96730. return { a: a, b: b, c: c };
  96731. }
  96732. OIMO.CollisionDetector = function () {
  96733. this.flip = false;
  96734. };
  96735. OIMO.CollisionDetector.prototype = {
  96736. constructor: OIMO.CollisionDetector,
  96737. detectCollision: function (shape1, shape2, manifold) {
  96738. OIMO.Error("CollisionDetector", "Inheritance error.");
  96739. }
  96740. };
  96741. /**
  96742. * A collision detector which detects collisions between two boxes.
  96743. * @author saharan
  96744. */
  96745. OIMO.BoxBoxCollisionDetector = function () {
  96746. OIMO.CollisionDetector.call(this);
  96747. this.clipVertices1 = new OIMO_ARRAY_TYPE(24); // 8 vertices x,y,z
  96748. this.clipVertices2 = new OIMO_ARRAY_TYPE(24);
  96749. this.used = new OIMO_ARRAY_TYPE(8);
  96750. this.INF = 1 / 0;
  96751. };
  96752. OIMO.BoxBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  96753. OIMO.BoxBoxCollisionDetector.prototype.constructor = OIMO.BoxBoxCollisionDetector;
  96754. OIMO.BoxBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  96755. // What you are doing
  96756. // · I to prepare a separate axis of the fifteen
  96757. //-Six in each of three normal vectors of the xyz direction of the box both
  96758. // · Remaining nine 3x3 a vector perpendicular to the side of the box 2 and the side of the box 1
  96759. // · Calculate the depth to the separation axis
  96760. // Calculates the distance using the inner product and put the amount of embedment
  96761. // · However a vertical separation axis and side to weight a little to avoid vibration
  96762. // And end when there is a separate axis that is remote even one
  96763. // · I look for separation axis with little to dent most
  96764. // Men and if separation axis of the first six - end collision
  96765. // Heng If it separate axis of nine other - side collision
  96766. // Heng - case of a side collision
  96767. // · Find points of two sides on which you made ​​the separation axis
  96768. // Calculates the point of closest approach of a straight line consisting of separate axis points obtained, and the collision point
  96769. //-Surface - the case of the plane crash
  96770. //-Box A, box B and the other a box of better made ​​a separate axis
  96771. // • 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
  96772. // When viewed from the front surface A, and the cut part exceeding the area of the surface A is a surface B
  96773. //-Plane B becomes the 3-8 triangle, I a candidate for the collision point the vertex of surface B
  96774. // • If more than one candidate 5 exists, scraping up to four
  96775. // For potential collision points of all, to examine the distance between the surface A
  96776. // • If you were on the inside surface of A, and the collision point
  96777. var b1;
  96778. var b2;
  96779. if (shape1.id < shape2.id) {
  96780. b1 = (shape1);
  96781. b2 = (shape2);
  96782. } else {
  96783. b1 = (shape2);
  96784. b2 = (shape1);
  96785. }
  96786. var V1 = b1.elements;
  96787. var V2 = b2.elements;
  96788. var D1 = b1.dimentions;
  96789. var D2 = b2.dimentions;
  96790. var p1 = b1.position;
  96791. var p2 = b2.position;
  96792. var p1x = p1.x;
  96793. var p1y = p1.y;
  96794. var p1z = p1.z;
  96795. var p2x = p2.x;
  96796. var p2y = p2.y;
  96797. var p2z = p2.z;
  96798. // diff
  96799. var dx = p2x - p1x;
  96800. var dy = p2y - p1y;
  96801. var dz = p2z - p1z;
  96802. // distance
  96803. var w1 = b1.halfWidth;
  96804. var h1 = b1.halfHeight;
  96805. var d1 = b1.halfDepth;
  96806. var w2 = b2.halfWidth;
  96807. var h2 = b2.halfHeight;
  96808. var d2 = b2.halfDepth;
  96809. // direction
  96810. // ----------------------------
  96811. // 15 separating axes
  96812. // 1~6: face
  96813. // 7~f: edge
  96814. // http://marupeke296.com/COL_3D_No13_OBBvsOBB.html
  96815. // ----------------------------
  96816. var a1x = D1[0];
  96817. var a1y = D1[1];
  96818. var a1z = D1[2];
  96819. var a2x = D1[3];
  96820. var a2y = D1[4];
  96821. var a2z = D1[5];
  96822. var a3x = D1[6];
  96823. var a3y = D1[7];
  96824. var a3z = D1[8];
  96825. var d1x = D1[9];
  96826. var d1y = D1[10];
  96827. var d1z = D1[11];
  96828. var d2x = D1[12];
  96829. var d2y = D1[13];
  96830. var d2z = D1[14];
  96831. var d3x = D1[15];
  96832. var d3y = D1[16];
  96833. var d3z = D1[17];
  96834. var a4x = D2[0];
  96835. var a4y = D2[1];
  96836. var a4z = D2[2];
  96837. var a5x = D2[3];
  96838. var a5y = D2[4];
  96839. var a5z = D2[5];
  96840. var a6x = D2[6];
  96841. var a6y = D2[7];
  96842. var a6z = D2[8];
  96843. var d4x = D2[9];
  96844. var d4y = D2[10];
  96845. var d4z = D2[11];
  96846. var d5x = D2[12];
  96847. var d5y = D2[13];
  96848. var d5z = D2[14];
  96849. var d6x = D2[15];
  96850. var d6y = D2[16];
  96851. var d6z = D2[17];
  96852. var a7x = a1y * a4z - a1z * a4y;
  96853. var a7y = a1z * a4x - a1x * a4z;
  96854. var a7z = a1x * a4y - a1y * a4x;
  96855. var a8x = a1y * a5z - a1z * a5y;
  96856. var a8y = a1z * a5x - a1x * a5z;
  96857. var a8z = a1x * a5y - a1y * a5x;
  96858. var a9x = a1y * a6z - a1z * a6y;
  96859. var a9y = a1z * a6x - a1x * a6z;
  96860. var a9z = a1x * a6y - a1y * a6x;
  96861. var aax = a2y * a4z - a2z * a4y;
  96862. var aay = a2z * a4x - a2x * a4z;
  96863. var aaz = a2x * a4y - a2y * a4x;
  96864. var abx = a2y * a5z - a2z * a5y;
  96865. var aby = a2z * a5x - a2x * a5z;
  96866. var abz = a2x * a5y - a2y * a5x;
  96867. var acx = a2y * a6z - a2z * a6y;
  96868. var acy = a2z * a6x - a2x * a6z;
  96869. var acz = a2x * a6y - a2y * a6x;
  96870. var adx = a3y * a4z - a3z * a4y;
  96871. var ady = a3z * a4x - a3x * a4z;
  96872. var adz = a3x * a4y - a3y * a4x;
  96873. var aex = a3y * a5z - a3z * a5y;
  96874. var aey = a3z * a5x - a3x * a5z;
  96875. var aez = a3x * a5y - a3y * a5x;
  96876. var afx = a3y * a6z - a3z * a6y;
  96877. var afy = a3z * a6x - a3x * a6z;
  96878. var afz = a3x * a6y - a3y * a6x;
  96879. // right or left flags
  96880. var right1;
  96881. var right2;
  96882. var right3;
  96883. var right4;
  96884. var right5;
  96885. var right6;
  96886. var right7;
  96887. var right8;
  96888. var right9;
  96889. var righta;
  96890. var rightb;
  96891. var rightc;
  96892. var rightd;
  96893. var righte;
  96894. var rightf;
  96895. // overlapping distances
  96896. var overlap1;
  96897. var overlap2;
  96898. var overlap3;
  96899. var overlap4;
  96900. var overlap5;
  96901. var overlap6;
  96902. var overlap7;
  96903. var overlap8;
  96904. var overlap9;
  96905. var overlapa;
  96906. var overlapb;
  96907. var overlapc;
  96908. var overlapd;
  96909. var overlape;
  96910. var overlapf;
  96911. // invalid flags
  96912. var invalid7 = false;
  96913. var invalid8 = false;
  96914. var invalid9 = false;
  96915. var invalida = false;
  96916. var invalidb = false;
  96917. var invalidc = false;
  96918. var invalidd = false;
  96919. var invalide = false;
  96920. var invalidf = false;
  96921. // temporary variables
  96922. var len;
  96923. var len1;
  96924. var len2;
  96925. var dot1;
  96926. var dot2;
  96927. var dot3;
  96928. // try axis 1
  96929. len = a1x * dx + a1y * dy + a1z * dz;
  96930. right1 = len > 0;
  96931. if (!right1) len = -len;
  96932. len1 = w1;
  96933. dot1 = a1x * a4x + a1y * a4y + a1z * a4z;
  96934. dot2 = a1x * a5x + a1y * a5y + a1z * a5z;
  96935. dot3 = a1x * a6x + a1y * a6y + a1z * a6z;
  96936. if (dot1 < 0) dot1 = -dot1;
  96937. if (dot2 < 0) dot2 = -dot2;
  96938. if (dot3 < 0) dot3 = -dot3;
  96939. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96940. overlap1 = len - len1 - len2;
  96941. if (overlap1 > 0) return;
  96942. // try axis 2
  96943. len = a2x * dx + a2y * dy + a2z * dz;
  96944. right2 = len > 0;
  96945. if (!right2) len = -len;
  96946. len1 = h1;
  96947. dot1 = a2x * a4x + a2y * a4y + a2z * a4z;
  96948. dot2 = a2x * a5x + a2y * a5y + a2z * a5z;
  96949. dot3 = a2x * a6x + a2y * a6y + a2z * a6z;
  96950. if (dot1 < 0) dot1 = -dot1;
  96951. if (dot2 < 0) dot2 = -dot2;
  96952. if (dot3 < 0) dot3 = -dot3;
  96953. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96954. overlap2 = len - len1 - len2;
  96955. if (overlap2 > 0) return;
  96956. // try axis 3
  96957. len = a3x * dx + a3y * dy + a3z * dz;
  96958. right3 = len > 0;
  96959. if (!right3) len = -len;
  96960. len1 = d1;
  96961. dot1 = a3x * a4x + a3y * a4y + a3z * a4z;
  96962. dot2 = a3x * a5x + a3y * a5y + a3z * a5z;
  96963. dot3 = a3x * a6x + a3y * a6y + a3z * a6z;
  96964. if (dot1 < 0) dot1 = -dot1;
  96965. if (dot2 < 0) dot2 = -dot2;
  96966. if (dot3 < 0) dot3 = -dot3;
  96967. len2 = dot1 * w2 + dot2 * h2 + dot3 * d2;
  96968. overlap3 = len - len1 - len2;
  96969. if (overlap3 > 0) return;
  96970. // try axis 4
  96971. len = a4x * dx + a4y * dy + a4z * dz;
  96972. right4 = len > 0;
  96973. if (!right4) len = -len;
  96974. dot1 = a4x * a1x + a4y * a1y + a4z * a1z;
  96975. dot2 = a4x * a2x + a4y * a2y + a4z * a2z;
  96976. dot3 = a4x * a3x + a4y * a3y + a4z * a3z;
  96977. if (dot1 < 0) dot1 = -dot1;
  96978. if (dot2 < 0) dot2 = -dot2;
  96979. if (dot3 < 0) dot3 = -dot3;
  96980. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96981. len2 = w2;
  96982. overlap4 = (len - len1 - len2) * 1.0;
  96983. if (overlap4 > 0) return;
  96984. // try axis 5
  96985. len = a5x * dx + a5y * dy + a5z * dz;
  96986. right5 = len > 0;
  96987. if (!right5) len = -len;
  96988. dot1 = a5x * a1x + a5y * a1y + a5z * a1z;
  96989. dot2 = a5x * a2x + a5y * a2y + a5z * a2z;
  96990. dot3 = a5x * a3x + a5y * a3y + a5z * a3z;
  96991. if (dot1 < 0) dot1 = -dot1;
  96992. if (dot2 < 0) dot2 = -dot2;
  96993. if (dot3 < 0) dot3 = -dot3;
  96994. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  96995. len2 = h2;
  96996. overlap5 = (len - len1 - len2) * 1.0;
  96997. if (overlap5 > 0) return;
  96998. // try axis 6
  96999. len = a6x * dx + a6y * dy + a6z * dz;
  97000. right6 = len > 0;
  97001. if (!right6) len = -len;
  97002. dot1 = a6x * a1x + a6y * a1y + a6z * a1z;
  97003. dot2 = a6x * a2x + a6y * a2y + a6z * a2z;
  97004. dot3 = a6x * a3x + a6y * a3y + a6z * a3z;
  97005. if (dot1 < 0) dot1 = -dot1;
  97006. if (dot2 < 0) dot2 = -dot2;
  97007. if (dot3 < 0) dot3 = -dot3;
  97008. len1 = dot1 * w1 + dot2 * h1 + dot3 * d1;
  97009. len2 = d2;
  97010. overlap6 = (len - len1 - len2) * 1.0;
  97011. if (overlap6 > 0) return;
  97012. // try axis 7
  97013. len = a7x * a7x + a7y * a7y + a7z * a7z;
  97014. if (len > 1e-5) {
  97015. len = 1 / OIMO.sqrt(len);
  97016. a7x *= len;
  97017. a7y *= len;
  97018. a7z *= len;
  97019. len = a7x * dx + a7y * dy + a7z * dz;
  97020. right7 = len > 0;
  97021. if (!right7) len = -len;
  97022. dot1 = a7x * a2x + a7y * a2y + a7z * a2z;
  97023. dot2 = a7x * a3x + a7y * a3y + a7z * a3z;
  97024. if (dot1 < 0) dot1 = -dot1;
  97025. if (dot2 < 0) dot2 = -dot2;
  97026. len1 = dot1 * h1 + dot2 * d1;
  97027. dot1 = a7x * a5x + a7y * a5y + a7z * a5z;
  97028. dot2 = a7x * a6x + a7y * a6y + a7z * a6z;
  97029. if (dot1 < 0) dot1 = -dot1;
  97030. if (dot2 < 0) dot2 = -dot2;
  97031. len2 = dot1 * h2 + dot2 * d2;
  97032. overlap7 = len - len1 - len2;
  97033. if (overlap7 > 0) return;
  97034. } else {
  97035. right7 = false;
  97036. overlap7 = 0;
  97037. invalid7 = true;
  97038. }
  97039. // try axis 8
  97040. len = a8x * a8x + a8y * a8y + a8z * a8z;
  97041. if (len > 1e-5) {
  97042. len = 1 / OIMO.sqrt(len);
  97043. a8x *= len;
  97044. a8y *= len;
  97045. a8z *= len;
  97046. len = a8x * dx + a8y * dy + a8z * dz;
  97047. right8 = len > 0;
  97048. if (!right8) len = -len;
  97049. dot1 = a8x * a2x + a8y * a2y + a8z * a2z;
  97050. dot2 = a8x * a3x + a8y * a3y + a8z * a3z;
  97051. if (dot1 < 0) dot1 = -dot1;
  97052. if (dot2 < 0) dot2 = -dot2;
  97053. len1 = dot1 * h1 + dot2 * d1;
  97054. dot1 = a8x * a4x + a8y * a4y + a8z * a4z;
  97055. dot2 = a8x * a6x + a8y * a6y + a8z * a6z;
  97056. if (dot1 < 0) dot1 = -dot1;
  97057. if (dot2 < 0) dot2 = -dot2;
  97058. len2 = dot1 * w2 + dot2 * d2;
  97059. overlap8 = len - len1 - len2;
  97060. if (overlap8 > 0) return;
  97061. } else {
  97062. right8 = false;
  97063. overlap8 = 0;
  97064. invalid8 = true;
  97065. }
  97066. // try axis 9
  97067. len = a9x * a9x + a9y * a9y + a9z * a9z;
  97068. if (len > 1e-5) {
  97069. len = 1 / OIMO.sqrt(len);
  97070. a9x *= len;
  97071. a9y *= len;
  97072. a9z *= len;
  97073. len = a9x * dx + a9y * dy + a9z * dz;
  97074. right9 = len > 0;
  97075. if (!right9) len = -len;
  97076. dot1 = a9x * a2x + a9y * a2y + a9z * a2z;
  97077. dot2 = a9x * a3x + a9y * a3y + a9z * a3z;
  97078. if (dot1 < 0) dot1 = -dot1;
  97079. if (dot2 < 0) dot2 = -dot2;
  97080. len1 = dot1 * h1 + dot2 * d1;
  97081. dot1 = a9x * a4x + a9y * a4y + a9z * a4z;
  97082. dot2 = a9x * a5x + a9y * a5y + a9z * a5z;
  97083. if (dot1 < 0) dot1 = -dot1;
  97084. if (dot2 < 0) dot2 = -dot2;
  97085. len2 = dot1 * w2 + dot2 * h2;
  97086. overlap9 = len - len1 - len2;
  97087. if (overlap9 > 0) return;
  97088. } else {
  97089. right9 = false;
  97090. overlap9 = 0;
  97091. invalid9 = true;
  97092. }
  97093. // try axis 10
  97094. len = aax * aax + aay * aay + aaz * aaz;
  97095. if (len > 1e-5) {
  97096. len = 1 / OIMO.sqrt(len);
  97097. aax *= len;
  97098. aay *= len;
  97099. aaz *= len;
  97100. len = aax * dx + aay * dy + aaz * dz;
  97101. righta = len > 0;
  97102. if (!righta) len = -len;
  97103. dot1 = aax * a1x + aay * a1y + aaz * a1z;
  97104. dot2 = aax * a3x + aay * a3y + aaz * a3z;
  97105. if (dot1 < 0) dot1 = -dot1;
  97106. if (dot2 < 0) dot2 = -dot2;
  97107. len1 = dot1 * w1 + dot2 * d1;
  97108. dot1 = aax * a5x + aay * a5y + aaz * a5z;
  97109. dot2 = aax * a6x + aay * a6y + aaz * a6z;
  97110. if (dot1 < 0) dot1 = -dot1;
  97111. if (dot2 < 0) dot2 = -dot2;
  97112. len2 = dot1 * h2 + dot2 * d2;
  97113. overlapa = len - len1 - len2;
  97114. if (overlapa > 0) return;
  97115. } else {
  97116. righta = false;
  97117. overlapa = 0;
  97118. invalida = true;
  97119. }
  97120. // try axis 11
  97121. len = abx * abx + aby * aby + abz * abz;
  97122. if (len > 1e-5) {
  97123. len = 1 / OIMO.sqrt(len);
  97124. abx *= len;
  97125. aby *= len;
  97126. abz *= len;
  97127. len = abx * dx + aby * dy + abz * dz;
  97128. rightb = len > 0;
  97129. if (!rightb) len = -len;
  97130. dot1 = abx * a1x + aby * a1y + abz * a1z;
  97131. dot2 = abx * a3x + aby * a3y + abz * a3z;
  97132. if (dot1 < 0) dot1 = -dot1;
  97133. if (dot2 < 0) dot2 = -dot2;
  97134. len1 = dot1 * w1 + dot2 * d1;
  97135. dot1 = abx * a4x + aby * a4y + abz * a4z;
  97136. dot2 = abx * a6x + aby * a6y + abz * a6z;
  97137. if (dot1 < 0) dot1 = -dot1;
  97138. if (dot2 < 0) dot2 = -dot2;
  97139. len2 = dot1 * w2 + dot2 * d2;
  97140. overlapb = len - len1 - len2;
  97141. if (overlapb > 0) return;
  97142. } else {
  97143. rightb = false;
  97144. overlapb = 0;
  97145. invalidb = true;
  97146. }
  97147. // try axis 12
  97148. len = acx * acx + acy * acy + acz * acz;
  97149. if (len > 1e-5) {
  97150. len = 1 / OIMO.sqrt(len);
  97151. acx *= len;
  97152. acy *= len;
  97153. acz *= len;
  97154. len = acx * dx + acy * dy + acz * dz;
  97155. rightc = len > 0;
  97156. if (!rightc) len = -len;
  97157. dot1 = acx * a1x + acy * a1y + acz * a1z;
  97158. dot2 = acx * a3x + acy * a3y + acz * a3z;
  97159. if (dot1 < 0) dot1 = -dot1;
  97160. if (dot2 < 0) dot2 = -dot2;
  97161. len1 = dot1 * w1 + dot2 * d1;
  97162. dot1 = acx * a4x + acy * a4y + acz * a4z;
  97163. dot2 = acx * a5x + acy * a5y + acz * a5z;
  97164. if (dot1 < 0) dot1 = -dot1;
  97165. if (dot2 < 0) dot2 = -dot2;
  97166. len2 = dot1 * w2 + dot2 * h2;
  97167. overlapc = len - len1 - len2;
  97168. if (overlapc > 0) return;
  97169. } else {
  97170. rightc = false;
  97171. overlapc = 0;
  97172. invalidc = true;
  97173. }
  97174. // try axis 13
  97175. len = adx * adx + ady * ady + adz * adz;
  97176. if (len > 1e-5) {
  97177. len = 1 / OIMO.sqrt(len);
  97178. adx *= len;
  97179. ady *= len;
  97180. adz *= len;
  97181. len = adx * dx + ady * dy + adz * dz;
  97182. rightd = len > 0;
  97183. if (!rightd) len = -len;
  97184. dot1 = adx * a1x + ady * a1y + adz * a1z;
  97185. dot2 = adx * a2x + ady * a2y + adz * a2z;
  97186. if (dot1 < 0) dot1 = -dot1;
  97187. if (dot2 < 0) dot2 = -dot2;
  97188. len1 = dot1 * w1 + dot2 * h1;
  97189. dot1 = adx * a5x + ady * a5y + adz * a5z;
  97190. dot2 = adx * a6x + ady * a6y + adz * a6z;
  97191. if (dot1 < 0) dot1 = -dot1;
  97192. if (dot2 < 0) dot2 = -dot2;
  97193. len2 = dot1 * h2 + dot2 * d2;
  97194. overlapd = len - len1 - len2;
  97195. if (overlapd > 0) return;
  97196. } else {
  97197. rightd = false;
  97198. overlapd = 0;
  97199. invalidd = true;
  97200. }
  97201. // try axis 14
  97202. len = aex * aex + aey * aey + aez * aez;
  97203. if (len > 1e-5) {
  97204. len = 1 / OIMO.sqrt(len);
  97205. aex *= len;
  97206. aey *= len;
  97207. aez *= len;
  97208. len = aex * dx + aey * dy + aez * dz;
  97209. righte = len > 0;
  97210. if (!righte) len = -len;
  97211. dot1 = aex * a1x + aey * a1y + aez * a1z;
  97212. dot2 = aex * a2x + aey * a2y + aez * a2z;
  97213. if (dot1 < 0) dot1 = -dot1;
  97214. if (dot2 < 0) dot2 = -dot2;
  97215. len1 = dot1 * w1 + dot2 * h1;
  97216. dot1 = aex * a4x + aey * a4y + aez * a4z;
  97217. dot2 = aex * a6x + aey * a6y + aez * a6z;
  97218. if (dot1 < 0) dot1 = -dot1;
  97219. if (dot2 < 0) dot2 = -dot2;
  97220. len2 = dot1 * w2 + dot2 * d2;
  97221. overlape = len - len1 - len2;
  97222. if (overlape > 0) return;
  97223. } else {
  97224. righte = false;
  97225. overlape = 0;
  97226. invalide = true;
  97227. }
  97228. // try axis 15
  97229. len = afx * afx + afy * afy + afz * afz;
  97230. if (len > 1e-5) {
  97231. len = 1 / OIMO.sqrt(len);
  97232. afx *= len;
  97233. afy *= len;
  97234. afz *= len;
  97235. len = afx * dx + afy * dy + afz * dz;
  97236. rightf = len > 0;
  97237. if (!rightf) len = -len;
  97238. dot1 = afx * a1x + afy * a1y + afz * a1z;
  97239. dot2 = afx * a2x + afy * a2y + afz * a2z;
  97240. if (dot1 < 0) dot1 = -dot1;
  97241. if (dot2 < 0) dot2 = -dot2;
  97242. len1 = dot1 * w1 + dot2 * h1;
  97243. dot1 = afx * a4x + afy * a4y + afz * a4z;
  97244. dot2 = afx * a5x + afy * a5y + afz * a5z;
  97245. if (dot1 < 0) dot1 = -dot1;
  97246. if (dot2 < 0) dot2 = -dot2;
  97247. len2 = dot1 * w2 + dot2 * h2;
  97248. overlapf = len - len1 - len2;
  97249. if (overlapf > 0) return;
  97250. } else {
  97251. rightf = false;
  97252. overlapf = 0;
  97253. invalidf = true;
  97254. }
  97255. // boxes are overlapping
  97256. var depth = overlap1;
  97257. var depth2 = overlap1;
  97258. var minIndex = 0;
  97259. var right = right1;
  97260. if (overlap2 > depth2) {
  97261. depth = overlap2;
  97262. depth2 = overlap2;
  97263. minIndex = 1;
  97264. right = right2;
  97265. }
  97266. if (overlap3 > depth2) {
  97267. depth = overlap3;
  97268. depth2 = overlap3;
  97269. minIndex = 2;
  97270. right = right3;
  97271. }
  97272. if (overlap4 > depth2) {
  97273. depth = overlap4;
  97274. depth2 = overlap4;
  97275. minIndex = 3;
  97276. right = right4;
  97277. }
  97278. if (overlap5 > depth2) {
  97279. depth = overlap5;
  97280. depth2 = overlap5;
  97281. minIndex = 4;
  97282. right = right5;
  97283. }
  97284. if (overlap6 > depth2) {
  97285. depth = overlap6;
  97286. depth2 = overlap6;
  97287. minIndex = 5;
  97288. right = right6;
  97289. }
  97290. if (overlap7 - 0.01 > depth2 && !invalid7) {
  97291. depth = overlap7;
  97292. depth2 = overlap7 - 0.01;
  97293. minIndex = 6;
  97294. right = right7;
  97295. }
  97296. if (overlap8 - 0.01 > depth2 && !invalid8) {
  97297. depth = overlap8;
  97298. depth2 = overlap8 - 0.01;
  97299. minIndex = 7;
  97300. right = right8;
  97301. }
  97302. if (overlap9 - 0.01 > depth2 && !invalid9) {
  97303. depth = overlap9;
  97304. depth2 = overlap9 - 0.01;
  97305. minIndex = 8;
  97306. right = right9;
  97307. }
  97308. if (overlapa - 0.01 > depth2 && !invalida) {
  97309. depth = overlapa;
  97310. depth2 = overlapa - 0.01;
  97311. minIndex = 9;
  97312. right = righta;
  97313. }
  97314. if (overlapb - 0.01 > depth2 && !invalidb) {
  97315. depth = overlapb;
  97316. depth2 = overlapb - 0.01;
  97317. minIndex = 10;
  97318. right = rightb;
  97319. }
  97320. if (overlapc - 0.01 > depth2 && !invalidc) {
  97321. depth = overlapc;
  97322. depth2 = overlapc - 0.01;
  97323. minIndex = 11;
  97324. right = rightc;
  97325. }
  97326. if (overlapd - 0.01 > depth2 && !invalidd) {
  97327. depth = overlapd;
  97328. depth2 = overlapd - 0.01;
  97329. minIndex = 12;
  97330. right = rightd;
  97331. }
  97332. if (overlape - 0.01 > depth2 && !invalide) {
  97333. depth = overlape;
  97334. depth2 = overlape - 0.01;
  97335. minIndex = 13;
  97336. right = righte;
  97337. }
  97338. if (overlapf - 0.01 > depth2 && !invalidf) {
  97339. depth = overlapf;
  97340. minIndex = 14;
  97341. right = rightf;
  97342. }
  97343. // normal
  97344. var nx = 0;
  97345. var ny = 0;
  97346. var nz = 0;
  97347. // edge line or face side normal
  97348. var n1x = 0;
  97349. var n1y = 0;
  97350. var n1z = 0;
  97351. var n2x = 0;
  97352. var n2y = 0;
  97353. var n2z = 0;
  97354. // center of current face
  97355. var cx = 0;
  97356. var cy = 0;
  97357. var cz = 0;
  97358. // face side
  97359. var s1x = 0;
  97360. var s1y = 0;
  97361. var s1z = 0;
  97362. var s2x = 0;
  97363. var s2y = 0;
  97364. var s2z = 0;
  97365. // swap b1 b2
  97366. var swap = false;
  97367. //_______________________________________
  97368. if (minIndex == 0) {// b1.x * b2
  97369. if (right) {
  97370. cx = p1x + d1x; cy = p1y + d1y; cz = p1z + d1z;
  97371. nx = a1x; ny = a1y; nz = a1z;
  97372. } else {
  97373. cx = p1x - d1x; cy = p1y - d1y; cz = p1z - d1z;
  97374. nx = -a1x; ny = -a1y; nz = -a1z;
  97375. }
  97376. s1x = d2x; s1y = d2y; s1z = d2z;
  97377. n1x = -a2x; n1y = -a2y; n1z = -a2z;
  97378. s2x = d3x; s2y = d3y; s2z = d3z;
  97379. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  97380. }
  97381. else if (minIndex == 1) {// b1.y * b2
  97382. if (right) {
  97383. cx = p1x + d2x; cy = p1y + d2y; cz = p1z + d2z;
  97384. nx = a2x; ny = a2y; nz = a2z;
  97385. } else {
  97386. cx = p1x - d2x; cy = p1y - d2y; cz = p1z - d2z;
  97387. nx = -a2x; ny = -a2y; nz = -a2z;
  97388. }
  97389. s1x = d1x; s1y = d1y; s1z = d1z;
  97390. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  97391. s2x = d3x; s2y = d3y; s2z = d3z;
  97392. n2x = -a3x; n2y = -a3y; n2z = -a3z;
  97393. }
  97394. else if (minIndex == 2) {// b1.z * b2
  97395. if (right) {
  97396. cx = p1x + d3x; cy = p1y + d3y; cz = p1z + d3z;
  97397. nx = a3x; ny = a3y; nz = a3z;
  97398. } else {
  97399. cx = p1x - d3x; cy = p1y - d3y; cz = p1z - d3z;
  97400. nx = -a3x; ny = -a3y; nz = -a3z;
  97401. }
  97402. s1x = d1x; s1y = d1y; s1z = d1z;
  97403. n1x = -a1x; n1y = -a1y; n1z = -a1z;
  97404. s2x = d2x; s2y = d2y; s2z = d2z;
  97405. n2x = -a2x; n2y = -a2y; n2z = -a2z;
  97406. }
  97407. else if (minIndex == 3) {// b2.x * b1
  97408. swap = true;
  97409. if (!right) {
  97410. cx = p2x + d4x; cy = p2y + d4y; cz = p2z + d4z;
  97411. nx = a4x; ny = a4y; nz = a4z;
  97412. } else {
  97413. cx = p2x - d4x; cy = p2y - d4y; cz = p2z - d4z;
  97414. nx = -a4x; ny = -a4y; nz = -a4z;
  97415. }
  97416. s1x = d5x; s1y = d5y; s1z = d5z;
  97417. n1x = -a5x; n1y = -a5y; n1z = -a5z;
  97418. s2x = d6x; s2y = d6y; s2z = d6z;
  97419. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  97420. }
  97421. else if (minIndex == 4) {// b2.y * b1
  97422. swap = true;
  97423. if (!right) {
  97424. cx = p2x + d5x; cy = p2y + d5y; cz = p2z + d5z;
  97425. nx = a5x; ny = a5y; nz = a5z;
  97426. } else {
  97427. cx = p2x - d5x; cy = p2y - d5y; cz = p2z - d5z;
  97428. nx = -a5x; ny = -a5y; nz = -a5z;
  97429. }
  97430. s1x = d4x; s1y = d4y; s1z = d4z;
  97431. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  97432. s2x = d6x; s2y = d6y; s2z = d6z;
  97433. n2x = -a6x; n2y = -a6y; n2z = -a6z;
  97434. }
  97435. else if (minIndex == 5) {// b2.z * b1
  97436. swap = true;
  97437. if (!right) {
  97438. cx = p2x + d6x; cy = p2y + d6y; cz = p2z + d6z;
  97439. nx = a6x; ny = a6y; nz = a6z;
  97440. } else {
  97441. cx = p2x - d6x; cy = p2y - d6y; cz = p2z - d6z;
  97442. nx = -a6x; ny = -a6y; nz = -a6z;
  97443. }
  97444. s1x = d4x; s1y = d4y; s1z = d4z;
  97445. n1x = -a4x; n1y = -a4y; n1z = -a4z;
  97446. s2x = d5x; s2y = d5y; s2z = d5z;
  97447. n2x = -a5x; n2y = -a5y; n2z = -a5z;
  97448. }
  97449. else if (minIndex == 6) {// b1.x * b2.x
  97450. nx = a7x; ny = a7y; nz = a7z;
  97451. n1x = a1x; n1y = a1y; n1z = a1z;
  97452. n2x = a4x; n2y = a4y; n2z = a4z;
  97453. }
  97454. else if (minIndex == 7) {// b1.x * b2.y
  97455. nx = a8x; ny = a8y; nz = a8z;
  97456. n1x = a1x; n1y = a1y; n1z = a1z;
  97457. n2x = a5x; n2y = a5y; n2z = a5z;
  97458. }
  97459. else if (minIndex == 8) {// b1.x * b2.z
  97460. nx = a9x; ny = a9y; nz = a9z;
  97461. n1x = a1x; n1y = a1y; n1z = a1z;
  97462. n2x = a6x; n2y = a6y; n2z = a6z;
  97463. }
  97464. else if (minIndex == 9) {// b1.y * b2.x
  97465. nx = aax; ny = aay; nz = aaz;
  97466. n1x = a2x; n1y = a2y; n1z = a2z;
  97467. n2x = a4x; n2y = a4y; n2z = a4z
  97468. }
  97469. else if (minIndex == 10) {// b1.y * b2.y
  97470. nx = abx; ny = aby; nz = abz;
  97471. n1x = a2x; n1y = a2y; n1z = a2z;
  97472. n2x = a5x; n2y = a5y; n2z = a5z;
  97473. }
  97474. else if (minIndex == 11) {// b1.y * b2.z
  97475. nx = acx; ny = acy; nz = acz;
  97476. n1x = a2x; n1y = a2y; n1z = a2z;
  97477. n2x = a6x; n2y = a6y; n2z = a6z;
  97478. }
  97479. else if (minIndex == 12) {// b1.z * b2.x
  97480. nx = adx; ny = ady; nz = adz;
  97481. n1x = a3x; n1y = a3y; n1z = a3z;
  97482. n2x = a4x; n2y = a4y; n2z = a4z;
  97483. }
  97484. else if (minIndex == 13) {// b1.z * b2.y
  97485. nx = aex; ny = aey; nz = aez;
  97486. n1x = a3x; n1y = a3y; n1z = a3z;
  97487. n2x = a5x; n2y = a5y; n2z = a5z;
  97488. }
  97489. else if (minIndex == 14) {// b1.z * b2.z
  97490. nx = afx; ny = afy; nz = afz;
  97491. n1x = a3x; n1y = a3y; n1z = a3z;
  97492. n2x = a6x; n2y = a6y; n2z = a6z;
  97493. }
  97494. //__________________________________________
  97495. var v;
  97496. if (minIndex > 5) {
  97497. if (!right) {
  97498. nx = -nx; ny = -ny; nz = -nz;
  97499. }
  97500. var distance;
  97501. var maxDistance;
  97502. var vx;
  97503. var vy;
  97504. var vz;
  97505. var v1x;
  97506. var v1y;
  97507. var v1z;
  97508. var v2x;
  97509. var v2y;
  97510. var v2z;
  97511. //vertex1;
  97512. v1x = V1[0]; v1y = V1[1]; v1z = V1[2];
  97513. maxDistance = nx * v1x + ny * v1y + nz * v1z;
  97514. //vertex2;
  97515. vx = V1[3]; vy = V1[4]; vz = V1[5];
  97516. distance = nx * vx + ny * vy + nz * vz;
  97517. if (distance > maxDistance) {
  97518. maxDistance = distance;
  97519. v1x = vx; v1y = vy; v1z = vz;
  97520. }
  97521. //vertex3;
  97522. vx = V1[6]; vy = V1[7]; vz = V1[8];
  97523. distance = nx * vx + ny * vy + nz * vz;
  97524. if (distance > maxDistance) {
  97525. maxDistance = distance;
  97526. v1x = vx; v1y = vy; v1z = vz;
  97527. }
  97528. //vertex4;
  97529. vx = V1[9]; vy = V1[10]; vz = V1[11];
  97530. distance = nx * vx + ny * vy + nz * vz;
  97531. if (distance > maxDistance) {
  97532. maxDistance = distance;
  97533. v1x = vx; v1y = vy; v1z = vz;
  97534. }
  97535. //vertex5;
  97536. vx = V1[12]; vy = V1[13]; vz = V1[14];
  97537. distance = nx * vx + ny * vy + nz * vz;
  97538. if (distance > maxDistance) {
  97539. maxDistance = distance;
  97540. v1x = vx; v1y = vy; v1z = vz;
  97541. }
  97542. //vertex6;
  97543. vx = V1[15]; vy = V1[16]; vz = V1[17];
  97544. distance = nx * vx + ny * vy + nz * vz;
  97545. if (distance > maxDistance) {
  97546. maxDistance = distance;
  97547. v1x = vx; v1y = vy; v1z = vz;
  97548. }
  97549. //vertex7;
  97550. vx = V1[18]; vy = V1[19]; vz = V1[20];
  97551. distance = nx * vx + ny * vy + nz * vz;
  97552. if (distance > maxDistance) {
  97553. maxDistance = distance;
  97554. v1x = vx; v1y = vy; v1z = vz;
  97555. }
  97556. //vertex8;
  97557. vx = V1[21]; vy = V1[22]; vz = V1[23];
  97558. distance = nx * vx + ny * vy + nz * vz;
  97559. if (distance > maxDistance) {
  97560. maxDistance = distance;
  97561. v1x = vx; v1y = vy; v1z = vz;
  97562. }
  97563. //vertex1;
  97564. v2x = V2[0]; v2y = V2[1]; v2z = V2[2];
  97565. maxDistance = nx * v2x + ny * v2y + nz * v2z;
  97566. //vertex2;
  97567. vx = V2[3]; vy = V2[4]; vz = V2[5];
  97568. distance = nx * vx + ny * vy + nz * vz;
  97569. if (distance < maxDistance) {
  97570. maxDistance = distance;
  97571. v2x = vx; v2y = vy; v2z = vz;
  97572. }
  97573. //vertex3;
  97574. vx = V2[6]; vy = V2[7]; vz = V2[8];
  97575. distance = nx * vx + ny * vy + nz * vz;
  97576. if (distance < maxDistance) {
  97577. maxDistance = distance;
  97578. v2x = vx; v2y = vy; v2z = vz;
  97579. }
  97580. //vertex4;
  97581. vx = V2[9]; vy = V2[10]; vz = V2[11];
  97582. distance = nx * vx + ny * vy + nz * vz;
  97583. if (distance < maxDistance) {
  97584. maxDistance = distance;
  97585. v2x = vx; v2y = vy; v2z = vz;
  97586. }
  97587. //vertex5;
  97588. vx = V2[12]; vy = V2[13]; vz = V2[14];
  97589. distance = nx * vx + ny * vy + nz * vz;
  97590. if (distance < maxDistance) {
  97591. maxDistance = distance;
  97592. v2x = vx; v2y = vy; v2z = vz;
  97593. }
  97594. //vertex6;
  97595. vx = V2[15]; vy = V2[16]; vz = V2[17];
  97596. distance = nx * vx + ny * vy + nz * vz;
  97597. if (distance < maxDistance) {
  97598. maxDistance = distance;
  97599. v2x = vx; v2y = vy; v2z = vz;
  97600. }
  97601. //vertex7;
  97602. vx = V2[18]; vy = V2[19]; vz = V2[20];
  97603. distance = nx * vx + ny * vy + nz * vz;
  97604. if (distance < maxDistance) {
  97605. maxDistance = distance;
  97606. v2x = vx; v2y = vy; v2z = vz;
  97607. }
  97608. //vertex8;
  97609. vx = V2[21]; vy = V2[22]; vz = V2[23];
  97610. distance = nx * vx + ny * vy + nz * vz;
  97611. if (distance < maxDistance) {
  97612. maxDistance = distance;
  97613. v2x = vx; v2y = vy; v2z = vz;
  97614. }
  97615. vx = v2x - v1x; vy = v2y - v1y; vz = v2z - v1z;
  97616. dot1 = n1x * n2x + n1y * n2y + n1z * n2z;
  97617. var t = (vx * (n1x - n2x * dot1) + vy * (n1y - n2y * dot1) + vz * (n1z - n2z * dot1)) / (1 - dot1 * dot1);
  97618. 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);
  97619. return;
  97620. }
  97621. // now detect face-face collision...
  97622. // target quad
  97623. var q1x;
  97624. var q1y;
  97625. var q1z;
  97626. var q2x;
  97627. var q2y;
  97628. var q2z;
  97629. var q3x;
  97630. var q3y;
  97631. var q3z;
  97632. var q4x;
  97633. var q4y;
  97634. var q4z;
  97635. // search support face and vertex
  97636. var minDot = 1;
  97637. var dot = 0;
  97638. var minDotIndex = 0;
  97639. if (swap) {
  97640. dot = a1x * nx + a1y * ny + a1z * nz;
  97641. if (dot < minDot) {
  97642. minDot = dot;
  97643. minDotIndex = 0;
  97644. }
  97645. if (-dot < minDot) {
  97646. minDot = -dot;
  97647. minDotIndex = 1;
  97648. }
  97649. dot = a2x * nx + a2y * ny + a2z * nz;
  97650. if (dot < minDot) {
  97651. minDot = dot;
  97652. minDotIndex = 2;
  97653. }
  97654. if (-dot < minDot) {
  97655. minDot = -dot;
  97656. minDotIndex = 3;
  97657. }
  97658. dot = a3x * nx + a3y * ny + a3z * nz;
  97659. if (dot < minDot) {
  97660. minDot = dot;
  97661. minDotIndex = 4;
  97662. }
  97663. if (-dot < minDot) {
  97664. minDot = -dot;
  97665. minDotIndex = 5;
  97666. }
  97667. if (minDotIndex == 0) {// x+ face
  97668. q1x = V1[0]; q1y = V1[1]; q1z = V1[2];//vertex1
  97669. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex3
  97670. q3x = V1[9]; q3y = V1[10]; q3z = V1[11];//vertex4
  97671. q4x = V1[3]; q4y = V1[4]; q4z = V1[5];//vertex2
  97672. }
  97673. else if (minDotIndex == 1) {// x- face
  97674. q1x = V1[15]; q1y = V1[16]; q1z = V1[17];//vertex6
  97675. q2x = V1[21]; q2y = V1[22]; q2z = V1[23];//vertex8
  97676. q3x = V1[18]; q3y = V1[19]; q3z = V1[20];//vertex7
  97677. q4x = V1[12]; q4y = V1[13]; q4z = V1[14];//vertex5
  97678. }
  97679. else if (minDotIndex == 2) {// y+ face
  97680. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  97681. q2x = V1[0]; q2y = V1[1]; q2z = V1[2];//vertex1
  97682. q3x = V1[3]; q3y = V1[4]; q3z = V1[5];//vertex2
  97683. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  97684. }
  97685. else if (minDotIndex == 3) {// y- face
  97686. q1x = V1[21]; q1y = V1[22]; q1z = V1[23];//vertex8
  97687. q2x = V1[9]; q2y = V1[10]; q2z = V1[11];//vertex4
  97688. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  97689. q4x = V1[18]; q4y = V1[19]; q4z = V1[20];//vertex7
  97690. }
  97691. else if (minDotIndex == 4) {// z+ face
  97692. q1x = V1[12]; q1y = V1[13]; q1z = V1[14];//vertex5
  97693. q2x = V1[18]; q2y = V1[19]; q2z = V1[20];//vertex7
  97694. q3x = V1[6]; q3y = V1[7]; q3z = V1[8];//vertex3
  97695. q4x = V1[0]; q4y = V1[1]; q4z = V1[2];//vertex1
  97696. }
  97697. else if (minDotIndex == 5) {// z- face
  97698. q1x = V1[3]; q1y = V1[4]; q1z = V1[5];//vertex2
  97699. q2x = V1[6]; q2y = V1[7]; q2z = V1[8];//vertex4
  97700. q3x = V1[21]; q3y = V1[22]; q3z = V1[23];//vertex8
  97701. q4x = V1[15]; q4y = V1[16]; q4z = V1[17];//vertex6
  97702. }
  97703. } else {
  97704. dot = a4x * nx + a4y * ny + a4z * nz;
  97705. if (dot < minDot) {
  97706. minDot = dot;
  97707. minDotIndex = 0;
  97708. }
  97709. if (-dot < minDot) {
  97710. minDot = -dot;
  97711. minDotIndex = 1;
  97712. }
  97713. dot = a5x * nx + a5y * ny + a5z * nz;
  97714. if (dot < minDot) {
  97715. minDot = dot;
  97716. minDotIndex = 2;
  97717. }
  97718. if (-dot < minDot) {
  97719. minDot = -dot;
  97720. minDotIndex = 3;
  97721. }
  97722. dot = a6x * nx + a6y * ny + a6z * nz;
  97723. if (dot < minDot) {
  97724. minDot = dot;
  97725. minDotIndex = 4;
  97726. }
  97727. if (-dot < minDot) {
  97728. minDot = -dot;
  97729. minDotIndex = 5;
  97730. }
  97731. //______________________________________________________
  97732. if (minDotIndex == 0) {// x+ face
  97733. q1x = V2[0]; q1y = V2[1]; q1z = V2[2];//vertex1
  97734. q2x = V2[6]; q2y = V2[7]; q2z = V2[8];//vertex3
  97735. q3x = V2[9]; q3y = V2[10]; q3z = V2[11];//vertex4
  97736. q4x = V2[3]; q4y = V2[4]; q4z = V2[5];//vertex2
  97737. }
  97738. else if (minDotIndex == 1) {// x- face
  97739. q1x = V2[15]; q1y = V2[16]; q1z = V2[17];//vertex6
  97740. q2x = V2[21]; q2y = V2[22]; q2z = V2[23]; //vertex8
  97741. q3x = V2[18]; q3y = V2[19]; q3z = V2[20];//vertex7
  97742. q4x = V2[12]; q4y = V2[13]; q4z = V2[14];//vertex5
  97743. }
  97744. else if (minDotIndex == 2) {// y+ face
  97745. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  97746. q2x = V2[0]; q2y = V2[1]; q2z = V2[2];//vertex1
  97747. q3x = V2[3]; q3y = V2[4]; q3z = V2[5];//vertex2
  97748. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  97749. }
  97750. else if (minDotIndex == 3) {// y- face
  97751. q1x = V2[21]; q1y = V2[22]; q1z = V2[23];//vertex8
  97752. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  97753. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  97754. q4x = V2[18]; q4y = V2[19]; q4z = V2[20];//vertex7
  97755. }
  97756. else if (minDotIndex == 4) {// z+ face
  97757. q1x = V2[12]; q1y = V2[13]; q1z = V2[14];//vertex5
  97758. q2x = V2[18]; q2y = V2[19]; q2z = V2[20];//vertex7
  97759. q3x = V2[6]; q3y = V2[7]; q3z = V2[8];//vertex3
  97760. q4x = V2[0]; q4y = V2[1]; q4z = V2[2];//vertex1
  97761. }
  97762. else if (minDotIndex == 5) {// z- face
  97763. q1x = V2[3]; q1y = V2[4]; q1z = V2[5];//vertex2
  97764. q2x = V2[9]; q2y = V2[10]; q2z = V2[11];//vertex4
  97765. q3x = V2[21]; q3y = V2[22]; q3z = V2[23];//vertex8
  97766. q4x = V2[15]; q4y = V2[16]; q4z = V2[17];//vertex6
  97767. }
  97768. }
  97769. // clip vertices
  97770. var numClipVertices;
  97771. var numAddedClipVertices;
  97772. var index;
  97773. var x1;
  97774. var y1;
  97775. var z1;
  97776. var x2;
  97777. var y2;
  97778. var z2;
  97779. this.clipVertices1[0] = q1x;
  97780. this.clipVertices1[1] = q1y;
  97781. this.clipVertices1[2] = q1z;
  97782. this.clipVertices1[3] = q2x;
  97783. this.clipVertices1[4] = q2y;
  97784. this.clipVertices1[5] = q2z;
  97785. this.clipVertices1[6] = q3x;
  97786. this.clipVertices1[7] = q3y;
  97787. this.clipVertices1[8] = q3z;
  97788. this.clipVertices1[9] = q4x;
  97789. this.clipVertices1[10] = q4y;
  97790. this.clipVertices1[11] = q4z;
  97791. numAddedClipVertices = 0;
  97792. x1 = this.clipVertices1[9];
  97793. y1 = this.clipVertices1[10];
  97794. z1 = this.clipVertices1[11];
  97795. dot1 = (x1 - cx - s1x) * n1x + (y1 - cy - s1y) * n1y + (z1 - cz - s1z) * n1z;
  97796. //var i = 4;
  97797. //while(i--){
  97798. for (var i = 0; i < 4; i++) {
  97799. index = i * 3;
  97800. x2 = this.clipVertices1[index];
  97801. y2 = this.clipVertices1[index + 1];
  97802. z2 = this.clipVertices1[index + 2];
  97803. dot2 = (x2 - cx - s1x) * n1x + (y2 - cy - s1y) * n1y + (z2 - cz - s1z) * n1z;
  97804. if (dot1 > 0) {
  97805. if (dot2 > 0) {
  97806. index = numAddedClipVertices * 3;
  97807. numAddedClipVertices++;
  97808. this.clipVertices2[index] = x2;
  97809. this.clipVertices2[index + 1] = y2;
  97810. this.clipVertices2[index + 2] = z2;
  97811. } else {
  97812. index = numAddedClipVertices * 3;
  97813. numAddedClipVertices++;
  97814. t = dot1 / (dot1 - dot2);
  97815. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97816. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97817. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97818. }
  97819. } else {
  97820. if (dot2 > 0) {
  97821. index = numAddedClipVertices * 3;
  97822. numAddedClipVertices++;
  97823. t = dot1 / (dot1 - dot2);
  97824. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97825. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97826. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97827. index = numAddedClipVertices * 3;
  97828. numAddedClipVertices++;
  97829. this.clipVertices2[index] = x2;
  97830. this.clipVertices2[index + 1] = y2;
  97831. this.clipVertices2[index + 2] = z2;
  97832. }
  97833. }
  97834. x1 = x2;
  97835. y1 = y2;
  97836. z1 = z2;
  97837. dot1 = dot2;
  97838. }
  97839. numClipVertices = numAddedClipVertices;
  97840. if (numClipVertices == 0) return;
  97841. numAddedClipVertices = 0;
  97842. index = (numClipVertices - 1) * 3;
  97843. x1 = this.clipVertices2[index];
  97844. y1 = this.clipVertices2[index + 1];
  97845. z1 = this.clipVertices2[index + 2];
  97846. dot1 = (x1 - cx - s2x) * n2x + (y1 - cy - s2y) * n2y + (z1 - cz - s2z) * n2z;
  97847. //i = numClipVertices;
  97848. //while(i--){
  97849. for (i = 0; i < numClipVertices; i++) {
  97850. index = i * 3;
  97851. x2 = this.clipVertices2[index];
  97852. y2 = this.clipVertices2[index + 1];
  97853. z2 = this.clipVertices2[index + 2];
  97854. dot2 = (x2 - cx - s2x) * n2x + (y2 - cy - s2y) * n2y + (z2 - cz - s2z) * n2z;
  97855. if (dot1 > 0) {
  97856. if (dot2 > 0) {
  97857. index = numAddedClipVertices * 3;
  97858. numAddedClipVertices++;
  97859. this.clipVertices1[index] = x2;
  97860. this.clipVertices1[index + 1] = y2;
  97861. this.clipVertices1[index + 2] = z2;
  97862. } else {
  97863. index = numAddedClipVertices * 3;
  97864. numAddedClipVertices++;
  97865. t = dot1 / (dot1 - dot2);
  97866. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97867. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97868. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97869. }
  97870. } else {
  97871. if (dot2 > 0) {
  97872. index = numAddedClipVertices * 3;
  97873. numAddedClipVertices++;
  97874. t = dot1 / (dot1 - dot2);
  97875. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97876. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97877. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97878. index = numAddedClipVertices * 3;
  97879. numAddedClipVertices++;
  97880. this.clipVertices1[index] = x2;
  97881. this.clipVertices1[index + 1] = y2;
  97882. this.clipVertices1[index + 2] = z2;
  97883. }
  97884. }
  97885. x1 = x2;
  97886. y1 = y2;
  97887. z1 = z2;
  97888. dot1 = dot2;
  97889. }
  97890. numClipVertices = numAddedClipVertices;
  97891. if (numClipVertices == 0) return;
  97892. numAddedClipVertices = 0;
  97893. index = (numClipVertices - 1) * 3;
  97894. x1 = this.clipVertices1[index];
  97895. y1 = this.clipVertices1[index + 1];
  97896. z1 = this.clipVertices1[index + 2];
  97897. dot1 = (x1 - cx + s1x) * -n1x + (y1 - cy + s1y) * -n1y + (z1 - cz + s1z) * -n1z;
  97898. //i = numClipVertices;
  97899. //while(i--){
  97900. for (i = 0; i < numClipVertices; i++) {
  97901. index = i * 3;
  97902. x2 = this.clipVertices1[index];
  97903. y2 = this.clipVertices1[index + 1];
  97904. z2 = this.clipVertices1[index + 2];
  97905. dot2 = (x2 - cx + s1x) * -n1x + (y2 - cy + s1y) * -n1y + (z2 - cz + s1z) * -n1z;
  97906. if (dot1 > 0) {
  97907. if (dot2 > 0) {
  97908. index = numAddedClipVertices * 3;
  97909. numAddedClipVertices++;
  97910. this.clipVertices2[index] = x2;
  97911. this.clipVertices2[index + 1] = y2;
  97912. this.clipVertices2[index + 2] = z2;
  97913. } else {
  97914. index = numAddedClipVertices * 3;
  97915. numAddedClipVertices++;
  97916. t = dot1 / (dot1 - dot2);
  97917. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97918. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97919. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97920. }
  97921. } else {
  97922. if (dot2 > 0) {
  97923. index = numAddedClipVertices * 3;
  97924. numAddedClipVertices++;
  97925. t = dot1 / (dot1 - dot2);
  97926. this.clipVertices2[index] = x1 + (x2 - x1) * t;
  97927. this.clipVertices2[index + 1] = y1 + (y2 - y1) * t;
  97928. this.clipVertices2[index + 2] = z1 + (z2 - z1) * t;
  97929. index = numAddedClipVertices * 3;
  97930. numAddedClipVertices++;
  97931. this.clipVertices2[index] = x2;
  97932. this.clipVertices2[index + 1] = y2;
  97933. this.clipVertices2[index + 2] = z2;
  97934. }
  97935. }
  97936. x1 = x2;
  97937. y1 = y2;
  97938. z1 = z2;
  97939. dot1 = dot2;
  97940. }
  97941. numClipVertices = numAddedClipVertices;
  97942. if (numClipVertices == 0) return;
  97943. numAddedClipVertices = 0;
  97944. index = (numClipVertices - 1) * 3;
  97945. x1 = this.clipVertices2[index];
  97946. y1 = this.clipVertices2[index + 1];
  97947. z1 = this.clipVertices2[index + 2];
  97948. dot1 = (x1 - cx + s2x) * -n2x + (y1 - cy + s2y) * -n2y + (z1 - cz + s2z) * -n2z;
  97949. //i = numClipVertices;
  97950. //while(i--){
  97951. for (i = 0; i < numClipVertices; i++) {
  97952. index = i * 3;
  97953. x2 = this.clipVertices2[index];
  97954. y2 = this.clipVertices2[index + 1];
  97955. z2 = this.clipVertices2[index + 2];
  97956. dot2 = (x2 - cx + s2x) * -n2x + (y2 - cy + s2y) * -n2y + (z2 - cz + s2z) * -n2z;
  97957. if (dot1 > 0) {
  97958. if (dot2 > 0) {
  97959. index = numAddedClipVertices * 3;
  97960. numAddedClipVertices++;
  97961. this.clipVertices1[index] = x2;
  97962. this.clipVertices1[index + 1] = y2;
  97963. this.clipVertices1[index + 2] = z2;
  97964. } else {
  97965. index = numAddedClipVertices * 3;
  97966. numAddedClipVertices++;
  97967. t = dot1 / (dot1 - dot2);
  97968. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97969. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97970. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97971. }
  97972. } else {
  97973. if (dot2 > 0) {
  97974. index = numAddedClipVertices * 3;
  97975. numAddedClipVertices++;
  97976. t = dot1 / (dot1 - dot2);
  97977. this.clipVertices1[index] = x1 + (x2 - x1) * t;
  97978. this.clipVertices1[index + 1] = y1 + (y2 - y1) * t;
  97979. this.clipVertices1[index + 2] = z1 + (z2 - z1) * t;
  97980. index = numAddedClipVertices * 3;
  97981. numAddedClipVertices++;
  97982. this.clipVertices1[index] = x2;
  97983. this.clipVertices1[index + 1] = y2;
  97984. this.clipVertices1[index + 2] = z2;
  97985. }
  97986. }
  97987. x1 = x2;
  97988. y1 = y2;
  97989. z1 = z2;
  97990. dot1 = dot2;
  97991. }
  97992. numClipVertices = numAddedClipVertices;
  97993. if (swap) {
  97994. var tb = b1;
  97995. b1 = b2;
  97996. b2 = tb;
  97997. }
  97998. if (numClipVertices == 0) return;
  97999. var flipped = b1 != shape1;
  98000. if (numClipVertices > 4) {
  98001. x1 = (q1x + q2x + q3x + q4x) * 0.25;
  98002. y1 = (q1y + q2y + q3y + q4y) * 0.25;
  98003. z1 = (q1z + q2z + q3z + q4z) * 0.25;
  98004. n1x = q1x - x1;
  98005. n1y = q1y - y1;
  98006. n1z = q1z - z1;
  98007. n2x = q2x - x1;
  98008. n2y = q2y - y1;
  98009. n2z = q2z - z1;
  98010. var index1 = 0;
  98011. var index2 = 0;
  98012. var index3 = 0;
  98013. var index4 = 0;
  98014. var maxDot = -this.INF;
  98015. minDot = this.INF;
  98016. //i = numClipVertices;
  98017. //while(i--){
  98018. for (i = 0; i < numClipVertices; i++) {
  98019. this.used[i] = false;
  98020. index = i * 3;
  98021. x1 = this.clipVertices1[index];
  98022. y1 = this.clipVertices1[index + 1];
  98023. z1 = this.clipVertices1[index + 2];
  98024. dot = x1 * n1x + y1 * n1y + z1 * n1z;
  98025. if (dot < minDot) {
  98026. minDot = dot;
  98027. index1 = i;
  98028. }
  98029. if (dot > maxDot) {
  98030. maxDot = dot;
  98031. index3 = i;
  98032. }
  98033. }
  98034. this.used[index1] = true;
  98035. this.used[index3] = true;
  98036. maxDot = -this.INF;
  98037. minDot = this.INF;
  98038. //i = numClipVertices;
  98039. //while(i--){
  98040. for (i = 0; i < numClipVertices; i++) {
  98041. if (this.used[i]) continue;
  98042. index = i * 3;
  98043. x1 = this.clipVertices1[index];
  98044. y1 = this.clipVertices1[index + 1];
  98045. z1 = this.clipVertices1[index + 2];
  98046. dot = x1 * n2x + y1 * n2y + z1 * n2z;
  98047. if (dot < minDot) {
  98048. minDot = dot;
  98049. index2 = i;
  98050. }
  98051. if (dot > maxDot) {
  98052. maxDot = dot;
  98053. index4 = i;
  98054. }
  98055. }
  98056. index = index1 * 3;
  98057. x1 = this.clipVertices1[index];
  98058. y1 = this.clipVertices1[index + 1];
  98059. z1 = this.clipVertices1[index + 2];
  98060. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  98061. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  98062. index = index2 * 3;
  98063. x1 = this.clipVertices1[index];
  98064. y1 = this.clipVertices1[index + 1];
  98065. z1 = this.clipVertices1[index + 2];
  98066. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  98067. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  98068. index = index3 * 3;
  98069. x1 = this.clipVertices1[index];
  98070. y1 = this.clipVertices1[index + 1];
  98071. z1 = this.clipVertices1[index + 2];
  98072. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  98073. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  98074. index = index4 * 3;
  98075. x1 = this.clipVertices1[index];
  98076. y1 = this.clipVertices1[index + 1];
  98077. z1 = this.clipVertices1[index + 2];
  98078. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  98079. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  98080. } else {
  98081. //i = numClipVertices;
  98082. //while(i--){
  98083. for (i = 0; i < numClipVertices; i++) {
  98084. index = i * 3;
  98085. x1 = this.clipVertices1[index];
  98086. y1 = this.clipVertices1[index + 1];
  98087. z1 = this.clipVertices1[index + 2];
  98088. dot = (x1 - cx) * nx + (y1 - cy) * ny + (z1 - cz) * nz;
  98089. if (dot < 0) manifold.addPoint(x1, y1, z1, nx, ny, nz, dot, flipped);
  98090. }
  98091. }
  98092. };
  98093. /**
  98094. * A collision detector which detects collisions between sphere and box.
  98095. * @author saharan
  98096. */
  98097. OIMO.SphereBoxCollisionDetector = function (flip) {
  98098. OIMO.CollisionDetector.call(this);
  98099. this.flip = flip;
  98100. };
  98101. OIMO.SphereBoxCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98102. OIMO.SphereBoxCollisionDetector.prototype.constructor = OIMO.SphereBoxCollisionDetector;
  98103. OIMO.SphereBoxCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98104. var s;
  98105. var b;
  98106. if (this.flip) {
  98107. s = (shape2);
  98108. b = (shape1);
  98109. } else {
  98110. s = (shape1);
  98111. b = (shape2);
  98112. }
  98113. var D = b.dimentions;
  98114. var ps = s.position;
  98115. var psx = ps.x;
  98116. var psy = ps.y;
  98117. var psz = ps.z;
  98118. var pb = b.position;
  98119. var pbx = pb.x;
  98120. var pby = pb.y;
  98121. var pbz = pb.z;
  98122. var rad = s.radius;
  98123. var hw = b.halfWidth;
  98124. var hh = b.halfHeight;
  98125. var hd = b.halfDepth;
  98126. var dx = psx - pbx;
  98127. var dy = psy - pby;
  98128. var dz = psz - pbz;
  98129. var sx = D[0] * dx + D[1] * dy + D[2] * dz;
  98130. var sy = D[3] * dx + D[4] * dy + D[5] * dz;
  98131. var sz = D[6] * dx + D[7] * dy + D[8] * dz;
  98132. var cx;
  98133. var cy;
  98134. var cz;
  98135. var len;
  98136. var invLen;
  98137. var overlap = 0;
  98138. if (sx > hw) {
  98139. sx = hw;
  98140. } else if (sx < -hw) {
  98141. sx = -hw;
  98142. } else {
  98143. overlap = 1;
  98144. }
  98145. if (sy > hh) {
  98146. sy = hh;
  98147. } else if (sy < -hh) {
  98148. sy = -hh;
  98149. } else {
  98150. overlap |= 2;
  98151. }
  98152. if (sz > hd) {
  98153. sz = hd;
  98154. } else if (sz < -hd) {
  98155. sz = -hd;
  98156. } else {
  98157. overlap |= 4;
  98158. }
  98159. if (overlap == 7) {
  98160. // center of sphere is in the box
  98161. if (sx < 0) {
  98162. dx = hw + sx;
  98163. } else {
  98164. dx = hw - sx;
  98165. }
  98166. if (sy < 0) {
  98167. dy = hh + sy;
  98168. } else {
  98169. dy = hh - sy;
  98170. }
  98171. if (sz < 0) {
  98172. dz = hd + sz;
  98173. } else {
  98174. dz = hd - sz;
  98175. }
  98176. if (dx < dy) {
  98177. if (dx < dz) {
  98178. len = dx - hw;
  98179. if (sx < 0) {
  98180. sx = -hw;
  98181. dx = D[0];
  98182. dy = D[1];
  98183. dz = D[2];
  98184. } else {
  98185. sx = hw;
  98186. dx = -D[0];
  98187. dy = -D[1];
  98188. dz = -D[2];
  98189. }
  98190. } else {
  98191. len = dz - hd;
  98192. if (sz < 0) {
  98193. sz = -hd;
  98194. dx = D[6];
  98195. dy = D[7];
  98196. dz = D[8];
  98197. } else {
  98198. sz = hd;
  98199. dx = -D[6];
  98200. dy = -D[7];
  98201. dz = -D[8];
  98202. }
  98203. }
  98204. } else {
  98205. if (dy < dz) {
  98206. len = dy - hh;
  98207. if (sy < 0) {
  98208. sy = -hh;
  98209. dx = D[3];
  98210. dy = D[4];
  98211. dz = D[5];
  98212. } else {
  98213. sy = hh;
  98214. dx = -D[3];
  98215. dy = -D[4];
  98216. dz = -D[5];
  98217. }
  98218. } else {
  98219. len = dz - hd;
  98220. if (sz < 0) {
  98221. sz = -hd;
  98222. dx = D[6];
  98223. dy = D[7];
  98224. dz = D[8];
  98225. } else {
  98226. sz = hd;
  98227. dx = -D[6];
  98228. dy = -D[7];
  98229. dz = -D[8];
  98230. }
  98231. }
  98232. }
  98233. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  98234. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  98235. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  98236. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  98237. } else {
  98238. cx = pbx + sx * D[0] + sy * D[3] + sz * D[6];
  98239. cy = pby + sx * D[1] + sy * D[4] + sz * D[7];
  98240. cz = pbz + sx * D[2] + sy * D[5] + sz * D[8];
  98241. dx = cx - ps.x;
  98242. dy = cy - ps.y;
  98243. dz = cz - ps.z;
  98244. len = dx * dx + dy * dy + dz * dz;
  98245. if (len > 0 && len < rad * rad) {
  98246. len = OIMO.sqrt(len);
  98247. invLen = 1 / len;
  98248. dx *= invLen;
  98249. dy *= invLen;
  98250. dz *= invLen;
  98251. manifold.addPoint(psx + rad * dx, psy + rad * dy, psz + rad * dz, dx, dy, dz, len - rad, this.flip);
  98252. }
  98253. }
  98254. };
  98255. /**
  98256. * A collision detector which detects collisions between two spheres.
  98257. * @author saharan
  98258. */
  98259. OIMO.SphereSphereCollisionDetector = function () {
  98260. OIMO.CollisionDetector.call(this);
  98261. };
  98262. OIMO.SphereSphereCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98263. OIMO.SphereSphereCollisionDetector.prototype.constructor = OIMO.SphereSphereCollisionDetector;
  98264. OIMO.SphereSphereCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98265. var s1 = shape1;
  98266. var s2 = shape2;
  98267. var p1 = s1.position;
  98268. var p2 = s2.position;
  98269. var dx = p2.x - p1.x;
  98270. var dy = p2.y - p1.y;
  98271. var dz = p2.z - p1.z;
  98272. var len = dx * dx + dy * dy + dz * dz;
  98273. var r1 = s1.radius;
  98274. var r2 = s2.radius;
  98275. var rad = r1 + r2;
  98276. if (len > 0 && len < rad * rad) {
  98277. len = OIMO.sqrt(len);
  98278. var invLen = 1 / len;
  98279. dx *= invLen;
  98280. dy *= invLen;
  98281. dz *= invLen;
  98282. manifold.addPoint(p1.x + dx * r1, p1.y + dy * r1, p1.z + dz * r1, dx, dy, dz, len - rad, false);
  98283. }
  98284. };
  98285. OIMO.BoxCylinderCollisionDetector = function (flip) {
  98286. OIMO.CollisionDetector.call(this);
  98287. this.flip = flip;
  98288. };
  98289. OIMO.BoxCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  98290. OIMO.BoxCylinderCollisionDetector.prototype.constructor = OIMO.BoxCylinderCollisionDetector;
  98291. OIMO.BoxCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  98292. var t1x;
  98293. var t1y;
  98294. var t1z;
  98295. var t2x;
  98296. var t2y;
  98297. var t2z;
  98298. var sup = new OIMO.Vec3();
  98299. var len;
  98300. var p1x;
  98301. var p1y;
  98302. var p1z;
  98303. var p2x;
  98304. var p2y;
  98305. var p2z;
  98306. var v01x = c1.position.x;
  98307. var v01y = c1.position.y;
  98308. var v01z = c1.position.z;
  98309. var v02x = c2.position.x;
  98310. var v02y = c2.position.y;
  98311. var v02z = c2.position.z;
  98312. var v0x = v02x - v01x;
  98313. var v0y = v02y - v01y;
  98314. var v0z = v02z - v01z;
  98315. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  98316. var nx = -v0x;
  98317. var ny = -v0y;
  98318. var nz = -v0z;
  98319. this.supportPointB(c1, -nx, -ny, -nz, sup);
  98320. var v11x = sup.x;
  98321. var v11y = sup.y;
  98322. var v11z = sup.z;
  98323. this.supportPointC(c2, nx, ny, nz, sup);
  98324. var v12x = sup.x;
  98325. var v12y = sup.y;
  98326. var v12z = sup.z;
  98327. var v1x = v12x - v11x;
  98328. var v1y = v12y - v11y;
  98329. var v1z = v12z - v11z;
  98330. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  98331. return false;
  98332. }
  98333. nx = v1y * v0z - v1z * v0y;
  98334. ny = v1z * v0x - v1x * v0z;
  98335. nz = v1x * v0y - v1y * v0x;
  98336. if (nx * nx + ny * ny + nz * nz == 0) {
  98337. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  98338. sep.normalize(sep);
  98339. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  98340. return true;
  98341. }
  98342. this.supportPointB(c1, -nx, -ny, -nz, sup);
  98343. var v21x = sup.x;
  98344. var v21y = sup.y;
  98345. var v21z = sup.z;
  98346. this.supportPointC(c2, nx, ny, nz, sup);
  98347. var v22x = sup.x;
  98348. var v22y = sup.y;
  98349. var v22z = sup.z;
  98350. var v2x = v22x - v21x;
  98351. var v2y = v22y - v21y;
  98352. var v2z = v22z - v21z;
  98353. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  98354. return false;
  98355. }
  98356. t1x = v1x - v0x;
  98357. t1y = v1y - v0y;
  98358. t1z = v1z - v0z;
  98359. t2x = v2x - v0x;
  98360. t2y = v2y - v0y;
  98361. t2z = v2z - v0z;
  98362. nx = t1y * t2z - t1z * t2y;
  98363. ny = t1z * t2x - t1x * t2z;
  98364. nz = t1x * t2y - t1y * t2x;
  98365. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  98366. t1x = v1x;
  98367. t1y = v1y;
  98368. t1z = v1z;
  98369. v1x = v2x;
  98370. v1y = v2y;
  98371. v1z = v2z;
  98372. v2x = t1x;
  98373. v2y = t1y;
  98374. v2z = t1z;
  98375. t1x = v11x;
  98376. t1y = v11y;
  98377. t1z = v11z;
  98378. v11x = v21x;
  98379. v11y = v21y;
  98380. v11z = v21z;
  98381. v21x = t1x;
  98382. v21y = t1y;
  98383. v21z = t1z;
  98384. t1x = v12x;
  98385. t1y = v12y;
  98386. t1z = v12z;
  98387. v12x = v22x;
  98388. v12y = v22y;
  98389. v12z = v22z;
  98390. v22x = t1x;
  98391. v22y = t1y;
  98392. v22z = t1z;
  98393. nx = -nx;
  98394. ny = -ny;
  98395. nz = -nz;
  98396. }
  98397. var iterations = 0;
  98398. while (true) {
  98399. if (++iterations > 100) {
  98400. return false;
  98401. }
  98402. this.supportPointB(c1, -nx, -ny, -nz, sup);
  98403. var v31x = sup.x;
  98404. var v31y = sup.y;
  98405. var v31z = sup.z;
  98406. this.supportPointC(c2, nx, ny, nz, sup);
  98407. var v32x = sup.x;
  98408. var v32y = sup.y;
  98409. var v32z = sup.z;
  98410. var v3x = v32x - v31x;
  98411. var v3y = v32y - v31y;
  98412. var v3z = v32z - v31z;
  98413. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  98414. return false;
  98415. }
  98416. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  98417. v2x = v3x;
  98418. v2y = v3y;
  98419. v2z = v3z;
  98420. v21x = v31x;
  98421. v21y = v31y;
  98422. v21z = v31z;
  98423. v22x = v32x;
  98424. v22y = v32y;
  98425. v22z = v32z;
  98426. t1x = v1x - v0x;
  98427. t1y = v1y - v0y;
  98428. t1z = v1z - v0z;
  98429. t2x = v3x - v0x;
  98430. t2y = v3y - v0y;
  98431. t2z = v3z - v0z;
  98432. nx = t1y * t2z - t1z * t2y;
  98433. ny = t1z * t2x - t1x * t2z;
  98434. nz = t1x * t2y - t1y * t2x;
  98435. continue;
  98436. }
  98437. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  98438. v1x = v3x;
  98439. v1y = v3y;
  98440. v1z = v3z;
  98441. v11x = v31x;
  98442. v11y = v31y;
  98443. v11z = v31z;
  98444. v12x = v32x;
  98445. v12y = v32y;
  98446. v12z = v32z;
  98447. t1x = v3x - v0x;
  98448. t1y = v3y - v0y;
  98449. t1z = v3z - v0z;
  98450. t2x = v2x - v0x;
  98451. t2y = v2y - v0y;
  98452. t2z = v2z - v0z;
  98453. nx = t1y * t2z - t1z * t2y;
  98454. ny = t1z * t2x - t1x * t2z;
  98455. nz = t1x * t2y - t1y * t2x;
  98456. continue;
  98457. }
  98458. var hit = false;
  98459. while (true) {
  98460. t1x = v2x - v1x;
  98461. t1y = v2y - v1y;
  98462. t1z = v2z - v1z;
  98463. t2x = v3x - v1x;
  98464. t2y = v3y - v1y;
  98465. t2z = v3z - v1z;
  98466. nx = t1y * t2z - t1z * t2y;
  98467. ny = t1z * t2x - t1x * t2z;
  98468. nz = t1x * t2y - t1y * t2x;
  98469. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  98470. nx *= len;
  98471. ny *= len;
  98472. nz *= len;
  98473. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  98474. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  98475. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  98476. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  98477. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  98478. var sum = b0 + b1 + b2 + b3;
  98479. if (sum <= 0) {
  98480. b0 = 0;
  98481. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  98482. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  98483. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  98484. sum = b1 + b2 + b3;
  98485. }
  98486. var inv = 1 / sum;
  98487. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  98488. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  98489. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  98490. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  98491. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  98492. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  98493. hit = true;
  98494. }
  98495. this.supportPointB(c1, -nx, -ny, -nz, sup);
  98496. var v41x = sup.x;
  98497. var v41y = sup.y;
  98498. var v41z = sup.z;
  98499. this.supportPointC(c2, nx, ny, nz, sup);
  98500. var v42x = sup.x;
  98501. var v42y = sup.y;
  98502. var v42z = sup.z;
  98503. var v4x = v42x - v41x;
  98504. var v4y = v42y - v41y;
  98505. var v4z = v42z - v41z;
  98506. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  98507. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  98508. if (hit) {
  98509. sep.init(-nx, -ny, -nz);
  98510. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  98511. dep.x = separation;
  98512. return true;
  98513. }
  98514. return false;
  98515. }
  98516. if (
  98517. (v4y * v1z - v4z * v1y) * v0x +
  98518. (v4z * v1x - v4x * v1z) * v0y +
  98519. (v4x * v1y - v4y * v1x) * v0z < 0
  98520. ) {
  98521. if (
  98522. (v4y * v2z - v4z * v2y) * v0x +
  98523. (v4z * v2x - v4x * v2z) * v0y +
  98524. (v4x * v2y - v4y * v2x) * v0z < 0
  98525. ) {
  98526. v1x = v4x;
  98527. v1y = v4y;
  98528. v1z = v4z;
  98529. v11x = v41x;
  98530. v11y = v41y;
  98531. v11z = v41z;
  98532. v12x = v42x;
  98533. v12y = v42y;
  98534. v12z = v42z;
  98535. } else {
  98536. v3x = v4x;
  98537. v3y = v4y;
  98538. v3z = v4z;
  98539. v31x = v41x;
  98540. v31y = v41y;
  98541. v31z = v41z;
  98542. v32x = v42x;
  98543. v32y = v42y;
  98544. v32z = v42z;
  98545. }
  98546. } else {
  98547. if (
  98548. (v4y * v3z - v4z * v3y) * v0x +
  98549. (v4z * v3x - v4x * v3z) * v0y +
  98550. (v4x * v3y - v4y * v3x) * v0z < 0
  98551. ) {
  98552. v2x = v4x;
  98553. v2y = v4y;
  98554. v2z = v4z;
  98555. v21x = v41x;
  98556. v21y = v41y;
  98557. v21z = v41z;
  98558. v22x = v42x;
  98559. v22y = v42y;
  98560. v22z = v42z;
  98561. } else {
  98562. v1x = v4x;
  98563. v1y = v4y;
  98564. v1z = v4z;
  98565. v11x = v41x;
  98566. v11y = v41y;
  98567. v11z = v41z;
  98568. v12x = v42x;
  98569. v12y = v42y;
  98570. v12z = v42z;
  98571. }
  98572. }
  98573. }
  98574. }
  98575. //return false;
  98576. };
  98577. OIMO.BoxCylinderCollisionDetector.prototype.supportPointB = function (c, dx, dy, dz, out) {
  98578. var rot = c.rotation.elements;
  98579. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  98580. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  98581. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  98582. var w = c.halfWidth;
  98583. var h = c.halfHeight;
  98584. var d = c.halfDepth;
  98585. var ox;
  98586. var oy;
  98587. var oz;
  98588. if (ldx < 0) ox = -w;
  98589. else ox = w;
  98590. if (ldy < 0) oy = -h;
  98591. else oy = h;
  98592. if (ldz < 0) oz = -d;
  98593. else oz = d;
  98594. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  98595. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  98596. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  98597. out.init(ldx, ldy, ldz);
  98598. };
  98599. OIMO.BoxCylinderCollisionDetector.prototype.supportPointC = function (c, dx, dy, dz, out) {
  98600. var rot = c.rotation.elements;
  98601. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  98602. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  98603. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  98604. var radx = ldx;
  98605. var radz = ldz;
  98606. var len = radx * radx + radz * radz;
  98607. var rad = c.radius;
  98608. var hh = c.halfHeight;
  98609. var ox;
  98610. var oy;
  98611. var oz;
  98612. if (len == 0) {
  98613. if (ldy < 0) {
  98614. ox = rad;
  98615. oy = -hh;
  98616. oz = 0;
  98617. } else {
  98618. ox = rad;
  98619. oy = hh;
  98620. oz = 0;
  98621. }
  98622. } else {
  98623. len = c.radius / OIMO.sqrt(len);
  98624. if (ldy < 0) {
  98625. ox = radx * len;
  98626. oy = -hh;
  98627. oz = radz * len;
  98628. } else {
  98629. ox = radx * len;
  98630. oy = hh;
  98631. oz = radz * len;
  98632. }
  98633. }
  98634. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  98635. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  98636. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  98637. out.init(ldx, ldy, ldz);
  98638. };
  98639. OIMO.BoxCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  98640. var b;
  98641. var c;
  98642. if (this.flip) {
  98643. b = shape2;
  98644. c = shape1;
  98645. } else {
  98646. b = shape1;
  98647. c = shape2;
  98648. }
  98649. var sep = new OIMO.Vec3();
  98650. var pos = new OIMO.Vec3();
  98651. var dep = new OIMO.Vec3();
  98652. var co;
  98653. if (!this.getSep(b, c, sep, pos, dep)) return;
  98654. var pbx = b.position.x;
  98655. var pby = b.position.y;
  98656. var pbz = b.position.z;
  98657. var pcx = c.position.x;
  98658. var pcy = c.position.y;
  98659. var pcz = c.position.z;
  98660. var bw = b.halfWidth;
  98661. var bh = b.halfHeight;
  98662. var bd = b.halfDepth;
  98663. var ch = c.halfHeight;
  98664. var r = c.radius;
  98665. var D = b.dimentions;
  98666. var nwx = D[0];//b.normalDirectionWidth.x;
  98667. var nwy = D[1];//b.normalDirectionWidth.y;
  98668. var nwz = D[2];//b.normalDirectionWidth.z;
  98669. var nhx = D[3];//b.normalDirectionHeight.x;
  98670. var nhy = D[4];//b.normalDirectionHeight.y;
  98671. var nhz = D[5];//b.normalDirectionHeight.z;
  98672. var ndx = D[6];//b.normalDirectionDepth.x;
  98673. var ndy = D[7];//b.normalDirectionDepth.y;
  98674. var ndz = D[8];//b.normalDirectionDepth.z;
  98675. var dwx = D[9];//b.halfDirectionWidth.x;
  98676. var dwy = D[10];//b.halfDirectionWidth.y;
  98677. var dwz = D[11];//b.halfDirectionWidth.z;
  98678. var dhx = D[12];//b.halfDirectionHeight.x;
  98679. var dhy = D[13];//b.halfDirectionHeight.y;
  98680. var dhz = D[14];//b.halfDirectionHeight.z;
  98681. var ddx = D[15];//b.halfDirectionDepth.x;
  98682. var ddy = D[16];//b.halfDirectionDepth.y;
  98683. var ddz = D[17];//b.halfDirectionDepth.z;
  98684. var ncx = c.normalDirection.x;
  98685. var ncy = c.normalDirection.y;
  98686. var ncz = c.normalDirection.z;
  98687. var dcx = c.halfDirection.x;
  98688. var dcy = c.halfDirection.y;
  98689. var dcz = c.halfDirection.z;
  98690. var nx = sep.x;
  98691. var ny = sep.y;
  98692. var nz = sep.z;
  98693. var dotw = nx * nwx + ny * nwy + nz * nwz;
  98694. var doth = nx * nhx + ny * nhy + nz * nhz;
  98695. var dotd = nx * ndx + ny * ndy + nz * ndz;
  98696. var dotc = nx * ncx + ny * ncy + nz * ncz;
  98697. var right1 = dotw > 0;
  98698. var right2 = doth > 0;
  98699. var right3 = dotd > 0;
  98700. var right4 = dotc > 0;
  98701. if (!right1) dotw = -dotw;
  98702. if (!right2) doth = -doth;
  98703. if (!right3) dotd = -dotd;
  98704. if (!right4) dotc = -dotc;
  98705. var state = 0;
  98706. if (dotc > 0.999) {
  98707. if (dotw > 0.999) {
  98708. if (dotw > dotc) state = 1;
  98709. else state = 4;
  98710. } else if (doth > 0.999) {
  98711. if (doth > dotc) state = 2;
  98712. else state = 4;
  98713. } else if (dotd > 0.999) {
  98714. if (dotd > dotc) state = 3;
  98715. else state = 4;
  98716. } else state = 4;
  98717. } else {
  98718. if (dotw > 0.999) state = 1;
  98719. else if (doth > 0.999) state = 2;
  98720. else if (dotd > 0.999) state = 3;
  98721. }
  98722. var cbx;
  98723. var cby;
  98724. var cbz;
  98725. var ccx;
  98726. var ccy;
  98727. var ccz;
  98728. var r00;
  98729. var r01;
  98730. var r02;
  98731. var r10;
  98732. var r11;
  98733. var r12;
  98734. var r20;
  98735. var r21;
  98736. var r22;
  98737. var px;
  98738. var py;
  98739. var pz;
  98740. var pd;
  98741. var dot;
  98742. var len;
  98743. var tx;
  98744. var ty;
  98745. var tz;
  98746. var td;
  98747. var dx;
  98748. var dy;
  98749. var dz;
  98750. var d1x;
  98751. var d1y;
  98752. var d1z;
  98753. var d2x;
  98754. var d2y;
  98755. var d2z;
  98756. var sx;
  98757. var sy;
  98758. var sz;
  98759. var sd;
  98760. var ex;
  98761. var ey;
  98762. var ez;
  98763. var ed;
  98764. var dot1;
  98765. var dot2;
  98766. var t1;
  98767. var t2;
  98768. var dir1x;
  98769. var dir1y;
  98770. var dir1z;
  98771. var dir2x;
  98772. var dir2y;
  98773. var dir2z;
  98774. var dir1l;
  98775. var dir2l;
  98776. if (state == 0) {
  98777. //manifold.addPoint(pos.x,pos.y,pos.z,nx,ny,nz,dep.x,b,c,0,0,false);
  98778. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, dep.x, this.flip);
  98779. } else if (state == 4) {
  98780. if (right4) {
  98781. ccx = pcx - dcx;
  98782. ccy = pcy - dcy;
  98783. ccz = pcz - dcz;
  98784. nx = -ncx;
  98785. ny = -ncy;
  98786. nz = -ncz;
  98787. } else {
  98788. ccx = pcx + dcx;
  98789. ccy = pcy + dcy;
  98790. ccz = pcz + dcz;
  98791. nx = ncx;
  98792. ny = ncy;
  98793. nz = ncz;
  98794. }
  98795. var v1x;
  98796. var v1y;
  98797. var v1z;
  98798. var v2x;
  98799. var v2y;
  98800. var v2z;
  98801. var v3x;
  98802. var v3y;
  98803. var v3z;
  98804. var v4x;
  98805. var v4y;
  98806. var v4z;
  98807. dot = 1;
  98808. state = 0;
  98809. dot1 = nwx * nx + nwy * ny + nwz * nz;
  98810. if (dot1 < dot) {
  98811. dot = dot1;
  98812. state = 0;
  98813. }
  98814. if (-dot1 < dot) {
  98815. dot = -dot1;
  98816. state = 1;
  98817. }
  98818. dot1 = nhx * nx + nhy * ny + nhz * nz;
  98819. if (dot1 < dot) {
  98820. dot = dot1;
  98821. state = 2;
  98822. }
  98823. if (-dot1 < dot) {
  98824. dot = -dot1;
  98825. state = 3;
  98826. }
  98827. dot1 = ndx * nx + ndy * ny + ndz * nz;
  98828. if (dot1 < dot) {
  98829. dot = dot1;
  98830. state = 4;
  98831. }
  98832. if (-dot1 < dot) {
  98833. dot = -dot1;
  98834. state = 5;
  98835. }
  98836. var v = b.elements;
  98837. switch (state) {
  98838. case 0:
  98839. //v=b.vertex1;
  98840. v1x = v[0];//v.x;
  98841. v1y = v[1];//v.y;
  98842. v1z = v[2];//v.z;
  98843. //v=b.vertex3;
  98844. v2x = v[6];//v.x;
  98845. v2y = v[7];//v.y;
  98846. v2z = v[8];//v.z;
  98847. //v=b.vertex4;
  98848. v3x = v[9];//v.x;
  98849. v3y = v[10];//v.y;
  98850. v3z = v[11];//v.z;
  98851. //v=b.vertex2;
  98852. v4x = v[3];//v.x;
  98853. v4y = v[4];//v.y;
  98854. v4z = v[5];//v.z;
  98855. break;
  98856. case 1:
  98857. //v=b.vertex6;
  98858. v1x = v[15];//v.x;
  98859. v1y = v[16];//v.y;
  98860. v1z = v[17];//v.z;
  98861. //v=b.vertex8;
  98862. v2x = v[21];//v.x;
  98863. v2y = v[22];//v.y;
  98864. v2z = v[23];//v.z;
  98865. //v=b.vertex7;
  98866. v3x = v[18];//v.x;
  98867. v3y = v[19];//v.y;
  98868. v3z = v[20];//v.z;
  98869. //v=b.vertex5;
  98870. v4x = v[12];//v.x;
  98871. v4y = v[13];//v.y;
  98872. v4z = v[14];//v.z;
  98873. break;
  98874. case 2:
  98875. //v=b.vertex5;
  98876. v1x = v[12];//v.x;
  98877. v1y = v[13];//v.y;
  98878. v1z = v[14];//v.z;
  98879. //v=b.vertex1;
  98880. v2x = v[0];//v.x;
  98881. v2y = v[1];//v.y;
  98882. v2z = v[2];//v.z;
  98883. //v=b.vertex2;
  98884. v3x = v[3];//v.x;
  98885. v3y = v[4];//v.y;
  98886. v3z = v[5];//v.z;
  98887. //v=b.vertex6;
  98888. v4x = v[15];//v.x;
  98889. v4y = v[16];//v.y;
  98890. v4z = v[17];//v.z;
  98891. break;
  98892. case 3:
  98893. //v=b.vertex8;
  98894. v1x = v[21];//v.x;
  98895. v1y = v[22];//v.y;
  98896. v1z = v[23];//v.z;
  98897. //v=b.vertex4;
  98898. v2x = v[9];//v.x;
  98899. v2y = v[10];//v.y;
  98900. v2z = v[11];//v.z;
  98901. //v=b.vertex3;
  98902. v3x = v[6];//v.x;
  98903. v3y = v[7];//v.y;
  98904. v3z = v[8];//v.z;
  98905. //v=b.vertex7;
  98906. v4x = v[18];//v.x;
  98907. v4y = v[19];//v.y;
  98908. v4z = v[20];//v.z;
  98909. break;
  98910. case 4:
  98911. //v=b.vertex5;
  98912. v1x = v[12];//v.x;
  98913. v1y = v[13];//v.y;
  98914. v1z = v[14];//v.z;
  98915. //v=b.vertex7;
  98916. v2x = v[18];//v.x;
  98917. v2y = v[19];//v.y;
  98918. v2z = v[20];//v.z;
  98919. //v=b.vertex3;
  98920. v3x = v[6];//v.x;
  98921. v3y = v[7];//v.y;
  98922. v3z = v[8];//v.z;
  98923. //v=b.vertex1;
  98924. v4x = v[0];//v.x;
  98925. v4y = v[1];//v.y;
  98926. v4z = v[2];//v.z;
  98927. break;
  98928. case 5:
  98929. //v=b.vertex2;
  98930. v1x = v[3];//v.x;
  98931. v1y = v[4];//v.y;
  98932. v1z = v[5];//v.z;
  98933. //v=b.vertex4;
  98934. v2x = v[9];//v.x;
  98935. v2y = v[10];//v.y;
  98936. v2z = v[11];//v.z;
  98937. //v=b.vertex8;
  98938. v3x = v[21];//v.x;
  98939. v3y = v[22];//v.y;
  98940. v3z = v[23];//v.z;
  98941. //v=b.vertex6;
  98942. v4x = v[15];//v.x;
  98943. v4y = v[16];//v.y;
  98944. v4z = v[17];//v.z;
  98945. break;
  98946. }
  98947. pd = nx * (v1x - ccx) + ny * (v1y - ccy) + nz * (v1z - ccz);
  98948. if (pd <= 0) manifold.addPoint(v1x, v1y, v1z, -nx, -ny, -nz, pd, this.flip);
  98949. pd = nx * (v2x - ccx) + ny * (v2y - ccy) + nz * (v2z - ccz);
  98950. if (pd <= 0) manifold.addPoint(v2x, v2y, v2z, -nx, -ny, -nz, pd, this.flip);
  98951. pd = nx * (v3x - ccx) + ny * (v3y - ccy) + nz * (v3z - ccz);
  98952. if (pd <= 0) manifold.addPoint(v3x, v3y, v3z, -nx, -ny, -nz, pd, this.flip);
  98953. pd = nx * (v4x - ccx) + ny * (v4y - ccy) + nz * (v4z - ccz);
  98954. if (pd <= 0) manifold.addPoint(v4x, v4y, v4z, -nx, -ny, -nz, pd, this.flip);
  98955. } else {
  98956. switch (state) {
  98957. case 1:
  98958. if (right1) {
  98959. cbx = pbx + dwx;
  98960. cby = pby + dwy;
  98961. cbz = pbz + dwz;
  98962. nx = nwx;
  98963. ny = nwy;
  98964. nz = nwz;
  98965. } else {
  98966. cbx = pbx - dwx;
  98967. cby = pby - dwy;
  98968. cbz = pbz - dwz;
  98969. nx = -nwx;
  98970. ny = -nwy;
  98971. nz = -nwz;
  98972. }
  98973. dir1x = nhx;
  98974. dir1y = nhy;
  98975. dir1z = nhz;
  98976. dir1l = bh;
  98977. dir2x = ndx;
  98978. dir2y = ndy;
  98979. dir2z = ndz;
  98980. dir2l = bd;
  98981. break;
  98982. case 2:
  98983. if (right2) {
  98984. cbx = pbx + dhx;
  98985. cby = pby + dhy;
  98986. cbz = pbz + dhz;
  98987. nx = nhx;
  98988. ny = nhy;
  98989. nz = nhz;
  98990. } else {
  98991. cbx = pbx - dhx;
  98992. cby = pby - dhy;
  98993. cbz = pbz - dhz;
  98994. nx = -nhx;
  98995. ny = -nhy;
  98996. nz = -nhz;
  98997. }
  98998. dir1x = nwx;
  98999. dir1y = nwy;
  99000. dir1z = nwz;
  99001. dir1l = bw;
  99002. dir2x = ndx;
  99003. dir2y = ndy;
  99004. dir2z = ndz;
  99005. dir2l = bd;
  99006. break;
  99007. case 3:
  99008. if (right3) {
  99009. cbx = pbx + ddx;
  99010. cby = pby + ddy;
  99011. cbz = pbz + ddz;
  99012. nx = ndx;
  99013. ny = ndy;
  99014. nz = ndz;
  99015. } else {
  99016. cbx = pbx - ddx;
  99017. cby = pby - ddy;
  99018. cbz = pbz - ddz;
  99019. nx = -ndx;
  99020. ny = -ndy;
  99021. nz = -ndz;
  99022. }
  99023. dir1x = nwx;
  99024. dir1y = nwy;
  99025. dir1z = nwz;
  99026. dir1l = bw;
  99027. dir2x = nhx;
  99028. dir2y = nhy;
  99029. dir2z = nhz;
  99030. dir2l = bh;
  99031. break;
  99032. }
  99033. dot = nx * ncx + ny * ncy + nz * ncz;
  99034. if (dot < 0) len = ch;
  99035. else len = -ch;
  99036. ccx = pcx + len * ncx;
  99037. ccy = pcy + len * ncy;
  99038. ccz = pcz + len * ncz;
  99039. if (dotc >= 0.999999) {
  99040. tx = -ny;
  99041. ty = nz;
  99042. tz = nx;
  99043. } else {
  99044. tx = nx;
  99045. ty = ny;
  99046. tz = nz;
  99047. }
  99048. len = tx * ncx + ty * ncy + tz * ncz;
  99049. dx = len * ncx - tx;
  99050. dy = len * ncy - ty;
  99051. dz = len * ncz - tz;
  99052. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  99053. if (len == 0) return;
  99054. len = r / len;
  99055. dx *= len;
  99056. dy *= len;
  99057. dz *= len;
  99058. tx = ccx + dx;
  99059. ty = ccy + dy;
  99060. tz = ccz + dz;
  99061. if (dot < -0.96 || dot > 0.96) {
  99062. r00 = ncx * ncx * 1.5 - 0.5;
  99063. r01 = ncx * ncy * 1.5 - ncz * 0.866025403;
  99064. r02 = ncx * ncz * 1.5 + ncy * 0.866025403;
  99065. r10 = ncy * ncx * 1.5 + ncz * 0.866025403;
  99066. r11 = ncy * ncy * 1.5 - 0.5;
  99067. r12 = ncy * ncz * 1.5 - ncx * 0.866025403;
  99068. r20 = ncz * ncx * 1.5 - ncy * 0.866025403;
  99069. r21 = ncz * ncy * 1.5 + ncx * 0.866025403;
  99070. r22 = ncz * ncz * 1.5 - 0.5;
  99071. px = tx;
  99072. py = ty;
  99073. pz = tz;
  99074. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  99075. tx = px - pd * nx - cbx;
  99076. ty = py - pd * ny - cby;
  99077. tz = pz - pd * nz - cbz;
  99078. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  99079. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  99080. if (sd < -dir1l) sd = -dir1l;
  99081. else if (sd > dir1l) sd = dir1l;
  99082. if (ed < -dir2l) ed = -dir2l;
  99083. else if (ed > dir2l) ed = dir2l;
  99084. tx = sd * dir1x + ed * dir2x;
  99085. ty = sd * dir1y + ed * dir2y;
  99086. tz = sd * dir1z + ed * dir2z;
  99087. px = cbx + tx;
  99088. py = cby + ty;
  99089. pz = cbz + tz;
  99090. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  99091. px = dx * r00 + dy * r01 + dz * r02;
  99092. py = dx * r10 + dy * r11 + dz * r12;
  99093. pz = dx * r20 + dy * r21 + dz * r22;
  99094. px = (dx = px) + ccx;
  99095. py = (dy = py) + ccy;
  99096. pz = (dz = pz) + ccz;
  99097. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  99098. if (pd <= 0) {
  99099. tx = px - pd * nx - cbx;
  99100. ty = py - pd * ny - cby;
  99101. tz = pz - pd * nz - cbz;
  99102. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  99103. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  99104. if (sd < -dir1l) sd = -dir1l;
  99105. else if (sd > dir1l) sd = dir1l;
  99106. if (ed < -dir2l) ed = -dir2l;
  99107. else if (ed > dir2l) ed = dir2l;
  99108. tx = sd * dir1x + ed * dir2x;
  99109. ty = sd * dir1y + ed * dir2y;
  99110. tz = sd * dir1z + ed * dir2z;
  99111. px = cbx + tx;
  99112. py = cby + ty;
  99113. pz = cbz + tz;
  99114. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,2,0,false);
  99115. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  99116. }
  99117. px = dx * r00 + dy * r01 + dz * r02;
  99118. py = dx * r10 + dy * r11 + dz * r12;
  99119. pz = dx * r20 + dy * r21 + dz * r22;
  99120. px = (dx = px) + ccx;
  99121. py = (dy = py) + ccy;
  99122. pz = (dz = pz) + ccz;
  99123. pd = nx * (px - cbx) + ny * (py - cby) + nz * (pz - cbz);
  99124. if (pd <= 0) {
  99125. tx = px - pd * nx - cbx;
  99126. ty = py - pd * ny - cby;
  99127. tz = pz - pd * nz - cbz;
  99128. sd = dir1x * tx + dir1y * ty + dir1z * tz;
  99129. ed = dir2x * tx + dir2y * ty + dir2z * tz;
  99130. if (sd < -dir1l) sd = -dir1l;
  99131. else if (sd > dir1l) sd = dir1l;
  99132. if (ed < -dir2l) ed = -dir2l;
  99133. else if (ed > dir2l) ed = dir2l;
  99134. tx = sd * dir1x + ed * dir2x;
  99135. ty = sd * dir1y + ed * dir2y;
  99136. tz = sd * dir1z + ed * dir2z;
  99137. px = cbx + tx;
  99138. py = cby + ty;
  99139. pz = cbz + tz;
  99140. //manifold.addPoint(px,py,pz,nx,ny,nz,pd,b,c,3,0,false);
  99141. manifold.addPoint(px, py, pz, nx, ny, nz, pd, this.flip);
  99142. }
  99143. } else {
  99144. sx = tx;
  99145. sy = ty;
  99146. sz = tz;
  99147. sd = nx * (sx - cbx) + ny * (sy - cby) + nz * (sz - cbz);
  99148. sx -= sd * nx;
  99149. sy -= sd * ny;
  99150. sz -= sd * nz;
  99151. if (dot > 0) {
  99152. ex = tx + dcx * 2;
  99153. ey = ty + dcy * 2;
  99154. ez = tz + dcz * 2;
  99155. } else {
  99156. ex = tx - dcx * 2;
  99157. ey = ty - dcy * 2;
  99158. ez = tz - dcz * 2;
  99159. }
  99160. ed = nx * (ex - cbx) + ny * (ey - cby) + nz * (ez - cbz);
  99161. ex -= ed * nx;
  99162. ey -= ed * ny;
  99163. ez -= ed * nz;
  99164. d1x = sx - cbx;
  99165. d1y = sy - cby;
  99166. d1z = sz - cbz;
  99167. d2x = ex - cbx;
  99168. d2y = ey - cby;
  99169. d2z = ez - cbz;
  99170. tx = ex - sx;
  99171. ty = ey - sy;
  99172. tz = ez - sz;
  99173. td = ed - sd;
  99174. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  99175. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  99176. dot1 = dotw - dir1l;
  99177. dot2 = doth - dir1l;
  99178. if (dot1 > 0) {
  99179. if (dot2 > 0) return;
  99180. t1 = dot1 / (dot1 - dot2);
  99181. sx = sx + tx * t1;
  99182. sy = sy + ty * t1;
  99183. sz = sz + tz * t1;
  99184. sd = sd + td * t1;
  99185. d1x = sx - cbx;
  99186. d1y = sy - cby;
  99187. d1z = sz - cbz;
  99188. dotw = d1x * dir1x + d1y * dir1y + d1z * dir1z;
  99189. tx = ex - sx;
  99190. ty = ey - sy;
  99191. tz = ez - sz;
  99192. td = ed - sd;
  99193. } else if (dot2 > 0) {
  99194. t1 = dot1 / (dot1 - dot2);
  99195. ex = sx + tx * t1;
  99196. ey = sy + ty * t1;
  99197. ez = sz + tz * t1;
  99198. ed = sd + td * t1;
  99199. d2x = ex - cbx;
  99200. d2y = ey - cby;
  99201. d2z = ez - cbz;
  99202. doth = d2x * dir1x + d2y * dir1y + d2z * dir1z;
  99203. tx = ex - sx;
  99204. ty = ey - sy;
  99205. tz = ez - sz;
  99206. td = ed - sd;
  99207. }
  99208. dot1 = dotw + dir1l;
  99209. dot2 = doth + dir1l;
  99210. if (dot1 < 0) {
  99211. if (dot2 < 0) return;
  99212. t1 = dot1 / (dot1 - dot2);
  99213. sx = sx + tx * t1;
  99214. sy = sy + ty * t1;
  99215. sz = sz + tz * t1;
  99216. sd = sd + td * t1;
  99217. d1x = sx - cbx;
  99218. d1y = sy - cby;
  99219. d1z = sz - cbz;
  99220. tx = ex - sx;
  99221. ty = ey - sy;
  99222. tz = ez - sz;
  99223. td = ed - sd;
  99224. } else if (dot2 < 0) {
  99225. t1 = dot1 / (dot1 - dot2);
  99226. ex = sx + tx * t1;
  99227. ey = sy + ty * t1;
  99228. ez = sz + tz * t1;
  99229. ed = sd + td * t1;
  99230. d2x = ex - cbx;
  99231. d2y = ey - cby;
  99232. d2z = ez - cbz;
  99233. tx = ex - sx;
  99234. ty = ey - sy;
  99235. tz = ez - sz;
  99236. td = ed - sd;
  99237. }
  99238. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  99239. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  99240. dot1 = dotw - dir2l;
  99241. dot2 = doth - dir2l;
  99242. if (dot1 > 0) {
  99243. if (dot2 > 0) return;
  99244. t1 = dot1 / (dot1 - dot2);
  99245. sx = sx + tx * t1;
  99246. sy = sy + ty * t1;
  99247. sz = sz + tz * t1;
  99248. sd = sd + td * t1;
  99249. d1x = sx - cbx;
  99250. d1y = sy - cby;
  99251. d1z = sz - cbz;
  99252. dotw = d1x * dir2x + d1y * dir2y + d1z * dir2z;
  99253. tx = ex - sx;
  99254. ty = ey - sy;
  99255. tz = ez - sz;
  99256. td = ed - sd;
  99257. } else if (dot2 > 0) {
  99258. t1 = dot1 / (dot1 - dot2);
  99259. ex = sx + tx * t1;
  99260. ey = sy + ty * t1;
  99261. ez = sz + tz * t1;
  99262. ed = sd + td * t1;
  99263. d2x = ex - cbx;
  99264. d2y = ey - cby;
  99265. d2z = ez - cbz;
  99266. doth = d2x * dir2x + d2y * dir2y + d2z * dir2z;
  99267. tx = ex - sx;
  99268. ty = ey - sy;
  99269. tz = ez - sz;
  99270. td = ed - sd;
  99271. }
  99272. dot1 = dotw + dir2l;
  99273. dot2 = doth + dir2l;
  99274. if (dot1 < 0) {
  99275. if (dot2 < 0) return;
  99276. t1 = dot1 / (dot1 - dot2);
  99277. sx = sx + tx * t1;
  99278. sy = sy + ty * t1;
  99279. sz = sz + tz * t1;
  99280. sd = sd + td * t1;
  99281. } else if (dot2 < 0) {
  99282. t1 = dot1 / (dot1 - dot2);
  99283. ex = sx + tx * t1;
  99284. ey = sy + ty * t1;
  99285. ez = sz + tz * t1;
  99286. ed = sd + td * t1;
  99287. }
  99288. if (sd < 0) {
  99289. //manifold.addPoint(sx,sy,sz,nx,ny,nz,sd,b,c,1,0,false);
  99290. manifold.addPoint(sx, sy, sz, nx, ny, nz, sd, this.flip);
  99291. }
  99292. if (ed < 0) {
  99293. //manifold.addPoint(ex,ey,ez,nx,ny,nz,ed,b,c,4,0,false);
  99294. manifold.addPoint(ex, ey, ez, nx, ny, nz, ed, this.flip);
  99295. }
  99296. }
  99297. }
  99298. };
  99299. OIMO.CylinderCylinderCollisionDetector = function () {
  99300. OIMO.CollisionDetector.call(this);
  99301. };
  99302. OIMO.CylinderCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  99303. OIMO.CylinderCylinderCollisionDetector.prototype.constructor = OIMO.CylinderCylinderCollisionDetector;
  99304. OIMO.CylinderCylinderCollisionDetector.prototype.getSep = function (c1, c2, sep, pos, dep) {
  99305. var t1x;
  99306. var t1y;
  99307. var t1z;
  99308. var t2x;
  99309. var t2y;
  99310. var t2z;
  99311. var sup = new OIMO.Vec3();
  99312. var len;
  99313. var p1x;
  99314. var p1y;
  99315. var p1z;
  99316. var p2x;
  99317. var p2y;
  99318. var p2z;
  99319. var v01x = c1.position.x;
  99320. var v01y = c1.position.y;
  99321. var v01z = c1.position.z;
  99322. var v02x = c2.position.x;
  99323. var v02y = c2.position.y;
  99324. var v02z = c2.position.z;
  99325. var v0x = v02x - v01x;
  99326. var v0y = v02y - v01y;
  99327. var v0z = v02z - v01z;
  99328. if (v0x * v0x + v0y * v0y + v0z * v0z == 0) v0y = 0.001;
  99329. var nx = -v0x;
  99330. var ny = -v0y;
  99331. var nz = -v0z;
  99332. this.supportPoint(c1, -nx, -ny, -nz, sup);
  99333. var v11x = sup.x;
  99334. var v11y = sup.y;
  99335. var v11z = sup.z;
  99336. this.supportPoint(c2, nx, ny, nz, sup);
  99337. var v12x = sup.x;
  99338. var v12y = sup.y;
  99339. var v12z = sup.z;
  99340. var v1x = v12x - v11x;
  99341. var v1y = v12y - v11y;
  99342. var v1z = v12z - v11z;
  99343. if (v1x * nx + v1y * ny + v1z * nz <= 0) {
  99344. return false;
  99345. }
  99346. nx = v1y * v0z - v1z * v0y;
  99347. ny = v1z * v0x - v1x * v0z;
  99348. nz = v1x * v0y - v1y * v0x;
  99349. if (nx * nx + ny * ny + nz * nz == 0) {
  99350. sep.init(v1x - v0x, v1y - v0y, v1z - v0z);
  99351. sep.normalize(sep);
  99352. pos.init((v11x + v12x) * 0.5, (v11y + v12y) * 0.5, (v11z + v12z) * 0.5);
  99353. return true;
  99354. }
  99355. this.supportPoint(c1, -nx, -ny, -nz, sup);
  99356. var v21x = sup.x;
  99357. var v21y = sup.y;
  99358. var v21z = sup.z;
  99359. this.supportPoint(c2, nx, ny, nz, sup);
  99360. var v22x = sup.x;
  99361. var v22y = sup.y;
  99362. var v22z = sup.z;
  99363. var v2x = v22x - v21x;
  99364. var v2y = v22y - v21y;
  99365. var v2z = v22z - v21z;
  99366. if (v2x * nx + v2y * ny + v2z * nz <= 0) {
  99367. return false;
  99368. }
  99369. t1x = v1x - v0x;
  99370. t1y = v1y - v0y;
  99371. t1z = v1z - v0z;
  99372. t2x = v2x - v0x;
  99373. t2y = v2y - v0y;
  99374. t2z = v2z - v0z;
  99375. nx = t1y * t2z - t1z * t2y;
  99376. ny = t1z * t2x - t1x * t2z;
  99377. nz = t1x * t2y - t1y * t2x;
  99378. if (nx * v0x + ny * v0y + nz * v0z > 0) {
  99379. t1x = v1x;
  99380. t1y = v1y;
  99381. t1z = v1z;
  99382. v1x = v2x;
  99383. v1y = v2y;
  99384. v1z = v2z;
  99385. v2x = t1x;
  99386. v2y = t1y;
  99387. v2z = t1z;
  99388. t1x = v11x;
  99389. t1y = v11y;
  99390. t1z = v11z;
  99391. v11x = v21x;
  99392. v11y = v21y;
  99393. v11z = v21z;
  99394. v21x = t1x;
  99395. v21y = t1y;
  99396. v21z = t1z;
  99397. t1x = v12x;
  99398. t1y = v12y;
  99399. t1z = v12z;
  99400. v12x = v22x;
  99401. v12y = v22y;
  99402. v12z = v22z;
  99403. v22x = t1x;
  99404. v22y = t1y;
  99405. v22z = t1z;
  99406. nx = -nx;
  99407. ny = -ny;
  99408. nz = -nz;
  99409. }
  99410. var iterations = 0;
  99411. while (true) {
  99412. if (++iterations > 100) {
  99413. return false;
  99414. }
  99415. this.supportPoint(c1, -nx, -ny, -nz, sup);
  99416. var v31x = sup.x;
  99417. var v31y = sup.y;
  99418. var v31z = sup.z;
  99419. this.supportPoint(c2, nx, ny, nz, sup);
  99420. var v32x = sup.x;
  99421. var v32y = sup.y;
  99422. var v32z = sup.z;
  99423. var v3x = v32x - v31x;
  99424. var v3y = v32y - v31y;
  99425. var v3z = v32z - v31z;
  99426. if (v3x * nx + v3y * ny + v3z * nz <= 0) {
  99427. return false;
  99428. }
  99429. if ((v1y * v3z - v1z * v3y) * v0x + (v1z * v3x - v1x * v3z) * v0y + (v1x * v3y - v1y * v3x) * v0z < 0) {
  99430. v2x = v3x;
  99431. v2y = v3y;
  99432. v2z = v3z;
  99433. v21x = v31x;
  99434. v21y = v31y;
  99435. v21z = v31z;
  99436. v22x = v32x;
  99437. v22y = v32y;
  99438. v22z = v32z;
  99439. t1x = v1x - v0x;
  99440. t1y = v1y - v0y;
  99441. t1z = v1z - v0z;
  99442. t2x = v3x - v0x;
  99443. t2y = v3y - v0y;
  99444. t2z = v3z - v0z;
  99445. nx = t1y * t2z - t1z * t2y;
  99446. ny = t1z * t2x - t1x * t2z;
  99447. nz = t1x * t2y - t1y * t2x;
  99448. continue;
  99449. }
  99450. if ((v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z < 0) {
  99451. v1x = v3x;
  99452. v1y = v3y;
  99453. v1z = v3z;
  99454. v11x = v31x;
  99455. v11y = v31y;
  99456. v11z = v31z;
  99457. v12x = v32x;
  99458. v12y = v32y;
  99459. v12z = v32z;
  99460. t1x = v3x - v0x;
  99461. t1y = v3y - v0y;
  99462. t1z = v3z - v0z;
  99463. t2x = v2x - v0x;
  99464. t2y = v2y - v0y;
  99465. t2z = v2z - v0z;
  99466. nx = t1y * t2z - t1z * t2y;
  99467. ny = t1z * t2x - t1x * t2z;
  99468. nz = t1x * t2y - t1y * t2x;
  99469. continue;
  99470. }
  99471. var hit = false;
  99472. while (true) {
  99473. t1x = v2x - v1x;
  99474. t1y = v2y - v1y;
  99475. t1z = v2z - v1z;
  99476. t2x = v3x - v1x;
  99477. t2y = v3y - v1y;
  99478. t2z = v3z - v1z;
  99479. nx = t1y * t2z - t1z * t2y;
  99480. ny = t1z * t2x - t1x * t2z;
  99481. nz = t1x * t2y - t1y * t2x;
  99482. len = 1 / OIMO.sqrt(nx * nx + ny * ny + nz * nz);
  99483. nx *= len;
  99484. ny *= len;
  99485. nz *= len;
  99486. if (nx * v1x + ny * v1y + nz * v1z >= 0 && !hit) {
  99487. var b0 = (v1y * v2z - v1z * v2y) * v3x + (v1z * v2x - v1x * v2z) * v3y + (v1x * v2y - v1y * v2x) * v3z;
  99488. var b1 = (v3y * v2z - v3z * v2y) * v0x + (v3z * v2x - v3x * v2z) * v0y + (v3x * v2y - v3y * v2x) * v0z;
  99489. var b2 = (v0y * v1z - v0z * v1y) * v3x + (v0z * v1x - v0x * v1z) * v3y + (v0x * v1y - v0y * v1x) * v3z;
  99490. var b3 = (v2y * v1z - v2z * v1y) * v0x + (v2z * v1x - v2x * v1z) * v0y + (v2x * v1y - v2y * v1x) * v0z;
  99491. var sum = b0 + b1 + b2 + b3;
  99492. if (sum <= 0) {
  99493. b0 = 0;
  99494. b1 = (v2y * v3z - v2z * v3y) * nx + (v2z * v3x - v2x * v3z) * ny + (v2x * v3y - v2y * v3x) * nz;
  99495. b2 = (v3y * v2z - v3z * v2y) * nx + (v3z * v2x - v3x * v2z) * ny + (v3x * v2y - v3y * v2x) * nz;
  99496. b3 = (v1y * v2z - v1z * v2y) * nx + (v1z * v2x - v1x * v2z) * ny + (v1x * v2y - v1y * v2x) * nz;
  99497. sum = b1 + b2 + b3;
  99498. }
  99499. var inv = 1 / sum;
  99500. p1x = (v01x * b0 + v11x * b1 + v21x * b2 + v31x * b3) * inv;
  99501. p1y = (v01y * b0 + v11y * b1 + v21y * b2 + v31y * b3) * inv;
  99502. p1z = (v01z * b0 + v11z * b1 + v21z * b2 + v31z * b3) * inv;
  99503. p2x = (v02x * b0 + v12x * b1 + v22x * b2 + v32x * b3) * inv;
  99504. p2y = (v02y * b0 + v12y * b1 + v22y * b2 + v32y * b3) * inv;
  99505. p2z = (v02z * b0 + v12z * b1 + v22z * b2 + v32z * b3) * inv;
  99506. hit = true;
  99507. }
  99508. this.supportPoint(c1, -nx, -ny, -nz, sup);
  99509. var v41x = sup.x;
  99510. var v41y = sup.y;
  99511. var v41z = sup.z;
  99512. this.supportPoint(c2, nx, ny, nz, sup);
  99513. var v42x = sup.x;
  99514. var v42y = sup.y;
  99515. var v42z = sup.z;
  99516. var v4x = v42x - v41x;
  99517. var v4y = v42y - v41y;
  99518. var v4z = v42z - v41z;
  99519. var separation = -(v4x * nx + v4y * ny + v4z * nz);
  99520. if ((v4x - v3x) * nx + (v4y - v3y) * ny + (v4z - v3z) * nz <= 0.01 || separation >= 0) {
  99521. if (hit) {
  99522. sep.init(-nx, -ny, -nz);
  99523. pos.init((p1x + p2x) * 0.5, (p1y + p2y) * 0.5, (p1z + p2z) * 0.5);
  99524. dep.x = separation;
  99525. return true;
  99526. }
  99527. return false;
  99528. }
  99529. if (
  99530. (v4y * v1z - v4z * v1y) * v0x +
  99531. (v4z * v1x - v4x * v1z) * v0y +
  99532. (v4x * v1y - v4y * v1x) * v0z < 0
  99533. ) {
  99534. if (
  99535. (v4y * v2z - v4z * v2y) * v0x +
  99536. (v4z * v2x - v4x * v2z) * v0y +
  99537. (v4x * v2y - v4y * v2x) * v0z < 0
  99538. ) {
  99539. v1x = v4x;
  99540. v1y = v4y;
  99541. v1z = v4z;
  99542. v11x = v41x;
  99543. v11y = v41y;
  99544. v11z = v41z;
  99545. v12x = v42x;
  99546. v12y = v42y;
  99547. v12z = v42z;
  99548. } else {
  99549. v3x = v4x;
  99550. v3y = v4y;
  99551. v3z = v4z;
  99552. v31x = v41x;
  99553. v31y = v41y;
  99554. v31z = v41z;
  99555. v32x = v42x;
  99556. v32y = v42y;
  99557. v32z = v42z;
  99558. }
  99559. } else {
  99560. if (
  99561. (v4y * v3z - v4z * v3y) * v0x +
  99562. (v4z * v3x - v4x * v3z) * v0y +
  99563. (v4x * v3y - v4y * v3x) * v0z < 0
  99564. ) {
  99565. v2x = v4x;
  99566. v2y = v4y;
  99567. v2z = v4z;
  99568. v21x = v41x;
  99569. v21y = v41y;
  99570. v21z = v41z;
  99571. v22x = v42x;
  99572. v22y = v42y;
  99573. v22z = v42z;
  99574. } else {
  99575. v1x = v4x;
  99576. v1y = v4y;
  99577. v1z = v4z;
  99578. v11x = v41x;
  99579. v11y = v41y;
  99580. v11z = v41z;
  99581. v12x = v42x;
  99582. v12y = v42y;
  99583. v12z = v42z;
  99584. }
  99585. }
  99586. }
  99587. }
  99588. //return false;
  99589. };
  99590. OIMO.CylinderCylinderCollisionDetector.prototype.supportPoint = function (c, dx, dy, dz, out) {
  99591. var rot = c.rotation.elements;
  99592. var ldx = rot[0] * dx + rot[3] * dy + rot[6] * dz;
  99593. var ldy = rot[1] * dx + rot[4] * dy + rot[7] * dz;
  99594. var ldz = rot[2] * dx + rot[5] * dy + rot[8] * dz;
  99595. var radx = ldx;
  99596. var radz = ldz;
  99597. var len = radx * radx + radz * radz;
  99598. var rad = c.radius;
  99599. var hh = c.halfHeight;
  99600. var ox;
  99601. var oy;
  99602. var oz;
  99603. if (len == 0) {
  99604. if (ldy < 0) {
  99605. ox = rad;
  99606. oy = -hh;
  99607. oz = 0;
  99608. } else {
  99609. ox = rad;
  99610. oy = hh;
  99611. oz = 0;
  99612. }
  99613. } else {
  99614. len = c.radius / OIMO.sqrt(len);
  99615. if (ldy < 0) {
  99616. ox = radx * len;
  99617. oy = -hh;
  99618. oz = radz * len;
  99619. } else {
  99620. ox = radx * len;
  99621. oy = hh;
  99622. oz = radz * len;
  99623. }
  99624. }
  99625. ldx = rot[0] * ox + rot[1] * oy + rot[2] * oz + c.position.x;
  99626. ldy = rot[3] * ox + rot[4] * oy + rot[5] * oz + c.position.y;
  99627. ldz = rot[6] * ox + rot[7] * oy + rot[8] * oz + c.position.z;
  99628. out.init(ldx, ldy, ldz);
  99629. };
  99630. OIMO.CylinderCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  99631. var c1;
  99632. var c2;
  99633. if (shape1.id < shape2.id) {
  99634. c1 = shape1;
  99635. c2 = shape2;
  99636. } else {
  99637. c1 = shape2;
  99638. c2 = shape1;
  99639. }
  99640. var p1 = c1.position;
  99641. var p2 = c2.position;
  99642. var p1x = p1.x;
  99643. var p1y = p1.y;
  99644. var p1z = p1.z;
  99645. var p2x = p2.x;
  99646. var p2y = p2.y;
  99647. var p2z = p2.z;
  99648. var h1 = c1.halfHeight;
  99649. var h2 = c2.halfHeight;
  99650. var n1 = c1.normalDirection;
  99651. var n2 = c2.normalDirection;
  99652. var d1 = c1.halfDirection;
  99653. var d2 = c2.halfDirection;
  99654. var r1 = c1.radius;
  99655. var r2 = c2.radius;
  99656. var n1x = n1.x;
  99657. var n1y = n1.y;
  99658. var n1z = n1.z;
  99659. var n2x = n2.x;
  99660. var n2y = n2.y;
  99661. var n2z = n2.z;
  99662. var d1x = d1.x;
  99663. var d1y = d1.y;
  99664. var d1z = d1.z;
  99665. var d2x = d2.x;
  99666. var d2y = d2.y;
  99667. var d2z = d2.z;
  99668. var dx = p1x - p2x;
  99669. var dy = p1y - p2y;
  99670. var dz = p1z - p2z;
  99671. var len;
  99672. var len1;
  99673. var len2;
  99674. var c;
  99675. var c1x;
  99676. var c1y;
  99677. var c1z;
  99678. var c2x;
  99679. var c2y;
  99680. var c2z;
  99681. var tx;
  99682. var ty;
  99683. var tz;
  99684. var sx;
  99685. var sy;
  99686. var sz;
  99687. var ex;
  99688. var ey;
  99689. var ez;
  99690. var depth1;
  99691. var depth2;
  99692. var dot;
  99693. var t1;
  99694. var t2;
  99695. var sep = new OIMO.Vec3();
  99696. var pos = new OIMO.Vec3();
  99697. var dep = new OIMO.Vec3();
  99698. if (!this.getSep(c1, c2, sep, pos, dep)) return;
  99699. var dot1 = sep.x * n1x + sep.y * n1y + sep.z * n1z;
  99700. var dot2 = sep.x * n2x + sep.y * n2y + sep.z * n2z;
  99701. var right1 = dot1 > 0;
  99702. var right2 = dot2 > 0;
  99703. if (!right1) dot1 = -dot1;
  99704. if (!right2) dot2 = -dot2;
  99705. var state = 0;
  99706. if (dot1 > 0.999 || dot2 > 0.999) {
  99707. if (dot1 > dot2) state = 1;
  99708. else state = 2;
  99709. }
  99710. var nx;
  99711. var ny;
  99712. var nz;
  99713. var depth = dep.x;
  99714. var r00;
  99715. var r01;
  99716. var r02;
  99717. var r10;
  99718. var r11;
  99719. var r12;
  99720. var r20;
  99721. var r21;
  99722. var r22;
  99723. var px;
  99724. var py;
  99725. var pz;
  99726. var pd;
  99727. var a;
  99728. var b;
  99729. var e;
  99730. var f;
  99731. nx = sep.x;
  99732. ny = sep.y;
  99733. nz = sep.z;
  99734. switch (state) {
  99735. case 0:
  99736. manifold.addPoint(pos.x, pos.y, pos.z, nx, ny, nz, depth, false);
  99737. break;
  99738. case 1:
  99739. if (right1) {
  99740. c1x = p1x + d1x;
  99741. c1y = p1y + d1y;
  99742. c1z = p1z + d1z;
  99743. nx = n1x;
  99744. ny = n1y;
  99745. nz = n1z;
  99746. } else {
  99747. c1x = p1x - d1x;
  99748. c1y = p1y - d1y;
  99749. c1z = p1z - d1z;
  99750. nx = -n1x;
  99751. ny = -n1y;
  99752. nz = -n1z;
  99753. }
  99754. dot = nx * n2x + ny * n2y + nz * n2z;
  99755. if (dot < 0) len = h2;
  99756. else len = -h2;
  99757. c2x = p2x + len * n2x;
  99758. c2y = p2y + len * n2y;
  99759. c2z = p2z + len * n2z;
  99760. if (dot2 >= 0.999999) {
  99761. tx = -ny;
  99762. ty = nz;
  99763. tz = nx;
  99764. } else {
  99765. tx = nx;
  99766. ty = ny;
  99767. tz = nz;
  99768. }
  99769. len = tx * n2x + ty * n2y + tz * n2z;
  99770. dx = len * n2x - tx;
  99771. dy = len * n2y - ty;
  99772. dz = len * n2z - tz;
  99773. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  99774. if (len == 0) break;
  99775. len = r2 / len;
  99776. dx *= len;
  99777. dy *= len;
  99778. dz *= len;
  99779. tx = c2x + dx;
  99780. ty = c2y + dy;
  99781. tz = c2z + dz;
  99782. if (dot < -0.96 || dot > 0.96) {
  99783. r00 = n2x * n2x * 1.5 - 0.5;
  99784. r01 = n2x * n2y * 1.5 - n2z * 0.866025403;
  99785. r02 = n2x * n2z * 1.5 + n2y * 0.866025403;
  99786. r10 = n2y * n2x * 1.5 + n2z * 0.866025403;
  99787. r11 = n2y * n2y * 1.5 - 0.5;
  99788. r12 = n2y * n2z * 1.5 - n2x * 0.866025403;
  99789. r20 = n2z * n2x * 1.5 - n2y * 0.866025403;
  99790. r21 = n2z * n2y * 1.5 + n2x * 0.866025403;
  99791. r22 = n2z * n2z * 1.5 - 0.5;
  99792. px = tx;
  99793. py = ty;
  99794. pz = tz;
  99795. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99796. tx = px - pd * nx - c1x;
  99797. ty = py - pd * ny - c1y;
  99798. tz = pz - pd * nz - c1z;
  99799. len = tx * tx + ty * ty + tz * tz;
  99800. if (len > r1 * r1) {
  99801. len = r1 / OIMO.sqrt(len);
  99802. tx *= len;
  99803. ty *= len;
  99804. tz *= len;
  99805. }
  99806. px = c1x + tx;
  99807. py = c1y + ty;
  99808. pz = c1z + tz;
  99809. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99810. px = dx * r00 + dy * r01 + dz * r02;
  99811. py = dx * r10 + dy * r11 + dz * r12;
  99812. pz = dx * r20 + dy * r21 + dz * r22;
  99813. px = (dx = px) + c2x;
  99814. py = (dy = py) + c2y;
  99815. pz = (dz = pz) + c2z;
  99816. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99817. if (pd <= 0) {
  99818. tx = px - pd * nx - c1x;
  99819. ty = py - pd * ny - c1y;
  99820. tz = pz - pd * nz - c1z;
  99821. len = tx * tx + ty * ty + tz * tz;
  99822. if (len > r1 * r1) {
  99823. len = r1 / OIMO.sqrt(len);
  99824. tx *= len;
  99825. ty *= len;
  99826. tz *= len;
  99827. }
  99828. px = c1x + tx;
  99829. py = c1y + ty;
  99830. pz = c1z + tz;
  99831. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99832. }
  99833. px = dx * r00 + dy * r01 + dz * r02;
  99834. py = dx * r10 + dy * r11 + dz * r12;
  99835. pz = dx * r20 + dy * r21 + dz * r22;
  99836. px = (dx = px) + c2x;
  99837. py = (dy = py) + c2y;
  99838. pz = (dz = pz) + c2z;
  99839. pd = nx * (px - c1x) + ny * (py - c1y) + nz * (pz - c1z);
  99840. if (pd <= 0) {
  99841. tx = px - pd * nx - c1x;
  99842. ty = py - pd * ny - c1y;
  99843. tz = pz - pd * nz - c1z;
  99844. len = tx * tx + ty * ty + tz * tz;
  99845. if (len > r1 * r1) {
  99846. len = r1 / OIMO.sqrt(len);
  99847. tx *= len;
  99848. ty *= len;
  99849. tz *= len;
  99850. }
  99851. px = c1x + tx;
  99852. py = c1y + ty;
  99853. pz = c1z + tz;
  99854. manifold.addPoint(px, py, pz, nx, ny, nz, pd, false);
  99855. }
  99856. } else {
  99857. sx = tx;
  99858. sy = ty;
  99859. sz = tz;
  99860. depth1 = nx * (sx - c1x) + ny * (sy - c1y) + nz * (sz - c1z);
  99861. sx -= depth1 * nx;
  99862. sy -= depth1 * ny;
  99863. sz -= depth1 * nz;
  99864. if (dot > 0) {
  99865. ex = tx + n2x * h2 * 2;
  99866. ey = ty + n2y * h2 * 2;
  99867. ez = tz + n2z * h2 * 2;
  99868. } else {
  99869. ex = tx - n2x * h2 * 2;
  99870. ey = ty - n2y * h2 * 2;
  99871. ez = tz - n2z * h2 * 2;
  99872. }
  99873. depth2 = nx * (ex - c1x) + ny * (ey - c1y) + nz * (ez - c1z);
  99874. ex -= depth2 * nx;
  99875. ey -= depth2 * ny;
  99876. ez -= depth2 * nz;
  99877. dx = c1x - sx;
  99878. dy = c1y - sy;
  99879. dz = c1z - sz;
  99880. tx = ex - sx;
  99881. ty = ey - sy;
  99882. tz = ez - sz;
  99883. a = dx * dx + dy * dy + dz * dz;
  99884. b = dx * tx + dy * ty + dz * tz;
  99885. e = tx * tx + ty * ty + tz * tz;
  99886. f = b * b - e * (a - r1 * r1);
  99887. if (f < 0) break;
  99888. f = OIMO.sqrt(f);
  99889. t1 = (b + f) / e;
  99890. t2 = (b - f) / e;
  99891. if (t2 < t1) {
  99892. len = t1;
  99893. t1 = t2;
  99894. t2 = len;
  99895. }
  99896. if (t2 > 1) t2 = 1;
  99897. if (t1 < 0) t1 = 0;
  99898. tx = sx + (ex - sx) * t1;
  99899. ty = sy + (ey - sy) * t1;
  99900. tz = sz + (ez - sz) * t1;
  99901. ex = sx + (ex - sx) * t2;
  99902. ey = sy + (ey - sy) * t2;
  99903. ez = sz + (ez - sz) * t2;
  99904. sx = tx;
  99905. sy = ty;
  99906. sz = tz;
  99907. len = depth1 + (depth2 - depth1) * t1;
  99908. depth2 = depth1 + (depth2 - depth1) * t2;
  99909. depth1 = len;
  99910. if (depth1 < 0) manifold.addPoint(sx, sy, sz, nx, ny, nz, pd, false);
  99911. if (depth2 < 0) manifold.addPoint(ex, ey, ez, nx, ny, nz, pd, false);
  99912. }
  99913. break;
  99914. case 2:
  99915. if (right2) {
  99916. c2x = p2x - d2x;
  99917. c2y = p2y - d2y;
  99918. c2z = p2z - d2z;
  99919. nx = -n2x;
  99920. ny = -n2y;
  99921. nz = -n2z;
  99922. } else {
  99923. c2x = p2x + d2x;
  99924. c2y = p2y + d2y;
  99925. c2z = p2z + d2z;
  99926. nx = n2x;
  99927. ny = n2y;
  99928. nz = n2z;
  99929. }
  99930. dot = nx * n1x + ny * n1y + nz * n1z;
  99931. if (dot < 0) len = h1;
  99932. else len = -h1;
  99933. c1x = p1x + len * n1x;
  99934. c1y = p1y + len * n1y;
  99935. c1z = p1z + len * n1z;
  99936. if (dot1 >= 0.999999) {
  99937. tx = -ny;
  99938. ty = nz;
  99939. tz = nx;
  99940. } else {
  99941. tx = nx;
  99942. ty = ny;
  99943. tz = nz;
  99944. }
  99945. len = tx * n1x + ty * n1y + tz * n1z;
  99946. dx = len * n1x - tx;
  99947. dy = len * n1y - ty;
  99948. dz = len * n1z - tz;
  99949. len = OIMO.sqrt(dx * dx + dy * dy + dz * dz);
  99950. if (len == 0) break;
  99951. len = r1 / len;
  99952. dx *= len;
  99953. dy *= len;
  99954. dz *= len;
  99955. tx = c1x + dx;
  99956. ty = c1y + dy;
  99957. tz = c1z + dz;
  99958. if (dot < -0.96 || dot > 0.96) {
  99959. r00 = n1x * n1x * 1.5 - 0.5;
  99960. r01 = n1x * n1y * 1.5 - n1z * 0.866025403;
  99961. r02 = n1x * n1z * 1.5 + n1y * 0.866025403;
  99962. r10 = n1y * n1x * 1.5 + n1z * 0.866025403;
  99963. r11 = n1y * n1y * 1.5 - 0.5;
  99964. r12 = n1y * n1z * 1.5 - n1x * 0.866025403;
  99965. r20 = n1z * n1x * 1.5 - n1y * 0.866025403;
  99966. r21 = n1z * n1y * 1.5 + n1x * 0.866025403;
  99967. r22 = n1z * n1z * 1.5 - 0.5;
  99968. px = tx;
  99969. py = ty;
  99970. pz = tz;
  99971. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99972. tx = px - pd * nx - c2x;
  99973. ty = py - pd * ny - c2y;
  99974. tz = pz - pd * nz - c2z;
  99975. len = tx * tx + ty * ty + tz * tz;
  99976. if (len > r2 * r2) {
  99977. len = r2 / OIMO.sqrt(len);
  99978. tx *= len;
  99979. ty *= len;
  99980. tz *= len;
  99981. }
  99982. px = c2x + tx;
  99983. py = c2y + ty;
  99984. pz = c2z + tz;
  99985. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  99986. px = dx * r00 + dy * r01 + dz * r02;
  99987. py = dx * r10 + dy * r11 + dz * r12;
  99988. pz = dx * r20 + dy * r21 + dz * r22;
  99989. px = (dx = px) + c1x;
  99990. py = (dy = py) + c1y;
  99991. pz = (dz = pz) + c1z;
  99992. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  99993. if (pd <= 0) {
  99994. tx = px - pd * nx - c2x;
  99995. ty = py - pd * ny - c2y;
  99996. tz = pz - pd * nz - c2z;
  99997. len = tx * tx + ty * ty + tz * tz;
  99998. if (len > r2 * r2) {
  99999. len = r2 / OIMO.sqrt(len);
  100000. tx *= len;
  100001. ty *= len;
  100002. tz *= len;
  100003. }
  100004. px = c2x + tx;
  100005. py = c2y + ty;
  100006. pz = c2z + tz;
  100007. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  100008. }
  100009. px = dx * r00 + dy * r01 + dz * r02;
  100010. py = dx * r10 + dy * r11 + dz * r12;
  100011. pz = dx * r20 + dy * r21 + dz * r22;
  100012. px = (dx = px) + c1x;
  100013. py = (dy = py) + c1y;
  100014. pz = (dz = pz) + c1z;
  100015. pd = nx * (px - c2x) + ny * (py - c2y) + nz * (pz - c2z);
  100016. if (pd <= 0) {
  100017. tx = px - pd * nx - c2x;
  100018. ty = py - pd * ny - c2y;
  100019. tz = pz - pd * nz - c2z;
  100020. len = tx * tx + ty * ty + tz * tz;
  100021. if (len > r2 * r2) {
  100022. len = r2 / OIMO.sqrt(len);
  100023. tx *= len;
  100024. ty *= len;
  100025. tz *= len;
  100026. }
  100027. px = c2x + tx;
  100028. py = c2y + ty;
  100029. pz = c2z + tz;
  100030. manifold.addPoint(px, py, pz, -nx, -ny, -nz, pd, false);
  100031. }
  100032. } else {
  100033. sx = tx;
  100034. sy = ty;
  100035. sz = tz;
  100036. depth1 = nx * (sx - c2x) + ny * (sy - c2y) + nz * (sz - c2z);
  100037. sx -= depth1 * nx;
  100038. sy -= depth1 * ny;
  100039. sz -= depth1 * nz;
  100040. if (dot > 0) {
  100041. ex = tx + n1x * h1 * 2;
  100042. ey = ty + n1y * h1 * 2;
  100043. ez = tz + n1z * h1 * 2;
  100044. } else {
  100045. ex = tx - n1x * h1 * 2;
  100046. ey = ty - n1y * h1 * 2;
  100047. ez = tz - n1z * h1 * 2;
  100048. }
  100049. depth2 = nx * (ex - c2x) + ny * (ey - c2y) + nz * (ez - c2z);
  100050. ex -= depth2 * nx;
  100051. ey -= depth2 * ny;
  100052. ez -= depth2 * nz;
  100053. dx = c2x - sx;
  100054. dy = c2y - sy;
  100055. dz = c2z - sz;
  100056. tx = ex - sx;
  100057. ty = ey - sy;
  100058. tz = ez - sz;
  100059. a = dx * dx + dy * dy + dz * dz;
  100060. b = dx * tx + dy * ty + dz * tz;
  100061. e = tx * tx + ty * ty + tz * tz;
  100062. f = b * b - e * (a - r2 * r2);
  100063. if (f < 0) break;
  100064. f = OIMO.sqrt(f);
  100065. t1 = (b + f) / e;
  100066. t2 = (b - f) / e;
  100067. if (t2 < t1) {
  100068. len = t1;
  100069. t1 = t2;
  100070. t2 = len;
  100071. }
  100072. if (t2 > 1) t2 = 1;
  100073. if (t1 < 0) t1 = 0;
  100074. tx = sx + (ex - sx) * t1;
  100075. ty = sy + (ey - sy) * t1;
  100076. tz = sz + (ez - sz) * t1;
  100077. ex = sx + (ex - sx) * t2;
  100078. ey = sy + (ey - sy) * t2;
  100079. ez = sz + (ez - sz) * t2;
  100080. sx = tx;
  100081. sy = ty;
  100082. sz = tz;
  100083. len = depth1 + (depth2 - depth1) * t1;
  100084. depth2 = depth1 + (depth2 - depth1) * t2;
  100085. depth1 = len;
  100086. if (depth1 < 0) {
  100087. manifold.addPoint(sx, sy, sz, -nx, -ny, -nz, depth1, false);
  100088. }
  100089. if (depth2 < 0) {
  100090. manifold.addPoint(ex, ey, ez, -nx, -ny, -nz, depth2, false);
  100091. }
  100092. }
  100093. break;
  100094. }
  100095. };
  100096. OIMO.SphereCylinderCollisionDetector = function (flip) {
  100097. OIMO.CollisionDetector.call(this);
  100098. this.flip = flip;
  100099. };
  100100. OIMO.SphereCylinderCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100101. OIMO.SphereCylinderCollisionDetector.prototype.constructor = OIMO.SphereCylinderCollisionDetector;
  100102. OIMO.SphereCylinderCollisionDetector.prototype.detectCollision = function (shape1, shape2, manifold) {
  100103. var s;
  100104. var c;
  100105. if (this.flip) {
  100106. s = shape2;
  100107. c = shape1;
  100108. } else {
  100109. s = shape1;
  100110. c = shape2;
  100111. }
  100112. var ps = s.position;
  100113. var psx = ps.x;
  100114. var psy = ps.y;
  100115. var psz = ps.z;
  100116. var pc = c.position;
  100117. var pcx = pc.x;
  100118. var pcy = pc.y;
  100119. var pcz = pc.z;
  100120. var dirx = c.normalDirection.x;
  100121. var diry = c.normalDirection.y;
  100122. var dirz = c.normalDirection.z;
  100123. var rads = s.radius;
  100124. var radc = c.radius;
  100125. var rad2 = rads + radc;
  100126. var halfh = c.halfHeight;
  100127. var dx = psx - pcx;
  100128. var dy = psy - pcy;
  100129. var dz = psz - pcz;
  100130. var dot = dx * dirx + dy * diry + dz * dirz;
  100131. if (dot < -halfh - rads || dot > halfh + rads) return;
  100132. var cx = pcx + dot * dirx;
  100133. var cy = pcy + dot * diry;
  100134. var cz = pcz + dot * dirz;
  100135. var d2x = psx - cx;
  100136. var d2y = psy - cy;
  100137. var d2z = psz - cz;
  100138. var len = d2x * d2x + d2y * d2y + d2z * d2z;
  100139. if (len > rad2 * rad2) return;
  100140. if (len > radc * radc) {
  100141. len = radc / OIMO.sqrt(len);
  100142. d2x *= len;
  100143. d2y *= len;
  100144. d2z *= len;
  100145. }
  100146. if (dot < -halfh) dot = -halfh;
  100147. else if (dot > halfh) dot = halfh;
  100148. cx = pcx + dot * dirx + d2x;
  100149. cy = pcy + dot * diry + d2y;
  100150. cz = pcz + dot * dirz + d2z;
  100151. dx = cx - psx;
  100152. dy = cy - psy;
  100153. dz = cz - psz;
  100154. len = dx * dx + dy * dy + dz * dz;
  100155. var invLen;
  100156. if (len > 0 && len < rads * rads) {
  100157. len = OIMO.sqrt(len);
  100158. invLen = 1 / len;
  100159. dx *= invLen;
  100160. dy *= invLen;
  100161. dz *= invLen;
  100162. ///result.addContactInfo(psx+dx*rads,psy+dy*rads,psz+dz*rads,dx,dy,dz,len-rads,s,c,0,0,false);
  100163. manifold.addPoint(psx + dx * rads, psy + dy * rads, psz + dz * rads, dx, dy, dz, len - rads, this.flip);
  100164. }
  100165. };
  100166. /**
  100167. * Class for checking collisions between 2 tetras,
  100168. * a shape that is made with 4 vertices and 4 faces
  100169. * arranged in triangles. With this algorigthm, soft
  100170. * body physics are possible and easier to implement.
  100171. * @author xprogram
  100172. */
  100173. OIMO.TetraTetraCollisionDetector = function () {
  100174. OIMO.CollisionDetector.call(this);
  100175. };
  100176. OIMO.TetraTetraCollisionDetector.prototype = Object.create(OIMO.CollisionDetector.prototype);
  100177. OIMO.TetraTetraCollisionDetector.prototype.constructor = OIMO.TetraTetraCollisionDetector;
  100178. OIMO.TetraTetraCollisionDetector.prototype.detectCollision = function (tet1, tet2, manifold) {
  100179. /*
  100180. * What we are doing:
  100181. * Each tetra is represented by four 3D triangles. The only
  100182. * quick way of finding if another tetra is within the other
  100183. * tetra is to see if a single vertex is within the triangles
  100184. * of the other tetra. So, for example, a tetra is represented
  100185. * by points B, C, D and E with triangles BCD, BCE, DCE and BDE.
  100186. * There is another tetra with a vertex A which was detected for
  100187. * collision by the broadphase. Now, if the point A is between ALL
  100188. * triangles of the other tetra (BCD, BCE, etc.) then the collision
  100189. * is valid and we can pass point A to the manifold. Since the only
  100190. * points on the tetra are the 4 vertices, collision detection is
  100191. * not so complex. However, it can be time-consuming because we
  100192. * need to split the 3D triangles into three 2D triangles each for
  100193. * collision detection.
  100194. */
  100195. var i, j, vec, fs1 = tet1.faces, vs1 = tet1.verts, fs2 = tet2.faces, vs2 = tet2.verts;
  100196. var j1, j2, j3, ts = 0; // Triangle vertices `j1`, `j2` and `j3`
  100197. // fs is undeclared
  100198. var fs = fs1;
  100199. for (i = 0; i < 4; i++) {
  100200. vec = vs1[i];
  100201. for (j = 0; j < 4; j++) {
  100202. j1 = vs2[fs[i].a];
  100203. j2 = vs2[fs[i].b];
  100204. j3 = vs2[fs[i].c];
  100205. if (
  100206. tricheck(pt(vec.x, vec.y), pt(j1.x, j1.y), pt(j2.x, j2.y), pt(j3.x, j3.y)) &&
  100207. tricheck(pt(vec.x, vec.z), pt(j1.x, j1.z), pt(j2.x, j2.z), pt(j3.x, j3.z)) &&
  100208. tricheck(pt(vec.z, vec.y), pt(j1.z, j1.y), pt(j2.z, j2.y), pt(j3.z, j3.y))
  100209. )
  100210. ts++;
  100211. if (ts === 4) // Only add point if it is inside all 4 triangles
  100212. manifold.addPoint(vec);
  100213. }
  100214. }
  100215. };
  100216. // Taken from: http://jsfiddle.net/PerroAZUL/zdaY8/1/
  100217. function tricheck(p, p0, p1, p2) {
  100218. var A = 0.5 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  100219. var sg = A < 0 ? -1 : 1;
  100220. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sg;
  100221. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sg;
  100222. return s > 0 && t > 0 && (s + t) < 2 * A * sg;
  100223. }
  100224. function pt(x, y) { return { x: x, y: y }; }
  100225. /**
  100226. * An axis-aligned bounding box.
  100227. * @author saharan
  100228. * @author lo-th
  100229. */
  100230. OIMO.AABB = function (minX, maxX, minY, maxY, minZ, maxZ) {
  100231. this.elements = new OIMO_ARRAY_TYPE(6);
  100232. var te = this.elements;
  100233. te[0] = minX || 0; te[1] = minY || 0; te[2] = minZ || 0;
  100234. te[3] = maxX || 0; te[4] = maxY || 0; te[5] = maxZ || 0;
  100235. };
  100236. OIMO.AABB.prototype = {
  100237. constructor: OIMO.AABB,
  100238. set: function (minX, maxX, minY, maxY, minZ, maxZ) {
  100239. var te = this.elements;
  100240. te[0] = minX; te[3] = maxX;
  100241. te[1] = minY; te[4] = maxY;
  100242. te[2] = minZ; te[5] = maxZ;
  100243. return this;
  100244. },
  100245. intersectTest: function (aabb) {
  100246. var te = this.elements;
  100247. var ue = aabb.elements;
  100248. 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];
  100249. },
  100250. intersectTestTwo: function (aabb) {
  100251. var te = this.elements;
  100252. var ue = aabb.elements;
  100253. 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];
  100254. },
  100255. clone: function () {
  100256. return new this.constructor().fromArray(this.elements);
  100257. },
  100258. copy: function (aabb, margin) {
  100259. var m = margin || 0;
  100260. var me = aabb.elements;
  100261. this.set(me[0] - m, me[3] + m, me[1] - m, me[4] + m, me[2] - m, me[5] + m);
  100262. return this;
  100263. },
  100264. fromArray: function (array) {
  100265. this.elements.set(array);
  100266. return this;
  100267. },
  100268. // Set this AABB to the combined AABB of aabb1 and aabb2.
  100269. combine: function (aabb1, aabb2) {
  100270. var a = aabb1.elements;
  100271. var b = aabb2.elements;
  100272. var te = this.elements;
  100273. te[0] = a[0] < b[0] ? a[0] : b[0];
  100274. te[1] = a[1] < b[1] ? a[1] : b[1];
  100275. te[2] = a[2] < b[2] ? a[2] : b[2];
  100276. te[3] = a[3] > b[3] ? a[3] : b[3];
  100277. te[4] = a[4] > b[4] ? a[4] : b[4];
  100278. te[5] = a[5] > b[5] ? a[5] : b[5];
  100279. return this;
  100280. },
  100281. // Get the surface area.
  100282. surfaceArea: function () {
  100283. var te = this.elements;
  100284. var a = te[3] - te[0];
  100285. var h = te[4] - te[1];
  100286. var d = te[5] - te[2];
  100287. return 2 * (a * (h + d) + h * d);
  100288. },
  100289. // Get whether the AABB intersects with the point or not.
  100290. intersectsWithPoint: function (x, y, z) {
  100291. var te = this.elements;
  100292. return x >= te[0] && x <= te[3] && y >= te[1] && y <= te[4] && z >= te[2] && z <= te[5];
  100293. },
  100294. /**
  100295. * Set the AABB from an array
  100296. * of vertices. From THREE.
  100297. * @author mrdoob
  100298. * @author xprogram
  100299. */
  100300. setFromPoints: function (arr) {
  100301. this.makeEmpty();
  100302. for (var i = 0; i < arr.length; i++) {
  100303. this.expandByPoint(arr[i]);
  100304. }
  100305. },
  100306. makeEmpty: function () {
  100307. this.set(-Infinity, -Infinity, -Infinity, Infinity, Infinity, Infinity);
  100308. },
  100309. expandByPoint: function (pt) {
  100310. var te = this.elements;
  100311. this.set(
  100312. OIMO.min(te[0], pt.x), OIMO.min(te[1], pt.y), OIMO.min(te[2], pt.z),
  100313. OIMO.max(te[3], pt.x), OIMO.max(te[4], pt.y), OIMO.max(te[5], pt.z)
  100314. );
  100315. }
  100316. };
  100317. /**
  100318. * A proxy is used for broad-phase collecting pairs that can be colliding.
  100319. */
  100320. OIMO.Proxy = function (shape) {
  100321. // The parent shape.
  100322. this.shape = shape;
  100323. // The axis-aligned bounding box.
  100324. this.aabb = shape.aabb;
  100325. };
  100326. OIMO.Proxy.prototype = {
  100327. constructor: OIMO.Proxy,
  100328. // Update the proxy.
  100329. update: function () {
  100330. OIMO.Error("Proxy", "Inheritance error.");
  100331. }
  100332. };
  100333. /**
  100334. * A basic implementation of proxies.
  100335. * @author saharan
  100336. */
  100337. OIMO.BasicProxy = function (shape) {
  100338. OIMO.Proxy.call(this, shape);
  100339. this.id = OIMO.proxyID++;
  100340. };
  100341. OIMO.BasicProxy.prototype = Object.create(OIMO.Proxy.prototype);
  100342. OIMO.BasicProxy.prototype.constructor = OIMO.BasicProxy;
  100343. OIMO.BasicProxy.prototype.update = function () {
  100344. };
  100345. /**
  100346. * The broad-phase is used for collecting all possible pairs for collision.
  100347. */
  100348. OIMO.BroadPhase = function () {
  100349. this.types = OIMO.BR_NULL;
  100350. this.numPairChecks = 0;
  100351. this.numPairs = 0;
  100352. this.pairs = [];
  100353. };
  100354. OIMO.BroadPhase.prototype = {
  100355. constructor: OIMO.BroadPhase,
  100356. /**
  100357. * Create a new proxy.
  100358. * @param shape
  100359. * @return
  100360. */
  100361. createProxy: function (shape) {
  100362. OIMO.Error("BroadPhase", "Inheritance error.");
  100363. },
  100364. /**
  100365. * Add the proxy into the broad-phase.
  100366. * @param proxy
  100367. */
  100368. addProxy: function (proxy) {
  100369. OIMO.Error("BroadPhase", "Inheritance error.");
  100370. },
  100371. /**
  100372. * Remove the proxy from the broad-phase.
  100373. * @param proxy
  100374. */
  100375. removeProxy: function (proxy) {
  100376. OIMO.Error("BroadPhase", "Inheritance error.");
  100377. },
  100378. /**
  100379. * Returns whether the pair is available or not.
  100380. * @param s1
  100381. * @param s2
  100382. * @return
  100383. */
  100384. isAvailablePair: function (s1, s2) {
  100385. var b1 = s1.parent;
  100386. var b2 = s2.parent;
  100387. if (b1 == b2 || // same parents
  100388. (!b1.isDynamic && !b2.isDynamic) || // static or kinematic object
  100389. (s1.belongsTo & s2.collidesWith) == 0 ||
  100390. (s2.belongsTo & s1.collidesWith) == 0 // collision filtering
  100391. ) { return false; }
  100392. var js;
  100393. if (b1.numJoints < b2.numJoints) js = b1.jointLink;
  100394. else js = b2.jointLink;
  100395. while (js !== null) {
  100396. var joint = js.joint;
  100397. if (!joint.allowCollision && ((joint.body1 == b1 && joint.body2 == b2) || (joint.body1 == b2 && joint.body2 == b1))) { return false; }
  100398. js = js.next;
  100399. }
  100400. return true;
  100401. },
  100402. // Detect overlapping pairs.
  100403. detectPairs: function () {
  100404. // clear old
  100405. this.pairs = [];
  100406. this.numPairs = 0;
  100407. this.numPairChecks = 0;
  100408. this.collectPairs();
  100409. },
  100410. collectPairs: function () {
  100411. OIMO.Error("BroadPhase", "Inheritance error.");
  100412. },
  100413. addPair: function (s1, s2) {
  100414. var pair = new OIMO.Pair(s1, s2);
  100415. this.pairs.push(pair);
  100416. this.numPairs++;
  100417. }
  100418. };
  100419. /**
  100420. * A broad-phase algorithm with brute-force search.
  100421. * This always checks for all possible pairs.
  100422. */
  100423. OIMO.BruteForceBroadPhase = function () {
  100424. OIMO.BroadPhase.call(this);
  100425. this.types = OIMO.BR_BRUTE_FORCE;;
  100426. //this.numProxies=0;
  100427. ///this.maxProxies = 256;
  100428. this.proxies = [];
  100429. //this.proxies.length = 256;
  100430. };
  100431. OIMO.BruteForceBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  100432. OIMO.BruteForceBroadPhase.prototype.constructor = OIMO.BruteForceBroadPhase;
  100433. OIMO.BruteForceBroadPhase.prototype.createProxy = function (shape) {
  100434. return new OIMO.BasicProxy(shape);
  100435. };
  100436. OIMO.BruteForceBroadPhase.prototype.addProxy = function (proxy) {
  100437. /*if(this.numProxies==this.maxProxies){
  100438. //this.maxProxies<<=1;
  100439. this.maxProxies*=2;
  100440. var newProxies=[];
  100441. newProxies.length = this.maxProxies;
  100442. var i = this.numProxies;
  100443. while(i--){
  100444. //for(var i=0, l=this.numProxies;i<l;i++){
  100445. newProxies[i]=this.proxies[i];
  100446. }
  100447. this.proxies=newProxies;
  100448. }*/
  100449. //this.proxies[this.numProxies++] = proxy;
  100450. this.proxies.push(proxy);
  100451. //this.numProxies++;
  100452. };
  100453. OIMO.BruteForceBroadPhase.prototype.removeProxy = function (proxy) {
  100454. var n = this.proxies.indexOf(proxy);
  100455. if (n > -1) {
  100456. this.proxies.splice(n, 1);
  100457. //this.numProxies--;
  100458. }
  100459. /*var i = this.numProxies;
  100460. while(i--){
  100461. //for(var i=0, l=this.numProxies;i<l;i++){
  100462. if(this.proxies[i] == proxy){
  100463. this.proxies[i] = this.proxies[--this.numProxies];
  100464. this.proxies[this.numProxies] = null;
  100465. return;
  100466. }
  100467. }*/
  100468. };
  100469. OIMO.BruteForceBroadPhase.prototype.collectPairs = function () {
  100470. var i = 0, j, p1, p2;
  100471. var px = this.proxies;
  100472. var l = px.length;//this.numProxies;
  100473. //var ar1 = [];
  100474. //var ar2 = [];
  100475. //for( i = px.length ; i-- ; ar1[ i ] = px[ i ] ){};
  100476. //for( i = px.length ; i-- ; ar2[ i ] = px[ i ] ){};
  100477. //var ar1 = JSON.parse(JSON.stringify(this.proxies))
  100478. //var ar2 = JSON.parse(JSON.stringify(this.proxies))
  100479. this.numPairChecks = l * (l - 1) >> 1;
  100480. //this.numPairChecks=this.numProxies*(this.numProxies-1)*0.5;
  100481. while (i < l) {
  100482. p1 = px[i++];
  100483. j = i + 1;
  100484. while (j < l) {
  100485. p2 = px[j++];
  100486. if (p1.aabb.intersectTest(p2.aabb) || !this.isAvailablePair(p1.shape, p2.shape)) continue;
  100487. this.addPair(p1.shape, p2.shape);
  100488. }
  100489. }
  100490. };
  100491. /**
  100492. * A pair of shapes that may collide.
  100493. * @author saharan
  100494. */
  100495. OIMO.Pair = function (s1, s2) {
  100496. // The first shape.
  100497. this.shape1 = s1 || null;
  100498. // The second shape.
  100499. this.shape2 = s2 || null;
  100500. };
  100501. /**
  100502. * A projection axis for sweep and prune broad-phase.
  100503. * @author saharan
  100504. */
  100505. OIMO.SAPAxis = function () {
  100506. this.numElements = 0;
  100507. this.bufferSize = 256;
  100508. this.elements = [];
  100509. this.elements.length = this.bufferSize;
  100510. this.stack = new OIMO_ARRAY_TYPE(64);
  100511. };
  100512. OIMO.SAPAxis.prototype = {
  100513. constructor: OIMO.SAPAxis,
  100514. addElements: function (min, max) {
  100515. if (this.numElements + 2 >= this.bufferSize) {
  100516. //this.bufferSize<<=1;
  100517. this.bufferSize *= 2;
  100518. var newElements = [];
  100519. var i = this.numElements;
  100520. while (i--) {
  100521. //for(var i=0, l=this.numElements; i<l; i++){
  100522. newElements[i] = this.elements[i];
  100523. }
  100524. }
  100525. this.elements[this.numElements++] = min;
  100526. this.elements[this.numElements++] = max;
  100527. },
  100528. removeElements: function (min, max) {
  100529. var minIndex = -1;
  100530. var maxIndex = -1;
  100531. for (var i = 0, l = this.numElements; i < l; i++) {
  100532. var e = this.elements[i];
  100533. if (e == min || e == max) {
  100534. if (minIndex == -1) {
  100535. minIndex = i;
  100536. } else {
  100537. maxIndex = i;
  100538. break;
  100539. }
  100540. }
  100541. }
  100542. for (i = minIndex + 1, l = maxIndex; i < l; i++) {
  100543. this.elements[i - 1] = this.elements[i];
  100544. }
  100545. for (i = maxIndex + 1, l = this.numElements; i < l; i++) {
  100546. this.elements[i - 2] = this.elements[i];
  100547. }
  100548. this.elements[--this.numElements] = null;
  100549. this.elements[--this.numElements] = null;
  100550. },
  100551. sort: function () {
  100552. var count = 0;
  100553. var threshold = 1;
  100554. while ((this.numElements >> threshold) != 0) threshold++;
  100555. threshold = threshold * this.numElements >> 2;
  100556. count = 0;
  100557. var giveup = false;
  100558. var elements = this.elements;
  100559. for (var i = 1, l = this.numElements; i < l; i++) { // try insertion sort
  100560. var tmp = elements[i];
  100561. var pivot = tmp.value;
  100562. var tmp2 = elements[i - 1];
  100563. if (tmp2.value > pivot) {
  100564. var j = i;
  100565. do {
  100566. elements[j] = tmp2;
  100567. if (--j == 0) break;
  100568. tmp2 = elements[j - 1];
  100569. } while (tmp2.value > pivot);
  100570. elements[j] = tmp;
  100571. count += i - j;
  100572. if (count > threshold) {
  100573. giveup = true; // stop and use quick sort
  100574. break;
  100575. }
  100576. }
  100577. }
  100578. if (!giveup) return;
  100579. count = 2; var stack = this.stack;
  100580. stack[0] = 0;
  100581. stack[1] = this.numElements - 1;
  100582. while (count > 0) {
  100583. var right = stack[--count];
  100584. var left = stack[--count];
  100585. var diff = right - left;
  100586. if (diff > 16) { // quick sort
  100587. //var mid=left+(diff>>1);
  100588. var mid = left + (OIMO.floor(diff * 0.5));
  100589. tmp = elements[mid];
  100590. elements[mid] = elements[right];
  100591. elements[right] = tmp;
  100592. pivot = tmp.value;
  100593. i = left - 1;
  100594. j = right;
  100595. while (true) {
  100596. var ei;
  100597. var ej;
  100598. do { ei = elements[++i]; } while (ei.value < pivot);
  100599. do { ej = elements[--j]; } while (pivot < ej.value && j != left);
  100600. if (i >= j) break;
  100601. elements[i] = ej;
  100602. elements[j] = ei;
  100603. }
  100604. elements[right] = elements[i];
  100605. elements[i] = tmp;
  100606. if (i - left > right - i) {
  100607. stack[count++] = left;
  100608. stack[count++] = i - 1;
  100609. stack[count++] = i + 1;
  100610. stack[count++] = right;
  100611. } else {
  100612. stack[count++] = i + 1;
  100613. stack[count++] = right;
  100614. stack[count++] = left;
  100615. stack[count++] = i - 1;
  100616. }
  100617. } else {
  100618. for (i = left + 1; i <= right; i++) {
  100619. tmp = elements[i];
  100620. pivot = tmp.value;
  100621. tmp2 = elements[i - 1];
  100622. if (tmp2.value > pivot) {
  100623. j = i;
  100624. do {
  100625. elements[j] = tmp2;
  100626. if (--j == 0) break;
  100627. tmp2 = elements[j - 1];
  100628. } while (tmp2.value > pivot);
  100629. elements[j] = tmp;
  100630. }
  100631. }
  100632. }
  100633. }
  100634. },
  100635. calculateTestCount: function () {
  100636. var num = 1;
  100637. var sum = 0;
  100638. for (var i = 1, l = this.numElements; i < l; i++) {
  100639. if (this.elements[i].max) {
  100640. num--;
  100641. } else {
  100642. sum += num;
  100643. num++;
  100644. }
  100645. }
  100646. return sum;
  100647. }
  100648. }
  100649. /**
  100650. * A broad-phase collision detection algorithm using sweep and prune.
  100651. * @author saharan
  100652. * @author lo-th
  100653. */
  100654. OIMO.SAPBroadPhase = function () {
  100655. OIMO.BroadPhase.call(this);
  100656. this.types = OIMO.BR_SWEEP_AND_PRUNE;
  100657. this.numElementsD = 0;
  100658. this.numElementsS = 0;
  100659. // dynamic proxies
  100660. this.axesD = [
  100661. new OIMO.SAPAxis(),
  100662. new OIMO.SAPAxis(),
  100663. new OIMO.SAPAxis()
  100664. ];
  100665. // static or sleeping proxies
  100666. this.axesS = [
  100667. new OIMO.SAPAxis(),
  100668. new OIMO.SAPAxis(),
  100669. new OIMO.SAPAxis()
  100670. ];
  100671. this.index1 = 0;
  100672. this.index2 = 1;
  100673. };
  100674. OIMO.SAPBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  100675. OIMO.SAPBroadPhase.prototype.constructor = OIMO.SAPBroadPhase;
  100676. OIMO.SAPBroadPhase.prototype.createProxy = function (shape) {
  100677. return new OIMO.SAPProxy(this, shape);
  100678. };
  100679. OIMO.SAPBroadPhase.prototype.addProxy = function (proxy) {
  100680. var p = proxy;
  100681. if (p.isDynamic()) {
  100682. this.axesD[0].addElements(p.min[0], p.max[0]);
  100683. this.axesD[1].addElements(p.min[1], p.max[1]);
  100684. this.axesD[2].addElements(p.min[2], p.max[2]);
  100685. p.belongsTo = 1;
  100686. this.numElementsD += 2;
  100687. } else {
  100688. this.axesS[0].addElements(p.min[0], p.max[0]);
  100689. this.axesS[1].addElements(p.min[1], p.max[1]);
  100690. this.axesS[2].addElements(p.min[2], p.max[2]);
  100691. p.belongsTo = 2;
  100692. this.numElementsS += 2;
  100693. }
  100694. };
  100695. OIMO.SAPBroadPhase.prototype.removeProxy = function (proxy) {
  100696. var p = proxy;
  100697. if (p.belongsTo == 0) return;
  100698. /*else if ( p.belongsTo == 1 ) {
  100699. this.axesD[0].removeElements( p.min[0], p.max[0] );
  100700. this.axesD[1].removeElements( p.min[1], p.max[1] );
  100701. this.axesD[2].removeElements( p.min[2], p.max[2] );
  100702. this.numElementsD -= 2;
  100703. } else if ( p.belongsTo == 2 ) {
  100704. this.axesS[0].removeElements( p.min[0], p.max[0] );
  100705. this.axesS[1].removeElements( p.min[1], p.max[1] );
  100706. this.axesS[2].removeElements( p.min[2], p.max[2] );
  100707. this.numElementsS -= 2;
  100708. }*/
  100709. switch (p.belongsTo) {
  100710. case 1:
  100711. this.axesD[0].removeElements(p.min[0], p.max[0]);
  100712. this.axesD[1].removeElements(p.min[1], p.max[1]);
  100713. this.axesD[2].removeElements(p.min[2], p.max[2]);
  100714. this.numElementsD -= 2;
  100715. break;
  100716. case 2:
  100717. this.axesS[0].removeElements(p.min[0], p.max[0]);
  100718. this.axesS[1].removeElements(p.min[1], p.max[1]);
  100719. this.axesS[2].removeElements(p.min[2], p.max[2]);
  100720. this.numElementsS -= 2;
  100721. break;
  100722. }
  100723. p.belongsTo = 0;
  100724. };
  100725. OIMO.SAPBroadPhase.prototype.collectPairs = function () {
  100726. if (this.numElementsD == 0) return;
  100727. var axis1 = this.axesD[this.index1];
  100728. var axis2 = this.axesD[this.index2];
  100729. axis1.sort();
  100730. axis2.sort();
  100731. var count1 = axis1.calculateTestCount();
  100732. var count2 = axis2.calculateTestCount();
  100733. var elementsD;
  100734. var elementsS;
  100735. if (count1 <= count2) {// select the best axis
  100736. axis2 = this.axesS[this.index1];
  100737. axis2.sort();
  100738. elementsD = axis1.elements;
  100739. elementsS = axis2.elements;
  100740. } else {
  100741. axis1 = this.axesS[this.index2];
  100742. axis1.sort();
  100743. elementsD = axis2.elements;
  100744. elementsS = axis1.elements;
  100745. this.index1 ^= this.index2;
  100746. this.index2 ^= this.index1;
  100747. this.index1 ^= this.index2;
  100748. }
  100749. var activeD;
  100750. var activeS;
  100751. var p = 0;
  100752. var q = 0;
  100753. while (p < this.numElementsD) {
  100754. var e1;
  100755. var dyn;
  100756. if (q == this.numElementsS) {
  100757. e1 = elementsD[p];
  100758. dyn = true;
  100759. p++;
  100760. } else {
  100761. var d = elementsD[p];
  100762. var s = elementsS[q];
  100763. if (d.value < s.value) {
  100764. e1 = d;
  100765. dyn = true;
  100766. p++;
  100767. } else {
  100768. e1 = s;
  100769. dyn = false;
  100770. q++;
  100771. }
  100772. }
  100773. if (!e1.max) {
  100774. var s1 = e1.proxy.shape;
  100775. var min1 = e1.min1.value;
  100776. var max1 = e1.max1.value;
  100777. var min2 = e1.min2.value;
  100778. var max2 = e1.max2.value;
  100779. for (var e2 = activeD; e2 != null; e2 = e2.pair) {// test for dynamic
  100780. var s2 = e2.proxy.shape;
  100781. this.numPairChecks++;
  100782. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  100783. this.addPair(s1, s2);
  100784. }
  100785. if (dyn) {
  100786. for (e2 = activeS; e2 != null; e2 = e2.pair) {// test for static
  100787. s2 = e2.proxy.shape;
  100788. this.numPairChecks++;
  100789. if (min1 > e2.max1.value || max1 < e2.min1.value || min2 > e2.max2.value || max2 < e2.min2.value || !this.isAvailablePair(s1, s2)) continue;
  100790. this.addPair(s1, s2);
  100791. }
  100792. e1.pair = activeD;
  100793. activeD = e1;
  100794. } else {
  100795. e1.pair = activeS;
  100796. activeS = e1;
  100797. }
  100798. } else {
  100799. var min = e1.pair;
  100800. if (dyn) {
  100801. if (min == activeD) {
  100802. activeD = activeD.pair;
  100803. continue;
  100804. } else {
  100805. e1 = activeD;
  100806. }
  100807. } else {
  100808. if (min == activeS) {
  100809. activeS = activeS.pair;
  100810. continue;
  100811. } else {
  100812. e1 = activeS;
  100813. }
  100814. }
  100815. do {
  100816. e2 = e1.pair;
  100817. if (e2 == min) {
  100818. e1.pair = e2.pair;
  100819. break;
  100820. }
  100821. e1 = e2;
  100822. } while (e1 != null);
  100823. }
  100824. }
  100825. this.index2 = (this.index1 | this.index2) ^ 3;
  100826. };
  100827. /**
  100828. * An element of proxies.
  100829. * @author saharan
  100830. */
  100831. OIMO.SAPElement = function (proxy, max) {
  100832. // The parent proxy
  100833. this.proxy = proxy;
  100834. // The pair element.
  100835. this.pair = null;
  100836. // The minimum element on other axis.
  100837. this.min1 = null;
  100838. // The maximum element on other axis.
  100839. this.max1 = null;
  100840. // The minimum element on other axis.
  100841. this.min2 = null;
  100842. // The maximum element on other axis.
  100843. this.max2 = null;
  100844. // Whether the element has maximum value or not.
  100845. this.max = max;
  100846. // The value of the element.
  100847. this.value = 0;
  100848. };
  100849. /**
  100850. * A proxy for sweep and prune broad-phase.
  100851. * @author saharan
  100852. * @author lo-th
  100853. */
  100854. OIMO.SAPProxy = function (sap, shape) {
  100855. OIMO.Proxy.call(this, shape);
  100856. // Type of the axis to which the proxy belongs to. [0:none, 1:dynamic, 2:static]
  100857. this.belongsTo = 0;
  100858. // The maximum elements on each axis.
  100859. this.max = [];
  100860. // The minimum elements on each axis.
  100861. this.min = [];
  100862. this.sap = sap;
  100863. this.min[0] = new OIMO.SAPElement(this, false);
  100864. this.max[0] = new OIMO.SAPElement(this, true);
  100865. this.min[1] = new OIMO.SAPElement(this, false);
  100866. this.max[1] = new OIMO.SAPElement(this, true);
  100867. this.min[2] = new OIMO.SAPElement(this, false);
  100868. this.max[2] = new OIMO.SAPElement(this, true);
  100869. this.max[0].pair = this.min[0];
  100870. this.max[1].pair = this.min[1];
  100871. this.max[2].pair = this.min[2];
  100872. this.min[0].min1 = this.min[1];
  100873. this.min[0].max1 = this.max[1];
  100874. this.min[0].min2 = this.min[2];
  100875. this.min[0].max2 = this.max[2];
  100876. this.min[1].min1 = this.min[0];
  100877. this.min[1].max1 = this.max[0];
  100878. this.min[1].min2 = this.min[2];
  100879. this.min[1].max2 = this.max[2];
  100880. this.min[2].min1 = this.min[0];
  100881. this.min[2].max1 = this.max[0];
  100882. this.min[2].min2 = this.min[1];
  100883. this.min[2].max2 = this.max[1];
  100884. };
  100885. OIMO.SAPProxy.prototype = Object.create(OIMO.Proxy.prototype);
  100886. OIMO.SAPProxy.prototype.constructor = OIMO.SAPProxy;
  100887. // Returns whether the proxy is dynamic or not.
  100888. OIMO.SAPProxy.prototype.isDynamic = function () {
  100889. var body = this.shape.parent;
  100890. return body.isDynamic && !body.sleeping;
  100891. };
  100892. OIMO.SAPProxy.prototype.update = function () {
  100893. var te = this.aabb.elements;
  100894. this.min[0].value = te[0];
  100895. this.min[1].value = te[1];
  100896. this.min[2].value = te[2];
  100897. this.max[0].value = te[3];
  100898. this.max[1].value = te[4];
  100899. this.max[2].value = te[5];
  100900. if (this.belongsTo == 1 && !this.isDynamic() || this.belongsTo == 2 && this.isDynamic()) {
  100901. this.sap.removeProxy(this);
  100902. this.sap.addProxy(this);
  100903. }
  100904. };
  100905. /**
  100906. * A dynamic bounding volume tree for the broad-phase algorithm.
  100907. * @author saharan
  100908. * @author lo-th
  100909. */
  100910. OIMO.DBVT = function () {
  100911. // The root of the tree.
  100912. this.root = null;
  100913. this.freeNodes = [];
  100914. this.freeNodes.length = 16384;
  100915. this.numFreeNodes = 0;
  100916. this.aabb = new OIMO.AABB();
  100917. };
  100918. OIMO.DBVT.prototype = {
  100919. constructor: OIMO.DBVT,
  100920. /**
  100921. * Move a leaf.
  100922. * @param leaf
  100923. */
  100924. moveLeaf: function (leaf) {
  100925. this.deleteLeaf(leaf);
  100926. this.insertLeaf(leaf);
  100927. },
  100928. /**
  100929. * Insert a leaf to the tree.
  100930. * @param node
  100931. */
  100932. insertLeaf: function (leaf) {
  100933. if (this.root == null) {
  100934. this.root = leaf;
  100935. return;
  100936. }
  100937. var lb = leaf.aabb;
  100938. var sibling = this.root;
  100939. var oldArea;
  100940. var newArea;
  100941. while (sibling.proxy == null) { // descend the node to search the best pair
  100942. var c1 = sibling.child1;
  100943. var c2 = sibling.child2;
  100944. var b = sibling.aabb;
  100945. var c1b = c1.aabb;
  100946. var c2b = c2.aabb;
  100947. oldArea = b.surfaceArea();
  100948. this.aabb.combine(lb, b);
  100949. newArea = this.aabb.surfaceArea();
  100950. var creatingCost = newArea * 2;
  100951. var incrementalCost = (newArea - oldArea) * 2; // cost of creating a new pair with the node
  100952. var discendingCost1 = incrementalCost;
  100953. this.aabb.combine(lb, c1b);
  100954. if (c1.proxy != null) {
  100955. // leaf cost = area(combined aabb)
  100956. discendingCost1 += this.aabb.surfaceArea();
  100957. } else {
  100958. // node cost = area(combined aabb) - area(old aabb)
  100959. discendingCost1 += this.aabb.surfaceArea() - c1b.surfaceArea();
  100960. }
  100961. var discendingCost2 = incrementalCost;
  100962. this.aabb.combine(lb, c2b);
  100963. if (c2.proxy != null) {
  100964. // leaf cost = area(combined aabb)
  100965. discendingCost2 += this.aabb.surfaceArea();
  100966. } else {
  100967. // node cost = area(combined aabb) - area(old aabb)
  100968. discendingCost2 += this.aabb.surfaceArea() - c2b.surfaceArea();
  100969. }
  100970. if (discendingCost1 < discendingCost2) {
  100971. if (creatingCost < discendingCost1) {
  100972. break;// stop descending
  100973. } else {
  100974. sibling = c1;// descend into first child
  100975. }
  100976. } else {
  100977. if (creatingCost < discendingCost2) {
  100978. break;// stop descending
  100979. } else {
  100980. sibling = c2;// descend into second child
  100981. }
  100982. }
  100983. }
  100984. var oldParent = sibling.parent;
  100985. var newParent;
  100986. if (this.numFreeNodes > 0) {
  100987. newParent = this.freeNodes[--this.numFreeNodes];
  100988. } else {
  100989. newParent = new OIMO.DBVTNode();
  100990. }
  100991. newParent.parent = oldParent;
  100992. newParent.child1 = leaf;
  100993. newParent.child2 = sibling;
  100994. newParent.aabb.combine(leaf.aabb, sibling.aabb);
  100995. newParent.height = sibling.height + 1;
  100996. sibling.parent = newParent;
  100997. leaf.parent = newParent;
  100998. if (sibling == this.root) {
  100999. // replace root
  101000. this.root = newParent;
  101001. } else {
  101002. // replace child
  101003. if (oldParent.child1 == sibling) {
  101004. oldParent.child1 = newParent;
  101005. } else {
  101006. oldParent.child2 = newParent;
  101007. }
  101008. }
  101009. // update whole tree
  101010. do {
  101011. newParent = this.balance(newParent);
  101012. this.fix(newParent);
  101013. newParent = newParent.parent;
  101014. } while (newParent != null);
  101015. },
  101016. getBalance: function (node) {
  101017. if (node.proxy != null) return 0;
  101018. return node.child1.height - node.child2.height;
  101019. },
  101020. /*print:function(node,indent,text){
  101021. var hasChild=node.proxy==null;
  101022. if(hasChild)text=this.print(node.child1,indent+1,text);
  101023. for(var i=indent*2;i>=0;i--){
  101024. text+=" ";
  101025. }
  101026. text+=(hasChild?this.getBalance(node):"["+node.proxy.aabb.minX+"]")+"\n";
  101027. if(hasChild)text=this.print(node.child2,indent+1,text);
  101028. return text;
  101029. },*/
  101030. /**
  101031. * Delete a leaf from the tree.
  101032. * @param node
  101033. */
  101034. deleteLeaf: function (leaf) {
  101035. if (leaf == this.root) {
  101036. this.root = null;
  101037. return;
  101038. }
  101039. var parent = leaf.parent;
  101040. var sibling;
  101041. if (parent.child1 == leaf) {
  101042. sibling = parent.child2;
  101043. } else {
  101044. sibling = parent.child1;
  101045. }
  101046. if (parent == this.root) {
  101047. this.root = sibling;
  101048. sibling.parent = null;
  101049. return;
  101050. }
  101051. var grandParent = parent.parent;
  101052. sibling.parent = grandParent;
  101053. if (grandParent.child1 == parent) {
  101054. grandParent.child1 = sibling;
  101055. } else {
  101056. grandParent.child2 = sibling;
  101057. }
  101058. if (this.numFreeNodes < 16384) {
  101059. this.freeNodes[this.numFreeNodes++] = parent;
  101060. }
  101061. do {
  101062. grandParent = this.balance(grandParent);
  101063. this.fix(grandParent);
  101064. grandParent = grandParent.parent;
  101065. } while (grandParent != null);
  101066. },
  101067. balance: function (node) {
  101068. var nh = node.height;
  101069. if (nh < 2) {
  101070. return node;
  101071. }
  101072. var p = node.parent;
  101073. var l = node.child1;
  101074. var r = node.child2;
  101075. var lh = l.height;
  101076. var rh = r.height;
  101077. var balance = lh - rh;
  101078. var t;// for bit operation
  101079. // [ N ]
  101080. // / \
  101081. // [ L ] [ R ]
  101082. // / \ / \
  101083. // [L-L] [L-R] [R-L] [R-R]
  101084. // Is the tree balanced?
  101085. if (balance > 1) {
  101086. var ll = l.child1;
  101087. var lr = l.child2;
  101088. var llh = ll.height;
  101089. var lrh = lr.height;
  101090. // Is L-L higher than L-R?
  101091. if (llh > lrh) {
  101092. // set N to L-R
  101093. l.child2 = node;
  101094. node.parent = l;
  101095. // [ L ]
  101096. // / \
  101097. // [L-L] [ N ]
  101098. // / \ / \
  101099. // [...] [...] [ L ] [ R ]
  101100. // set L-R
  101101. node.child1 = lr;
  101102. lr.parent = node;
  101103. // [ L ]
  101104. // / \
  101105. // [L-L] [ N ]
  101106. // / \ / \
  101107. // [...] [...] [L-R] [ R ]
  101108. // fix bounds and heights
  101109. node.aabb.combine(lr.aabb, r.aabb);
  101110. t = lrh - rh;
  101111. node.height = lrh - (t & t >> 31) + 1;
  101112. l.aabb.combine(ll.aabb, node.aabb);
  101113. t = llh - nh;
  101114. l.height = llh - (t & t >> 31) + 1;
  101115. } else {
  101116. // set N to L-L
  101117. l.child1 = node;
  101118. node.parent = l;
  101119. // [ L ]
  101120. // / \
  101121. // [ N ] [L-R]
  101122. // / \ / \
  101123. // [ L ] [ R ] [...] [...]
  101124. // set L-L
  101125. node.child1 = ll;
  101126. ll.parent = node;
  101127. // [ L ]
  101128. // / \
  101129. // [ N ] [L-R]
  101130. // / \ / \
  101131. // [L-L] [ R ] [...] [...]
  101132. // fix bounds and heights
  101133. node.aabb.combine(ll.aabb, r.aabb);
  101134. t = llh - rh;
  101135. node.height = llh - (t & t >> 31) + 1;
  101136. l.aabb.combine(node.aabb, lr.aabb);
  101137. t = nh - lrh;
  101138. l.height = nh - (t & t >> 31) + 1;
  101139. }
  101140. // set new parent of L
  101141. if (p != null) {
  101142. if (p.child1 == node) {
  101143. p.child1 = l;
  101144. } else {
  101145. p.child2 = l;
  101146. }
  101147. } else {
  101148. this.root = l;
  101149. }
  101150. l.parent = p;
  101151. return l;
  101152. } else if (balance < -1) {
  101153. var rl = r.child1;
  101154. var rr = r.child2;
  101155. var rlh = rl.height;
  101156. var rrh = rr.height;
  101157. // Is R-L higher than R-R?
  101158. if (rlh > rrh) {
  101159. // set N to R-R
  101160. r.child2 = node;
  101161. node.parent = r;
  101162. // [ R ]
  101163. // / \
  101164. // [R-L] [ N ]
  101165. // / \ / \
  101166. // [...] [...] [ L ] [ R ]
  101167. // set R-R
  101168. node.child2 = rr;
  101169. rr.parent = node;
  101170. // [ R ]
  101171. // / \
  101172. // [R-L] [ N ]
  101173. // / \ / \
  101174. // [...] [...] [ L ] [R-R]
  101175. // fix bounds and heights
  101176. node.aabb.combine(l.aabb, rr.aabb);
  101177. t = lh - rrh;
  101178. node.height = lh - (t & t >> 31) + 1;
  101179. r.aabb.combine(rl.aabb, node.aabb);
  101180. t = rlh - nh;
  101181. r.height = rlh - (t & t >> 31) + 1;
  101182. } else {
  101183. // set N to R-L
  101184. r.child1 = node;
  101185. node.parent = r;
  101186. // [ R ]
  101187. // / \
  101188. // [ N ] [R-R]
  101189. // / \ / \
  101190. // [ L ] [ R ] [...] [...]
  101191. // set R-L
  101192. node.child2 = rl;
  101193. rl.parent = node;
  101194. // [ R ]
  101195. // / \
  101196. // [ N ] [R-R]
  101197. // / \ / \
  101198. // [ L ] [R-L] [...] [...]
  101199. // fix bounds and heights
  101200. node.aabb.combine(l.aabb, rl.aabb);
  101201. t = lh - rlh;
  101202. node.height = lh - (t & t >> 31) + 1;
  101203. r.aabb.combine(node.aabb, rr.aabb);
  101204. t = nh - rrh;
  101205. r.height = nh - (t & t >> 31) + 1;
  101206. }
  101207. // set new parent of R
  101208. if (p != null) {
  101209. if (p.child1 == node) {
  101210. p.child1 = r;
  101211. } else {
  101212. p.child2 = r;
  101213. }
  101214. } else {
  101215. this.root = r;
  101216. }
  101217. r.parent = p;
  101218. return r;
  101219. }
  101220. return node;
  101221. },
  101222. fix: function (node) {
  101223. var c1 = node.child1;
  101224. var c2 = node.child2;
  101225. node.aabb.combine(c1.aabb, c2.aabb);
  101226. //var h1 = c1.height;
  101227. //var h2 = c2.height;
  101228. node.height = c1.height < c2.height ? c2.height + 1 : c1.height + 1;
  101229. /*if( h1 < h2 ) {
  101230. node.height = h2+1;
  101231. }else{
  101232. node.height = h1+1;
  101233. }*/
  101234. }
  101235. }
  101236. /**
  101237. * A broad-phase algorithm using dynamic bounding volume tree.
  101238. * @author saharan
  101239. * @author lo-th
  101240. */
  101241. OIMO.DBVTBroadPhase = function () {
  101242. OIMO.BroadPhase.call(this);
  101243. this.types = OIMO.BR_BOUNDING_VOLUME_TREE;
  101244. this.tree = new OIMO.DBVT();
  101245. this.stack = [];
  101246. this.leaves = [];
  101247. this.numLeaves = 0;
  101248. };
  101249. OIMO.DBVTBroadPhase.prototype = Object.create(OIMO.BroadPhase.prototype);
  101250. OIMO.DBVTBroadPhase.prototype.constructor = OIMO.DBVTBroadPhase;
  101251. OIMO.DBVTBroadPhase.prototype.createProxy = function (shape) {
  101252. return new OIMO.DBVTProxy(shape);
  101253. };
  101254. OIMO.DBVTBroadPhase.prototype.addProxy = function (proxy) {
  101255. this.tree.insertLeaf(proxy.leaf);
  101256. this.leaves.push(proxy.leaf);
  101257. this.numLeaves++;
  101258. };
  101259. OIMO.DBVTBroadPhase.prototype.removeProxy = function (proxy) {
  101260. this.tree.deleteLeaf(proxy.leaf);
  101261. var n = this.leaves.indexOf(proxy.leaf);
  101262. if (n > -1) {
  101263. this.leaves.splice(n, 1);
  101264. this.numLeaves--;
  101265. }
  101266. };
  101267. OIMO.DBVTBroadPhase.prototype.collectPairs = function () {
  101268. if (this.numLeaves < 2) return;
  101269. var leaf, margin = 0.1, i = this.numLeaves;
  101270. while (i--) {
  101271. leaf = this.leaves[i];
  101272. if (leaf.proxy.aabb.intersectTestTwo(leaf.aabb)) {
  101273. leaf.aabb.copy(leaf.proxy.aabb, margin);
  101274. this.tree.deleteLeaf(leaf);
  101275. this.tree.insertLeaf(leaf);
  101276. this.collide(leaf, this.tree.root);
  101277. }
  101278. }
  101279. };
  101280. OIMO.DBVTBroadPhase.prototype.collide = function (node1, node2) {
  101281. var stackCount = 2;
  101282. var s1, s2, n1, n2, l1, l2;
  101283. this.stack[0] = node1;
  101284. this.stack[1] = node2;
  101285. while (stackCount > 0) {
  101286. n1 = this.stack[--stackCount];
  101287. n2 = this.stack[--stackCount];
  101288. l1 = n1.proxy != null;
  101289. l2 = n2.proxy != null;
  101290. this.numPairChecks++;
  101291. if (l1 && l2) {
  101292. s1 = n1.proxy.shape;
  101293. s2 = n2.proxy.shape;
  101294. if (s1 == s2 || s1.aabb.intersectTest(s2.aabb) || !this.isAvailablePair(s1, s2)) continue;
  101295. this.addPair(s1, s2);
  101296. } else {
  101297. if (n1.aabb.intersectTest(n2.aabb)) continue;
  101298. /*if(stackCount+4>=this.maxStack){// expand the stack
  101299. //this.maxStack<<=1;
  101300. this.maxStack*=2;
  101301. var newStack = [];// vector
  101302. newStack.length = this.maxStack;
  101303. for(var i=0;i<stackCount;i++){
  101304. newStack[i] = this.stack[i];
  101305. }
  101306. this.stack = newStack;
  101307. }*/
  101308. if (l2 || !l1 && (n1.aabb.surfaceArea() > n2.aabb.surfaceArea())) {
  101309. this.stack[stackCount++] = n1.child1;
  101310. this.stack[stackCount++] = n2;
  101311. this.stack[stackCount++] = n1.child2;
  101312. this.stack[stackCount++] = n2;
  101313. } else {
  101314. this.stack[stackCount++] = n1;
  101315. this.stack[stackCount++] = n2.child1;
  101316. this.stack[stackCount++] = n1;
  101317. this.stack[stackCount++] = n2.child2;
  101318. }
  101319. }
  101320. }
  101321. };
  101322. /**
  101323. * A node of the dynamic bounding volume tree.
  101324. * @author saharan
  101325. */
  101326. OIMO.DBVTNode = function () {
  101327. // The first child node of this node.
  101328. this.child1 = null;
  101329. // The second child node of this node.
  101330. this.child2 = null;
  101331. // The parent node of this tree.
  101332. this.parent = null;
  101333. // The proxy of this node. This has no value if this node is not leaf.
  101334. this.proxy = null;
  101335. // The maximum distance from leaf nodes.
  101336. this.height = 0;
  101337. // The AABB of this node.
  101338. this.aabb = new OIMO.AABB();
  101339. };
  101340. /**
  101341. * A proxy for dynamic bounding volume tree broad-phase.
  101342. * @author saharan
  101343. */
  101344. OIMO.DBVTProxy = function (shape) {
  101345. OIMO.Proxy.call(this, shape);
  101346. // The leaf of the proxy.
  101347. this.leaf = new OIMO.DBVTNode();
  101348. this.leaf.proxy = this;
  101349. };
  101350. OIMO.DBVTProxy.prototype = Object.create(OIMO.Proxy.prototype);
  101351. OIMO.DBVTProxy.prototype.constructor = OIMO.DBVTProxy;
  101352. OIMO.DBVTProxy.prototype.update = function () {
  101353. };
  101354. OIMO.World.prototype.add = function (obj) {
  101355. obj = obj || {};
  101356. var type = obj.type || "box";
  101357. if (typeof type === 'string') type = [type];// single shape
  101358. if (type[0].substring(0, 5) == 'joint') { // is joint
  101359. if (type[0] === 'joint') type[0] = 'jointHinge';
  101360. var axe1 = obj.axe1 || [1, 0, 0];
  101361. var axe2 = obj.axe2 || [1, 0, 0];
  101362. var pos1 = obj.pos1 || [0, 0, 0];
  101363. var pos2 = obj.pos2 || [0, 0, 0];
  101364. pos1 = pos1.map(function (x) { return x * OIMO.INV_SCALE; });
  101365. pos2 = pos2.map(function (x) { return x * OIMO.INV_SCALE; });
  101366. var min, max;
  101367. if (type[0] === "jointDistance") {
  101368. min = obj.min || 0;
  101369. max = obj.max || 10;
  101370. min = min * OIMO.INV_SCALE;
  101371. max = max * OIMO.INV_SCALE;
  101372. } else {
  101373. min = obj.min || 57.29578;
  101374. max = obj.max || 0;
  101375. min = min * OIMO.degtorad;
  101376. max = max * OIMO.degtorad;
  101377. }
  101378. var limit = obj.limit || null;
  101379. var spring = obj.spring || null;
  101380. var motor = obj.motor || null;
  101381. // joint setting
  101382. var jc = new OIMO.JointConfig();
  101383. jc.allowCollision = obj.collision || false;;
  101384. jc.localAxis1.init(axe1[0], axe1[1], axe1[2]);
  101385. jc.localAxis2.init(axe2[0], axe2[1], axe2[2]);
  101386. jc.localAnchorPoint1.init(pos1[0], pos1[1], pos1[2]);
  101387. jc.localAnchorPoint2.init(pos2[0], pos2[1], pos2[2]);
  101388. if (typeof obj.body1 == 'string' || obj.body1 instanceof String) obj.body1 = this.getByName(obj.body1);
  101389. if (typeof obj.body2 == 'string' || obj.body2 instanceof String) obj.body2 = this.getByName(obj.body2);
  101390. jc.body1 = obj.body1;
  101391. jc.body2 = obj.body2;
  101392. var joint;
  101393. switch (type[0]) {
  101394. case "jointDistance": joint = new OIMO.DistanceJoint(jc, min, max);
  101395. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);
  101396. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  101397. break;
  101398. case "jointHinge": joint = new OIMO.HingeJoint(jc, min, max);
  101399. if (spring !== null) joint.limitMotor.setSpring(spring[0], spring[1]);// soften the joint ex: 100, 0.2
  101400. if (motor !== null) joint.limitMotor.setSpring(motor[0], motor[1]);
  101401. break;
  101402. case "jointPrisme": joint = new OIMO.PrismaticJoint(jc, min, max); break;
  101403. case "jointSlide": joint = new OIMO.SliderJoint(jc, min, max); break;
  101404. case "jointBall": joint = new OIMO.BallAndSocketJoint(jc); break;
  101405. case "jointWheel": joint = new OIMO.WheelJoint(jc);
  101406. if (limit !== null) joint.rotationalLimitMotor1.setLimit(limit[0], limit[1]);
  101407. if (spring !== null) joint.rotationalLimitMotor1.setSpring(spring[0], spring[1]);
  101408. if (motor !== null) joint.rotationalLimitMotor1.setSpring(motor[0], motor[1]);
  101409. break;
  101410. }
  101411. joint.name = obj.name || '';
  101412. // finaly add to physics world
  101413. this.addJoint(joint);
  101414. return joint;
  101415. } else { // is body
  101416. // I'm dynamique or not
  101417. var move = obj.move || false;
  101418. // I can sleep or not
  101419. var noSleep = obj.noSleep || false;
  101420. // My start position
  101421. var p = obj.pos || [0, 0, 0];
  101422. p = p.map(function (x) { return x * OIMO.INV_SCALE; });
  101423. // My size
  101424. var s = obj.size || [1, 1, 1];
  101425. s = s.map(function (x) { return x * OIMO.INV_SCALE; });
  101426. // My rotation in degre
  101427. var rot = obj.rot || [0, 0, 0];
  101428. rot = rot.map(function (x) { return x * OIMO.degtorad; });
  101429. var r = [];
  101430. for (var i = 0; i < rot.length / 3; i++) {
  101431. var tmp = OIMO.EulerToAxis(rot[i + 0], rot[i + 1], rot[i + 2]);
  101432. r.push(tmp[0]); r.push(tmp[1]); r.push(tmp[2]); r.push(tmp[3]);
  101433. }
  101434. // My physics setting
  101435. var sc = new OIMO.ShapeConfig();
  101436. if (obj.sc !== undefined) sc = obj.sc;
  101437. if (obj.config) {
  101438. // The density of the shape.
  101439. sc.density = obj.config[0] === undefined ? 1 : obj.config[0];
  101440. // The coefficient of friction of the shape.
  101441. sc.friction = obj.config[1] === undefined ? 0.4 : obj.config[1];
  101442. // The coefficient of restitution of the shape.
  101443. sc.restitution = obj.config[2] === undefined ? 0.2 : obj.config[2];
  101444. // The bits of the collision groups to which the shape belongs.
  101445. sc.belongsTo = obj.config[3] || 1;
  101446. //sc.belongsTo = obj.config[3] === undefined ? 1 : obj.config[3];
  101447. // The bits of the collision groups with which the shape collides.
  101448. sc.collidesWith = obj.config[4] || 0xffffffff;
  101449. //sc.collidesWith = obj.config[4] === undefined ? 0xffffffff : obj.config[4];
  101450. }
  101451. // direct physics setting
  101452. if (obj.density !== undefined) sc.density = obj.density;
  101453. if (obj.friction !== undefined) sc.friction = obj.friction;
  101454. if (obj.restitution !== undefined) sc.restitution = obj.restitution;
  101455. if (obj.belongsTo !== undefined) sc.belongsTo = obj.belongsTo;
  101456. if (obj.collidesWith !== undefined) sc.collidesWith = obj.collidesWith;
  101457. if (obj.massPos) {
  101458. obj.massPos = obj.massPos.map(function (x) { return x * OIMO.INV_SCALE; });
  101459. sc.relativePosition.init(obj.massPos[0], obj.massPos[1], obj.massPos[2]);
  101460. }
  101461. if (obj.massRot) {
  101462. obj.massRot = obj.massRot.map(function (x) { return x * OIMO.degtorad; });
  101463. sc.relativeRotation = OIMO.EulerToMatrix(obj.massRot[0], obj.massRot[1], obj.massRot[2]);
  101464. }
  101465. // My rigidbody
  101466. var body = new OIMO.RigidBody(p[0], p[1], p[2], r[0], r[1], r[2], r[3]);
  101467. // My shapes
  101468. var shapes = [];
  101469. //if( typeof type === 'string' ) type = [type];// single shape
  101470. var n, n2;
  101471. for (var i = 0; i < type.length; i++) {
  101472. n = i * 3;
  101473. n2 = i * 4;
  101474. switch (type[i]) {
  101475. case "sphere": shapes[i] = new OIMO.SphereShape(sc, s[n]); break;
  101476. case "cylinder": shapes[i] = new OIMO.CylinderShape(sc, s[n], s[n + 1]); break;
  101477. case "box": shapes[i] = new OIMO.BoxShape(sc, s[n], s[n + 1], s[n + 2]); break;
  101478. }
  101479. body.addShape(shapes[i]);
  101480. if (i > 0) {
  101481. //shapes[i].position.init(p[0]+p[n+0], p[1]+p[n+1], p[2]+p[n+2] );
  101482. shapes[i].relativePosition = new OIMO.Vec3(p[n], p[n + 1], p[n + 2]);
  101483. if (r[n2 + 0]) shapes[i].relativeRotation = [r[n2], r[n2 + 1], r[n2 + 2], r[n2 + 3]];
  101484. }
  101485. }
  101486. // I'm static or i move
  101487. if (move) {
  101488. if (obj.massPos || obj.massRot) body.setupMass(0x1, false);
  101489. else body.setupMass(0x1, true);
  101490. if (noSleep) body.allowSleep = false;
  101491. else body.allowSleep = true;
  101492. } else {
  101493. body.setupMass(0x2);
  101494. }
  101495. body.name = obj.name || ' ';
  101496. // finaly add to physics world
  101497. this.addRigidBody(body);
  101498. return body;
  101499. }
  101500. }
  101501. //UMD simplified
  101502. var root = this;
  101503. if (!root['OIMO']) {
  101504. if (true)
  101505. module.exports = OIMO;
  101506. else if (typeof define === 'function' && define.amd)
  101507. define([], function () {
  101508. return OIMO;
  101509. });
  101510. else if (typeof exports === 'object')
  101511. exports["OIMO"] = OIMO;
  101512. else {
  101513. root["OIMO"] = OIMO;
  101514. }
  101515. }
  101516. /***/ }),
  101517. /* 19 */
  101518. /***/ (function(module, exports, __webpack_require__) {
  101519. "use strict";
  101520. Object.defineProperty(exports, "__esModule", { value: true });
  101521. var babylonjs_1 = __webpack_require__(0);
  101522. var helper_1 = __webpack_require__(3);
  101523. var TemplateManager = (function () {
  101524. function TemplateManager(containerElement) {
  101525. this.containerElement = containerElement;
  101526. this.templates = {};
  101527. this.onInit = new babylonjs_1.Observable();
  101528. this.onLoaded = new babylonjs_1.Observable();
  101529. this.onStateChange = new babylonjs_1.Observable();
  101530. this.onAllLoaded = new babylonjs_1.Observable();
  101531. this.onEventTriggered = new babylonjs_1.Observable();
  101532. this.eventManager = new eventManager_1.EventManager(this);
  101533. }
  101534. TemplateManager.prototype.initTemplate = function (templates) {
  101535. var _this = this;
  101536. var internalInit = function (dependencyMap, name, parentTemplate) {
  101537. var template = _this.templates[name];
  101538. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  101539. return internalInit(dependencyMap[childName], childName, template);
  101540. });
  101541. var addToParent = function () {
  101542. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  101543. template.appendTo(containingElement);
  101544. _this.checkLoadedState();
  101545. };
  101546. if (parentTemplate && !parentTemplate.parent) {
  101547. parentTemplate.onAppended.add(function () {
  101548. addToParent();
  101549. });
  101550. }
  101551. else {
  101552. addToParent();
  101553. }
  101554. return template;
  101555. };
  101556. return this.buildHTMLTree(templates).then(function (htmlTree) {
  101557. if (_this.templates['main']) {
  101558. internalInit(htmlTree, 'main');
  101559. }
  101560. else {
  101561. _this.checkLoadedState();
  101562. }
  101563. return;
  101564. });
  101565. };
  101566. TemplateManager.prototype.buildHTMLTree = function (templates) {
  101567. var _this = this;
  101568. var promises = Object.keys(templates).map(function (name) {
  101569. if (!templates[name])
  101570. return Promise.resolve(false);
  101571. var template = new Template(name, templates[name]);
  101572. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  101573. _this.templates[name] = template;
  101574. return template.initPromise;
  101575. });
  101576. return Promise.all(promises).then(function () {
  101577. var templateStructure = {};
  101578. var buildTree = function (parentObject, name) {
  101579. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  101580. childNodes.forEach(function (element) {
  101581. parentObject[element] = {};
  101582. buildTree(parentObject[element], element);
  101583. });
  101584. };
  101585. if (_this.templates['main']) {
  101586. buildTree(templateStructure, "main");
  101587. }
  101588. return templateStructure;
  101589. });
  101590. };
  101591. TemplateManager.prototype.getCanvas = function () {
  101592. return this.containerElement.querySelector('canvas');
  101593. };
  101594. TemplateManager.prototype.getTemplate = function (name) {
  101595. return this.templates[name];
  101596. };
  101597. TemplateManager.prototype.checkLoadedState = function () {
  101598. var _this = this;
  101599. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  101600. return _this.templates[key].isLoaded && !!_this.templates[key].parent;
  101601. });
  101602. if (done) {
  101603. this.onAllLoaded.notifyObservers(this);
  101604. }
  101605. };
  101606. TemplateManager.prototype.dispose = function () {
  101607. var _this = this;
  101608. Object.keys(this.templates).forEach(function (template) {
  101609. _this.templates[template].dispose();
  101610. });
  101611. this.onInit.clear();
  101612. this.onAllLoaded.clear();
  101613. this.onEventTriggered.clear();
  101614. this.onLoaded.clear();
  101615. this.onStateChange.clear();
  101616. };
  101617. return TemplateManager;
  101618. }());
  101619. exports.TemplateManager = TemplateManager;
  101620. var Handlebars = __webpack_require__(20);
  101621. var eventManager_1 = __webpack_require__(21);
  101622. Handlebars.registerHelper('eachInMap', function (map, block) {
  101623. var out = '';
  101624. Object.keys(map).map(function (prop) {
  101625. var data = map[prop];
  101626. if (typeof data === 'object') {
  101627. data.id = data.id || prop;
  101628. out += block.fn(data);
  101629. }
  101630. else {
  101631. out += block.fn({ id: prop, value: data });
  101632. }
  101633. });
  101634. return out;
  101635. });
  101636. var Template = (function () {
  101637. function Template(name, _configuration) {
  101638. var _this = this;
  101639. this.name = name;
  101640. this._configuration = _configuration;
  101641. this.onInit = new babylonjs_1.Observable();
  101642. this.onLoaded = new babylonjs_1.Observable();
  101643. this.onAppended = new babylonjs_1.Observable();
  101644. this.onStateChange = new babylonjs_1.Observable();
  101645. this.onEventTriggered = new babylonjs_1.Observable();
  101646. this.isLoaded = false;
  101647. this.isShown = false;
  101648. this.onInit.notifyObservers(this);
  101649. var htmlContentPromise = getTemplateAsHtml(_configuration);
  101650. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  101651. if (htmlTemplate) {
  101652. _this.htmlTemplate = htmlTemplate;
  101653. var compiledTemplate = Handlebars.compile(htmlTemplate);
  101654. var config = _this._configuration.params || {};
  101655. var rawHtml = compiledTemplate(config);
  101656. _this.fragment = document.createRange().createContextualFragment(rawHtml);
  101657. _this.isLoaded = true;
  101658. _this.isShown = true;
  101659. _this.onLoaded.notifyObservers(_this);
  101660. }
  101661. return _this;
  101662. });
  101663. }
  101664. Template.prototype.updateParams = function (params) {
  101665. this._configuration.params = params;
  101666. if (this.isLoaded) {
  101667. this.dispose();
  101668. }
  101669. var compiledTemplate = Handlebars.compile(this.htmlTemplate);
  101670. var config = this._configuration.params || {};
  101671. var rawHtml = compiledTemplate(config);
  101672. this.fragment = document.createRange().createContextualFragment(rawHtml);
  101673. if (this.parent) {
  101674. this.appendTo(this.parent, true);
  101675. }
  101676. };
  101677. Object.defineProperty(Template.prototype, "configuration", {
  101678. get: function () {
  101679. return this._configuration;
  101680. },
  101681. enumerable: true,
  101682. configurable: true
  101683. });
  101684. Template.prototype.getChildElements = function () {
  101685. var childrenArray = [];
  101686. var children = this.fragment.children;
  101687. if (!children) {
  101688. children = this.fragment.querySelectorAll('*');
  101689. }
  101690. for (var i = 0; i < children.length; ++i) {
  101691. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  101692. }
  101693. return childrenArray;
  101694. };
  101695. Template.prototype.appendTo = function (parent, forceRemove) {
  101696. var _this = this;
  101697. if (this.parent) {
  101698. if (forceRemove) {
  101699. this.parent.removeChild(this.fragment);
  101700. }
  101701. else {
  101702. return;
  101703. }
  101704. }
  101705. this.parent = parent;
  101706. if (this._configuration.id) {
  101707. this.parent.id = this._configuration.id;
  101708. }
  101709. this.fragment = this.parent.appendChild(this.fragment);
  101710. setTimeout(function () {
  101711. _this.registerEvents();
  101712. _this.onAppended.notifyObservers(_this);
  101713. });
  101714. };
  101715. Template.prototype.show = function (visibilityFunction) {
  101716. var _this = this;
  101717. return Promise.resolve().then(function () {
  101718. if (visibilityFunction) {
  101719. return visibilityFunction(_this);
  101720. }
  101721. else {
  101722. _this.parent.style.display = 'flex';
  101723. return _this;
  101724. }
  101725. }).then(function () {
  101726. _this.isShown = true;
  101727. _this.onStateChange.notifyObservers(_this);
  101728. return _this;
  101729. });
  101730. };
  101731. Template.prototype.hide = function (visibilityFunction) {
  101732. var _this = this;
  101733. return Promise.resolve().then(function () {
  101734. if (visibilityFunction) {
  101735. return visibilityFunction(_this);
  101736. }
  101737. else {
  101738. _this.parent.style.display = 'hide';
  101739. return _this;
  101740. }
  101741. }).then(function () {
  101742. _this.isShown = false;
  101743. _this.onStateChange.notifyObservers(_this);
  101744. return _this;
  101745. });
  101746. };
  101747. Template.prototype.dispose = function () {
  101748. this.onAppended.clear();
  101749. this.onEventTriggered.clear();
  101750. this.onInit.clear();
  101751. this.onLoaded.clear();
  101752. this.onStateChange.clear();
  101753. this.isLoaded = false;
  101754. this.parent.removeChild(this.fragment);
  101755. };
  101756. Template.prototype.registerEvents = function () {
  101757. var _this = this;
  101758. this.registeredEvents = this.registeredEvents || [];
  101759. if (this.registeredEvents.length) {
  101760. this.registeredEvents.forEach(function (evt) {
  101761. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  101762. });
  101763. }
  101764. if (this._configuration.events) {
  101765. var _loop_1 = function (eventName) {
  101766. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  101767. var functionToFire_1 = function (selector, event) {
  101768. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  101769. };
  101770. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  101771. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, '#' + this_1.parent.id), false);
  101772. }
  101773. else if (typeof this_1._configuration.events[eventName] === 'object') {
  101774. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  101775. var event_1 = this_1._configuration.events[eventName] || {};
  101776. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  101777. if (selector && selector.indexOf('#') !== 0) {
  101778. selector = '#' + selector;
  101779. }
  101780. var htmlElement = _this.parent.querySelector(selector);
  101781. if (htmlElement) {
  101782. var binding = functionToFire_1.bind(_this, selector);
  101783. htmlElement.addEventListener(eventName, binding, false);
  101784. _this.registeredEvents.push({
  101785. htmlElement: htmlElement,
  101786. eventName: eventName,
  101787. function: binding
  101788. });
  101789. }
  101790. });
  101791. }
  101792. }
  101793. };
  101794. var this_1 = this;
  101795. for (var eventName in this._configuration.events) {
  101796. _loop_1(eventName);
  101797. }
  101798. }
  101799. };
  101800. return Template;
  101801. }());
  101802. exports.Template = Template;
  101803. function getTemplateAsHtml(templateConfig) {
  101804. if (!templateConfig) {
  101805. return Promise.reject('No templateConfig provided');
  101806. }
  101807. else if (templateConfig.html) {
  101808. return Promise.resolve(templateConfig.html);
  101809. }
  101810. else {
  101811. var location_1 = getTemplateLocation(templateConfig);
  101812. if (helper_1.isUrl(location_1)) {
  101813. return helper_1.loadFile(location_1);
  101814. }
  101815. else {
  101816. location_1 = location_1.replace('#', '');
  101817. var element = document.getElementById(location_1);
  101818. if (element) {
  101819. return Promise.resolve(element.innerHTML);
  101820. }
  101821. else {
  101822. return Promise.reject('Template ID not found');
  101823. }
  101824. }
  101825. }
  101826. }
  101827. exports.getTemplateAsHtml = getTemplateAsHtml;
  101828. function getTemplateLocation(templateConfig) {
  101829. if (!templateConfig || typeof templateConfig === 'string') {
  101830. return templateConfig;
  101831. }
  101832. else {
  101833. return templateConfig.location;
  101834. }
  101835. }
  101836. exports.getTemplateLocation = getTemplateLocation;
  101837. /***/ }),
  101838. /* 20 */
  101839. /***/ (function(module, exports, __webpack_require__) {
  101840. /**!
  101841. @license
  101842. handlebars v4.0.11
  101843. Copyright (C) 2011-2017 by Yehuda Katz
  101844. Permission is hereby granted, free of charge, to any person obtaining a copy
  101845. of this software and associated documentation files (the "Software"), to deal
  101846. in the Software without restriction, including without limitation the rights
  101847. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  101848. copies of the Software, and to permit persons to whom the Software is
  101849. furnished to do so, subject to the following conditions:
  101850. The above copyright notice and this permission notice shall be included in
  101851. all copies or substantial portions of the Software.
  101852. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  101853. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  101854. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  101855. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  101856. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  101857. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  101858. THE SOFTWARE.
  101859. */
  101860. !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],
  101861. 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){
  101862. 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"]}])});
  101863. /***/ }),
  101864. /* 21 */
  101865. /***/ (function(module, exports, __webpack_require__) {
  101866. "use strict";
  101867. Object.defineProperty(exports, "__esModule", { value: true });
  101868. var EventManager = (function () {
  101869. function EventManager(templateManager) {
  101870. var _this = this;
  101871. this.templateManager = templateManager;
  101872. this.callbacksContainer = {};
  101873. this.templateManager.onEventTriggered.add(function (eventData) {
  101874. _this.eventTriggered(eventData);
  101875. });
  101876. }
  101877. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  101878. if (!this.callbacksContainer[templateName]) {
  101879. this.callbacksContainer[templateName] = [];
  101880. }
  101881. this.callbacksContainer[templateName].push({
  101882. eventType: eventType,
  101883. callback: callback
  101884. });
  101885. };
  101886. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  101887. var callbackDefs = this.callbacksContainer[templateName] || [];
  101888. this.callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  101889. };
  101890. EventManager.prototype.eventTriggered = function (data) {
  101891. var templateName = data.template.name;
  101892. var eventType = data.event.type;
  101893. var selector = data.selector;
  101894. var callbackDefs = this.callbacksContainer[templateName] || [];
  101895. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  101896. callbackDef.callback(data);
  101897. });
  101898. };
  101899. return EventManager;
  101900. }());
  101901. exports.EventManager = EventManager;
  101902. /***/ }),
  101903. /* 22 */
  101904. /***/ (function(module, exports, __webpack_require__) {
  101905. "use strict";
  101906. Object.defineProperty(exports, "__esModule", { value: true });
  101907. var mappers_1 = __webpack_require__(1);
  101908. var types_1 = __webpack_require__(23);
  101909. var deepmerge = __webpack_require__(14);
  101910. var ConfigurationLoader = (function () {
  101911. function ConfigurationLoader() {
  101912. this.configurationCache = {};
  101913. }
  101914. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  101915. var _this = this;
  101916. if (initConfig === void 0) { initConfig = {}; }
  101917. var loadedConfig = deepmerge({}, initConfig);
  101918. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  101919. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  101920. if (loadedConfig.configuration) {
  101921. var mapperType_1 = "json";
  101922. return Promise.resolve().then(function () {
  101923. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  101924. var url = '';
  101925. if (typeof loadedConfig.configuration === "string") {
  101926. url = loadedConfig.configuration;
  101927. }
  101928. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  101929. url = loadedConfig.configuration.url;
  101930. var type = loadedConfig.configuration.mapper;
  101931. if (!type) {
  101932. type = loadedConfig.configuration.url.split('.').pop();
  101933. }
  101934. mapperType_1 = type || mapperType_1;
  101935. }
  101936. return _this.loadFile(url);
  101937. }
  101938. else {
  101939. if (typeof loadedConfig.configuration === "object") {
  101940. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  101941. return loadedConfig.configuration.payload || {};
  101942. }
  101943. return {};
  101944. }
  101945. }).then(function (data) {
  101946. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  101947. var parsed = mapper.map(data);
  101948. var merged = deepmerge(loadedConfig, parsed);
  101949. if (callback)
  101950. callback(merged);
  101951. return merged;
  101952. });
  101953. }
  101954. else {
  101955. if (callback)
  101956. callback(loadedConfig);
  101957. return Promise.resolve(loadedConfig);
  101958. }
  101959. };
  101960. ConfigurationLoader.prototype.loadFile = function (url) {
  101961. var cacheReference = this.configurationCache;
  101962. if (cacheReference[url]) {
  101963. return Promise.resolve(cacheReference[url]);
  101964. }
  101965. return new Promise(function (resolve, reject) {
  101966. var xhr = new XMLHttpRequest();
  101967. xhr.open('GET', url);
  101968. xhr.send();
  101969. xhr.onreadystatechange = function () {
  101970. var DONE = 4;
  101971. var OK = 200;
  101972. if (xhr.readyState === DONE) {
  101973. if (xhr.status === OK) {
  101974. cacheReference[url] = xhr.responseText;
  101975. resolve(xhr.responseText);
  101976. }
  101977. else {
  101978. console.log('Error: ' + xhr.status, url);
  101979. reject('Error: ' + xhr.status);
  101980. }
  101981. }
  101982. };
  101983. });
  101984. };
  101985. return ConfigurationLoader;
  101986. }());
  101987. exports.ConfigurationLoader = ConfigurationLoader;
  101988. exports.configurationLoader = new ConfigurationLoader();
  101989. exports.default = exports.configurationLoader;
  101990. /***/ }),
  101991. /* 23 */
  101992. /***/ (function(module, exports, __webpack_require__) {
  101993. "use strict";
  101994. Object.defineProperty(exports, "__esModule", { value: true });
  101995. var minimal_1 = __webpack_require__(24);
  101996. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  101997. var default_1 = __webpack_require__(25);
  101998. exports.defaultConfiguration = default_1.defaultConfiguration;
  101999. var getConfigurationType = function (type) {
  102000. switch (type) {
  102001. case 'default':
  102002. return default_1.defaultConfiguration;
  102003. case 'minimal':
  102004. return minimal_1.minimalConfiguration;
  102005. case 'none':
  102006. return {};
  102007. default:
  102008. return default_1.defaultConfiguration;
  102009. }
  102010. };
  102011. exports.getConfigurationType = getConfigurationType;
  102012. /***/ }),
  102013. /* 24 */
  102014. /***/ (function(module, exports, __webpack_require__) {
  102015. "use strict";
  102016. Object.defineProperty(exports, "__esModule", { value: true });
  102017. exports.minimalConfiguration = {
  102018. version: "0.1",
  102019. templates: {
  102020. main: {
  102021. html: __webpack_require__(7)
  102022. },
  102023. loadingScreen: {
  102024. html: __webpack_require__(8),
  102025. params: {
  102026. backgroundColor: "#000000",
  102027. loadingImage: __webpack_require__(9)
  102028. }
  102029. },
  102030. viewer: {
  102031. html: __webpack_require__(10),
  102032. },
  102033. overlay: {
  102034. html: __webpack_require__(11),
  102035. params: {
  102036. closeImage: __webpack_require__(12),
  102037. closeText: 'Close'
  102038. }
  102039. },
  102040. error: {
  102041. html: __webpack_require__(13)
  102042. }
  102043. },
  102044. engine: {
  102045. antialiasing: true
  102046. }
  102047. };
  102048. /***/ }),
  102049. /* 25 */
  102050. /***/ (function(module, exports, __webpack_require__) {
  102051. "use strict";
  102052. Object.defineProperty(exports, "__esModule", { value: true });
  102053. exports.defaultConfiguration = {
  102054. version: "3.2.0-alpha4",
  102055. templates: {
  102056. main: {
  102057. html: __webpack_require__(7)
  102058. },
  102059. loadingScreen: {
  102060. html: __webpack_require__(8),
  102061. params: {
  102062. backgroundColor: "#000000",
  102063. loadingImage: __webpack_require__(9)
  102064. }
  102065. },
  102066. viewer: {
  102067. html: __webpack_require__(10),
  102068. events: {
  102069. pointerout: true,
  102070. pointerdown: true,
  102071. pointerup: true
  102072. }
  102073. },
  102074. navBar: {
  102075. html: __webpack_require__(26),
  102076. params: {
  102077. buttons: {
  102078. "fullscreen-button": {
  102079. altText: "Fullscreen",
  102080. image: __webpack_require__(27)
  102081. }
  102082. },
  102083. visibilityTimeout: 2000
  102084. },
  102085. events: {
  102086. pointerdown: { 'fullscreen-button': true },
  102087. pointerover: true
  102088. }
  102089. },
  102090. overlay: {
  102091. html: __webpack_require__(11),
  102092. params: {
  102093. closeImage: __webpack_require__(12),
  102094. closeText: 'Close'
  102095. }
  102096. },
  102097. help: {
  102098. html: __webpack_require__(28)
  102099. },
  102100. share: {
  102101. html: __webpack_require__(29)
  102102. },
  102103. error: {
  102104. html: __webpack_require__(13)
  102105. }
  102106. },
  102107. camera: {
  102108. behaviors: {
  102109. autoRotate: 0,
  102110. framing: {
  102111. type: 2,
  102112. zoomOnBoundingInfo: true,
  102113. zoomStopsAnimation: false
  102114. }
  102115. }
  102116. },
  102117. skybox: {
  102118. pbr: true,
  102119. blur: 0.7,
  102120. infiniteDIstance: false,
  102121. },
  102122. ground: true,
  102123. engine: {
  102124. antialiasing: true
  102125. },
  102126. scene: {
  102127. imageProcessingConfiguration: {
  102128. exposure: 1.4,
  102129. contrast: 1.66,
  102130. toneMappingEnabled: true
  102131. }
  102132. }
  102133. };
  102134. /***/ }),
  102135. /* 26 */
  102136. /***/ (function(module, exports) {
  102137. 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>";
  102138. /***/ }),
  102139. /* 27 */
  102140. /***/ (function(module, exports) {
  102141. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  102142. /***/ }),
  102143. /* 28 */
  102144. /***/ (function(module, exports) {
  102145. module.exports = "HELP";
  102146. /***/ }),
  102147. /* 29 */
  102148. /***/ (function(module, exports) {
  102149. module.exports = "SHARE";
  102150. /***/ }),
  102151. /* 30 */
  102152. /***/ (function(module, exports, __webpack_require__) {
  102153. /* WEBPACK VAR INJECTION */(function(global) {var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  102154. var babylonDependency = (globalObject && globalObject.BABYLON) || BABYLON || ("function" !== 'undefined' && __webpack_require__(0));
  102155. var BABYLON = babylonDependency;
  102156. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  102157. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  102158. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  102159. 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;
  102160. return c > 3 && r && Object.defineProperty(target, key, r), r;
  102161. };
  102162. var __extends = (this && this.__extends) || (function () {
  102163. var extendStatics = Object.setPrototypeOf ||
  102164. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  102165. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  102166. return function (d, b) {
  102167. extendStatics(d, b);
  102168. function __() { this.constructor = d; }
  102169. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  102170. };
  102171. })();
  102172. var BABYLON;
  102173. (function (BABYLON) {
  102174. var STLFileLoader = /** @class */ (function () {
  102175. function STLFileLoader() {
  102176. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  102177. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  102178. 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;
  102179. 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;
  102180. this.name = "stl";
  102181. // force data to come in as an ArrayBuffer
  102182. // we'll convert to string if it looks like it's an ASCII .stl
  102183. this.extensions = {
  102184. ".stl": { isBinary: true },
  102185. };
  102186. }
  102187. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  102188. var matches;
  102189. if (this.isBinary(data)) {
  102190. // binary .stl
  102191. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  102192. this.parseBinary(babylonMesh, data);
  102193. if (meshes) {
  102194. meshes.push(babylonMesh);
  102195. }
  102196. return true;
  102197. }
  102198. // ASCII .stl
  102199. // convert to string
  102200. var array_buffer = new Uint8Array(data);
  102201. var str = '';
  102202. for (var i = 0; i < data.byteLength; i++) {
  102203. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  102204. }
  102205. data = str;
  102206. while (matches = this.solidPattern.exec(data)) {
  102207. var meshName = matches[1];
  102208. var meshNameFromEnd = matches[3];
  102209. if (meshName != meshNameFromEnd) {
  102210. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  102211. return false;
  102212. }
  102213. // check meshesNames
  102214. if (meshesNames && meshName) {
  102215. if (meshesNames instanceof Array) {
  102216. if (!meshesNames.indexOf(meshName)) {
  102217. continue;
  102218. }
  102219. }
  102220. else {
  102221. if (meshName !== meshesNames) {
  102222. continue;
  102223. }
  102224. }
  102225. }
  102226. // stl mesh name can be empty as well
  102227. meshName = meshName || "stlmesh";
  102228. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  102229. this.parseASCII(babylonMesh, matches[2]);
  102230. if (meshes) {
  102231. meshes.push(babylonMesh);
  102232. }
  102233. }
  102234. return true;
  102235. };
  102236. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  102237. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  102238. if (result) {
  102239. scene.createDefaultCameraOrLight();
  102240. }
  102241. return result;
  102242. };
  102243. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  102244. var container = new BABYLON.AssetContainer(scene);
  102245. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  102246. container.removeAllFromScene();
  102247. return container;
  102248. };
  102249. STLFileLoader.prototype.isBinary = function (data) {
  102250. // check if file size is correct for binary stl
  102251. var faceSize, nFaces, reader;
  102252. reader = new DataView(data);
  102253. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  102254. nFaces = reader.getUint32(80, true);
  102255. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  102256. return true;
  102257. }
  102258. // check characters higher than ASCII to confirm binary
  102259. var fileLength = reader.byteLength;
  102260. for (var index = 0; index < fileLength; index++) {
  102261. if (reader.getUint8(index) > 127) {
  102262. return true;
  102263. }
  102264. }
  102265. return false;
  102266. };
  102267. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  102268. var reader = new DataView(data);
  102269. var faces = reader.getUint32(80, true);
  102270. var dataOffset = 84;
  102271. var faceLength = 12 * 4 + 2;
  102272. var offset = 0;
  102273. var positions = new Float32Array(faces * 3 * 3);
  102274. var normals = new Float32Array(faces * 3 * 3);
  102275. var indices = new Uint32Array(faces * 3);
  102276. var indicesCount = 0;
  102277. for (var face = 0; face < faces; face++) {
  102278. var start = dataOffset + face * faceLength;
  102279. var normalX = reader.getFloat32(start, true);
  102280. var normalY = reader.getFloat32(start + 4, true);
  102281. var normalZ = reader.getFloat32(start + 8, true);
  102282. for (var i = 1; i <= 3; i++) {
  102283. var vertexstart = start + i * 12;
  102284. // ordering is intentional to match ascii import
  102285. positions[offset] = reader.getFloat32(vertexstart, true);
  102286. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  102287. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  102288. normals[offset] = normalX;
  102289. normals[offset + 2] = normalY;
  102290. normals[offset + 1] = normalZ;
  102291. offset += 3;
  102292. }
  102293. indices[indicesCount] = indicesCount++;
  102294. indices[indicesCount] = indicesCount++;
  102295. indices[indicesCount] = indicesCount++;
  102296. }
  102297. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  102298. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  102299. mesh.setIndices(indices);
  102300. mesh.computeWorldMatrix(true);
  102301. };
  102302. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  102303. var positions = [];
  102304. var normals = [];
  102305. var indices = [];
  102306. var indicesCount = 0;
  102307. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  102308. var matches;
  102309. while (matches = this.facetsPattern.exec(solidData)) {
  102310. var facet = matches[1];
  102311. //one normal per face
  102312. var normalMatches = this.normalPattern.exec(facet);
  102313. this.normalPattern.lastIndex = 0;
  102314. if (!normalMatches) {
  102315. continue;
  102316. }
  102317. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  102318. var vertexMatch;
  102319. while (vertexMatch = this.vertexPattern.exec(facet)) {
  102320. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  102321. normals.push(normal[0], normal[1], normal[2]);
  102322. }
  102323. indices.push(indicesCount++, indicesCount++, indicesCount++);
  102324. this.vertexPattern.lastIndex = 0;
  102325. }
  102326. this.facetsPattern.lastIndex = 0;
  102327. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  102328. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  102329. mesh.setIndices(indices);
  102330. mesh.computeWorldMatrix(true);
  102331. };
  102332. return STLFileLoader;
  102333. }());
  102334. BABYLON.STLFileLoader = STLFileLoader;
  102335. if (BABYLON.SceneLoader) {
  102336. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  102337. }
  102338. })(BABYLON || (BABYLON = {}));
  102339. //# sourceMappingURL=babylon.stlFileLoader.js.map
  102340. var BABYLON;
  102341. (function (BABYLON) {
  102342. /**
  102343. * Class reading and parsing the MTL file bundled with the obj file.
  102344. */
  102345. var MTLFileLoader = /** @class */ (function () {
  102346. function MTLFileLoader() {
  102347. // All material loaded from the mtl will be set here
  102348. this.materials = [];
  102349. }
  102350. /**
  102351. * This function will read the mtl file and create each material described inside
  102352. * This function could be improve by adding :
  102353. * -some component missing (Ni, Tf...)
  102354. * -including the specific options available
  102355. *
  102356. * @param scene
  102357. * @param data
  102358. * @param rootUrl
  102359. */
  102360. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  102361. //Split the lines from the file
  102362. var lines = data.split('\n');
  102363. //Space char
  102364. var delimiter_pattern = /\s+/;
  102365. //Array with RGB colors
  102366. var color;
  102367. //New material
  102368. var material = null;
  102369. //Look at each line
  102370. for (var i = 0; i < lines.length; i++) {
  102371. var line = lines[i].trim();
  102372. // Blank line or comment
  102373. if (line.length === 0 || line.charAt(0) === '#') {
  102374. continue;
  102375. }
  102376. //Get the first parameter (keyword)
  102377. var pos = line.indexOf(' ');
  102378. var key = (pos >= 0) ? line.substring(0, pos) : line;
  102379. key = key.toLowerCase();
  102380. //Get the data following the key
  102381. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  102382. //This mtl keyword will create the new material
  102383. if (key === "newmtl") {
  102384. //Check if it is the first material.
  102385. // Materials specifications are described after this keyword.
  102386. if (material) {
  102387. //Add the previous material in the material array.
  102388. this.materials.push(material);
  102389. }
  102390. //Create a new material.
  102391. // value is the name of the material read in the mtl file
  102392. material = new BABYLON.StandardMaterial(value, scene);
  102393. }
  102394. else if (key === "kd" && material) {
  102395. // Diffuse color (color under white light) using RGB values
  102396. //value = "r g b"
  102397. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102398. //color = [r,g,b]
  102399. //Set tghe color into the material
  102400. material.diffuseColor = BABYLON.Color3.FromArray(color);
  102401. }
  102402. else if (key === "ka" && material) {
  102403. // Ambient color (color under shadow) using RGB values
  102404. //value = "r g b"
  102405. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102406. //color = [r,g,b]
  102407. //Set tghe color into the material
  102408. material.ambientColor = BABYLON.Color3.FromArray(color);
  102409. }
  102410. else if (key === "ks" && material) {
  102411. // Specular color (color when light is reflected from shiny surface) using RGB values
  102412. //value = "r g b"
  102413. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102414. //color = [r,g,b]
  102415. //Set the color into the material
  102416. material.specularColor = BABYLON.Color3.FromArray(color);
  102417. }
  102418. else if (key === "ke" && material) {
  102419. // Emissive color using RGB values
  102420. color = value.split(delimiter_pattern, 3).map(parseFloat);
  102421. material.emissiveColor = BABYLON.Color3.FromArray(color);
  102422. }
  102423. else if (key === "ns" && material) {
  102424. //value = "Integer"
  102425. material.specularPower = parseFloat(value);
  102426. }
  102427. else if (key === "d" && material) {
  102428. //d is dissolve for current material. It mean alpha for BABYLON
  102429. material.alpha = parseFloat(value);
  102430. //Texture
  102431. //This part can be improved by adding the possible options of texture
  102432. }
  102433. else if (key === "map_ka" && material) {
  102434. // ambient texture map with a loaded image
  102435. //We must first get the folder of the image
  102436. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102437. }
  102438. else if (key === "map_kd" && material) {
  102439. // Diffuse texture map with a loaded image
  102440. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102441. }
  102442. else if (key === "map_ks" && material) {
  102443. // Specular texture map with a loaded image
  102444. //We must first get the folder of the image
  102445. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102446. }
  102447. else if (key === "map_ns") {
  102448. //Specular
  102449. //Specular highlight component
  102450. //We must first get the folder of the image
  102451. //
  102452. //Not supported by BABYLON
  102453. //
  102454. // continue;
  102455. }
  102456. else if (key === "map_bump" && material) {
  102457. //The bump texture
  102458. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102459. }
  102460. else if (key === "map_d" && material) {
  102461. // The dissolve of the material
  102462. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  102463. //Options for illumination
  102464. }
  102465. else if (key === "illum") {
  102466. //Illumination
  102467. if (value === "0") {
  102468. //That mean Kd == Kd
  102469. }
  102470. else if (value === "1") {
  102471. //Color on and Ambient on
  102472. }
  102473. else if (value === "2") {
  102474. //Highlight on
  102475. }
  102476. else if (value === "3") {
  102477. //Reflection on and Ray trace on
  102478. }
  102479. else if (value === "4") {
  102480. //Transparency: Glass on, Reflection: Ray trace on
  102481. }
  102482. else if (value === "5") {
  102483. //Reflection: Fresnel on and Ray trace on
  102484. }
  102485. else if (value === "6") {
  102486. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  102487. }
  102488. else if (value === "7") {
  102489. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  102490. }
  102491. else if (value === "8") {
  102492. //Reflection on and Ray trace off
  102493. }
  102494. else if (value === "9") {
  102495. //Transparency: Glass on, Reflection: Ray trace off
  102496. }
  102497. else if (value === "10") {
  102498. //Casts shadows onto invisible surfaces
  102499. }
  102500. }
  102501. else {
  102502. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  102503. }
  102504. }
  102505. //At the end of the file, add the last material
  102506. if (material) {
  102507. this.materials.push(material);
  102508. }
  102509. };
  102510. /**
  102511. * Gets the texture for the material.
  102512. *
  102513. * If the material is imported from input file,
  102514. * We sanitize the url to ensure it takes the textre from aside the material.
  102515. *
  102516. * @param rootUrl The root url to load from
  102517. * @param value The value stored in the mtl
  102518. * @return The Texture
  102519. */
  102520. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  102521. if (!value) {
  102522. return null;
  102523. }
  102524. var url = rootUrl;
  102525. // Load from input file.
  102526. if (rootUrl === "file:") {
  102527. var lastDelimiter = value.lastIndexOf("\\");
  102528. if (lastDelimiter === -1) {
  102529. lastDelimiter = value.lastIndexOf("/");
  102530. }
  102531. if (lastDelimiter > -1) {
  102532. url += value.substr(lastDelimiter + 1);
  102533. }
  102534. else {
  102535. url += value;
  102536. }
  102537. }
  102538. else {
  102539. url += value;
  102540. }
  102541. return new BABYLON.Texture(url, scene);
  102542. };
  102543. return MTLFileLoader;
  102544. }());
  102545. BABYLON.MTLFileLoader = MTLFileLoader;
  102546. var OBJFileLoader = /** @class */ (function () {
  102547. function OBJFileLoader() {
  102548. this.name = "obj";
  102549. this.extensions = ".obj";
  102550. this.obj = /^o/;
  102551. this.group = /^g/;
  102552. this.mtllib = /^mtllib /;
  102553. this.usemtl = /^usemtl /;
  102554. this.smooth = /^s /;
  102555. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102556. // vn float float float
  102557. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102558. // vt float float
  102559. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  102560. // f vertex vertex vertex ...
  102561. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  102562. // f vertex/uvs vertex/uvs vertex/uvs ...
  102563. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  102564. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  102565. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  102566. // f vertex//normal vertex//normal vertex//normal ...
  102567. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  102568. }
  102569. /**
  102570. * Calls synchronously the MTL file attached to this obj.
  102571. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  102572. * Without this function materials are not displayed in the first frame (but displayed after).
  102573. * In consequence it is impossible to get material information in your HTML file
  102574. *
  102575. * @param url The URL of the MTL file
  102576. * @param rootUrl
  102577. * @param onSuccess Callback function to be called when the MTL file is loaded
  102578. * @private
  102579. */
  102580. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  102581. //The complete path to the mtl file
  102582. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  102583. // Loads through the babylon tools to allow fileInput search.
  102584. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  102585. };
  102586. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  102587. //get the meshes from OBJ file
  102588. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  102589. //Push meshes from OBJ file into the variable mesh of this function
  102590. if (meshes) {
  102591. loadedMeshes.forEach(function (mesh) {
  102592. meshes.push(mesh);
  102593. });
  102594. }
  102595. return true;
  102596. };
  102597. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  102598. //Get the 3D model
  102599. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  102600. };
  102601. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  102602. var container = new BABYLON.AssetContainer(scene);
  102603. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  102604. container.removeAllFromScene();
  102605. return container;
  102606. };
  102607. /**
  102608. * Read the OBJ file and create an Array of meshes.
  102609. * Each mesh contains all information given by the OBJ and the MTL file.
  102610. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  102611. *
  102612. * @param meshesNames
  102613. * @param scene BABYLON.Scene The scene where are displayed the data
  102614. * @param data String The content of the obj file
  102615. * @param rootUrl String The path to the folder
  102616. * @returns Array<AbstractMesh>
  102617. * @private
  102618. */
  102619. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  102620. var positions = []; //values for the positions of vertices
  102621. var normals = []; //Values for the normals
  102622. var uvs = []; //Values for the textures
  102623. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  102624. var handledMesh; //The current mesh of meshes array
  102625. var indicesForBabylon = []; //The list of indices for VertexData
  102626. var wrappedPositionForBabylon = []; //The list of position in vectors
  102627. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  102628. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  102629. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  102630. var curPositionInIndices = 0;
  102631. var hasMeshes = false; //Meshes are defined in the file
  102632. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  102633. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  102634. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  102635. var triangles = []; //Indices from new triangles coming from polygons
  102636. var materialNameFromObj = ""; //The name of the current material
  102637. var fileToLoad = ""; //The name of the mtlFile to load
  102638. var materialsFromMTLFile = new MTLFileLoader();
  102639. var objMeshName = ""; //The name of the current obj mesh
  102640. var increment = 1; //Id for meshes created by the multimaterial
  102641. var isFirstMaterial = true;
  102642. /**
  102643. * Search for obj in the given array.
  102644. * This function is called to check if a couple of data already exists in an array.
  102645. *
  102646. * If found, returns the index of the founded tuple index. Returns -1 if not found
  102647. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  102648. * @param obj Array<number>
  102649. * @returns {boolean}
  102650. */
  102651. var isInArray = function (arr, obj) {
  102652. if (!arr[obj[0]])
  102653. arr[obj[0]] = { normals: [], idx: [] };
  102654. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  102655. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  102656. };
  102657. var isInArrayUV = function (arr, obj) {
  102658. if (!arr[obj[0]])
  102659. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  102660. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  102661. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  102662. return arr[obj[0]].idx[idx];
  102663. }
  102664. return -1;
  102665. };
  102666. /**
  102667. * This function set the data for each triangle.
  102668. * Data are position, normals and uvs
  102669. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  102670. * If the tuple already exist, add only their indice
  102671. *
  102672. * @param indicePositionFromObj Integer The index in positions array
  102673. * @param indiceUvsFromObj Integer The index in uvs array
  102674. * @param indiceNormalFromObj Integer The index in normals array
  102675. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  102676. * @param textureVectorFromOBJ Vector3 The value of uvs
  102677. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  102678. */
  102679. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  102680. //Check if this tuple already exists in the list of tuples
  102681. var _index;
  102682. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  102683. _index = isInArrayUV(tuplePosNorm, [
  102684. indicePositionFromObj,
  102685. indiceNormalFromObj,
  102686. indiceUvsFromObj
  102687. ]);
  102688. }
  102689. else {
  102690. _index = isInArray(tuplePosNorm, [
  102691. indicePositionFromObj,
  102692. indiceNormalFromObj
  102693. ]);
  102694. }
  102695. //If it not exists
  102696. if (_index == -1) {
  102697. //Add an new indice.
  102698. //The array of indices is only an array with his length equal to the number of triangles - 1.
  102699. //We add vertices data in this order
  102700. indicesForBabylon.push(wrappedPositionForBabylon.length);
  102701. //Push the position of vertice for Babylon
  102702. //Each element is a BABYLON.Vector3(x,y,z)
  102703. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  102704. //Push the uvs for Babylon
  102705. //Each element is a BABYLON.Vector3(u,v)
  102706. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  102707. //Push the normals for Babylon
  102708. //Each element is a BABYLON.Vector3(x,y,z)
  102709. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  102710. //Add the tuple in the comparison list
  102711. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  102712. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  102713. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  102714. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  102715. }
  102716. else {
  102717. //The tuple already exists
  102718. //Add the index of the already existing tuple
  102719. //At this index we can get the value of position, normal and uvs of vertex
  102720. indicesForBabylon.push(_index);
  102721. }
  102722. };
  102723. /**
  102724. * Transform BABYLON.Vector() object onto 3 digits in an array
  102725. */
  102726. var unwrapData = function () {
  102727. //Every array has the same length
  102728. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  102729. //Push the x, y, z values of each element in the unwrapped array
  102730. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  102731. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  102732. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  102733. }
  102734. // Reset arrays for the next new meshes
  102735. wrappedPositionForBabylon = [];
  102736. wrappedNormalsForBabylon = [];
  102737. wrappedUvsForBabylon = [];
  102738. tuplePosNorm = [];
  102739. curPositionInIndices = 0;
  102740. };
  102741. /**
  102742. * Create triangles from polygons by recursion
  102743. * The best to understand how it works is to draw it in the same time you get the recursion.
  102744. * It is important to notice that a triangle is a polygon
  102745. * We get 4 patterns of face defined in OBJ File :
  102746. * facePattern1 = ["1","2","3","4","5","6"]
  102747. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  102748. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  102749. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  102750. * Each pattern is divided by the same method
  102751. * @param face Array[String] The indices of elements
  102752. * @param v Integer The variable to increment
  102753. */
  102754. var getTriangles = function (face, v) {
  102755. //Work for each element of the array
  102756. if (v + 1 < face.length) {
  102757. //Add on the triangle variable the indexes to obtain triangles
  102758. triangles.push(face[0], face[v], face[v + 1]);
  102759. //Incrementation for recursion
  102760. v += 1;
  102761. //Recursion
  102762. getTriangles(face, v);
  102763. }
  102764. //Result obtained after 2 iterations:
  102765. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  102766. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  102767. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  102768. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  102769. };
  102770. /**
  102771. * Create triangles and push the data for each polygon for the pattern 1
  102772. * In this pattern we get vertice positions
  102773. * @param face
  102774. * @param v
  102775. */
  102776. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  102777. //Get the indices of triangles for each polygon
  102778. getTriangles(face, v);
  102779. //For each element in the triangles array.
  102780. //This var could contains 1 to an infinity of triangles
  102781. for (var k = 0; k < triangles.length; k++) {
  102782. // Set position indice
  102783. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  102784. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  102785. positions[indicePositionFromObj], //Get the vectors data
  102786. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  102787. );
  102788. }
  102789. //Reset variable for the next line
  102790. triangles = [];
  102791. };
  102792. /**
  102793. * Create triangles and push the data for each polygon for the pattern 2
  102794. * In this pattern we get vertice positions and uvsu
  102795. * @param face
  102796. * @param v
  102797. */
  102798. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  102799. //Get the indices of triangles for each polygon
  102800. getTriangles(face, v);
  102801. for (var k = 0; k < triangles.length; k++) {
  102802. //triangle[k] = "1/1"
  102803. //Split the data for getting position and uv
  102804. var point = triangles[k].split("/"); // ["1", "1"]
  102805. //Set position indice
  102806. var indicePositionFromObj = parseInt(point[0]) - 1;
  102807. //Set uv indice
  102808. var indiceUvsFromObj = parseInt(point[1]) - 1;
  102809. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  102810. positions[indicePositionFromObj], //Get the values for each element
  102811. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  102812. );
  102813. }
  102814. //Reset variable for the next line
  102815. triangles = [];
  102816. };
  102817. /**
  102818. * Create triangles and push the data for each polygon for the pattern 3
  102819. * In this pattern we get vertice positions, uvs and normals
  102820. * @param face
  102821. * @param v
  102822. */
  102823. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  102824. //Get the indices of triangles for each polygon
  102825. getTriangles(face, v);
  102826. for (var k = 0; k < triangles.length; k++) {
  102827. //triangle[k] = "1/1/1"
  102828. //Split the data for getting position, uv, and normals
  102829. var point = triangles[k].split("/"); // ["1", "1", "1"]
  102830. // Set position indice
  102831. var indicePositionFromObj = parseInt(point[0]) - 1;
  102832. // Set uv indice
  102833. var indiceUvsFromObj = parseInt(point[1]) - 1;
  102834. // Set normal indice
  102835. var indiceNormalFromObj = parseInt(point[2]) - 1;
  102836. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  102837. );
  102838. }
  102839. //Reset variable for the next line
  102840. triangles = [];
  102841. };
  102842. /**
  102843. * Create triangles and push the data for each polygon for the pattern 4
  102844. * In this pattern we get vertice positions and normals
  102845. * @param face
  102846. * @param v
  102847. */
  102848. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  102849. getTriangles(face, v);
  102850. for (var k = 0; k < triangles.length; k++) {
  102851. //triangle[k] = "1//1"
  102852. //Split the data for getting position and normals
  102853. var point = triangles[k].split("//"); // ["1", "1"]
  102854. // We check indices, and normals
  102855. var indicePositionFromObj = parseInt(point[0]) - 1;
  102856. var indiceNormalFromObj = parseInt(point[1]) - 1;
  102857. setData(indicePositionFromObj, 1, //Default value for uv
  102858. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  102859. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  102860. }
  102861. //Reset variable for the next line
  102862. triangles = [];
  102863. };
  102864. var addPreviousObjMesh = function () {
  102865. //Check if it is not the first mesh. Otherwise we don't have data.
  102866. if (meshesFromObj.length > 0) {
  102867. //Get the previous mesh for applying the data about the faces
  102868. //=> in obj file, faces definition append after the name of the mesh
  102869. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  102870. //Set the data into Array for the mesh
  102871. unwrapData();
  102872. // Reverse tab. Otherwise face are displayed in the wrong sens
  102873. indicesForBabylon.reverse();
  102874. //Set the information for the mesh
  102875. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  102876. handledMesh.indices = indicesForBabylon.slice();
  102877. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  102878. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  102879. handledMesh.uvs = unwrappedUVForBabylon.slice();
  102880. //Reset the array for the next mesh
  102881. indicesForBabylon = [];
  102882. unwrappedPositionsForBabylon = [];
  102883. unwrappedNormalsForBabylon = [];
  102884. unwrappedUVForBabylon = [];
  102885. }
  102886. };
  102887. //Main function
  102888. //Split the file into lines
  102889. var lines = data.split('\n');
  102890. //Look at each line
  102891. for (var i = 0; i < lines.length; i++) {
  102892. var line = lines[i].trim();
  102893. var result;
  102894. //Comment or newLine
  102895. if (line.length === 0 || line.charAt(0) === '#') {
  102896. continue;
  102897. //Get information about one position possible for the vertices
  102898. }
  102899. else if ((result = this.vertexPattern.exec(line)) !== null) {
  102900. //Create a Vector3 with the position x, y, z
  102901. //Value of result:
  102902. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102903. //Add the Vector in the list of positions
  102904. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102905. }
  102906. else if ((result = this.normalPattern.exec(line)) !== null) {
  102907. //Create a Vector3 with the normals x, y, z
  102908. //Value of result
  102909. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  102910. //Add the Vector in the list of normals
  102911. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  102912. }
  102913. else if ((result = this.uvPattern.exec(line)) !== null) {
  102914. //Create a Vector2 with the normals u, v
  102915. //Value of result
  102916. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  102917. //Add the Vector in the list of uvs
  102918. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  102919. //Identify patterns of faces
  102920. //Face could be defined in different type of pattern
  102921. }
  102922. else if ((result = this.facePattern3.exec(line)) !== null) {
  102923. //Value of result:
  102924. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  102925. //Set the data for this face
  102926. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  102927. 1);
  102928. }
  102929. else if ((result = this.facePattern4.exec(line)) !== null) {
  102930. //Value of result:
  102931. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  102932. //Set the data for this face
  102933. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  102934. 1);
  102935. }
  102936. else if ((result = this.facePattern2.exec(line)) !== null) {
  102937. //Value of result:
  102938. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  102939. //Set the data for this face
  102940. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  102941. 1);
  102942. }
  102943. else if ((result = this.facePattern1.exec(line)) !== null) {
  102944. //Value of result
  102945. //["f 1 2 3", "1 2 3"...]
  102946. //Set the data for this face
  102947. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  102948. 1);
  102949. //Define a mesh or an object
  102950. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  102951. }
  102952. else if (this.group.test(line) || this.obj.test(line)) {
  102953. //Create a new mesh corresponding to the name of the group.
  102954. //Definition of the mesh
  102955. var objMesh =
  102956. //Set the name of the current obj mesh
  102957. {
  102958. name: line.substring(2).trim(),
  102959. indices: undefined,
  102960. positions: undefined,
  102961. normals: undefined,
  102962. uvs: undefined,
  102963. materialName: ""
  102964. };
  102965. addPreviousObjMesh();
  102966. //Push the last mesh created with only the name
  102967. meshesFromObj.push(objMesh);
  102968. //Set this variable to indicate that now meshesFromObj has objects defined inside
  102969. hasMeshes = true;
  102970. isFirstMaterial = true;
  102971. increment = 1;
  102972. //Keyword for applying a material
  102973. }
  102974. else if (this.usemtl.test(line)) {
  102975. //Get the name of the material
  102976. materialNameFromObj = line.substring(7).trim();
  102977. //If this new material is in the same mesh
  102978. if (!isFirstMaterial) {
  102979. //Set the data for the previous mesh
  102980. addPreviousObjMesh();
  102981. //Create a new mesh
  102982. var objMesh =
  102983. //Set the name of the current obj mesh
  102984. {
  102985. name: objMeshName + "_mm" + increment.toString(),
  102986. indices: undefined,
  102987. positions: undefined,
  102988. normals: undefined,
  102989. uvs: undefined,
  102990. materialName: materialNameFromObj
  102991. };
  102992. increment++;
  102993. //If meshes are already defined
  102994. meshesFromObj.push(objMesh);
  102995. }
  102996. //Set the material name if the previous line define a mesh
  102997. if (hasMeshes && isFirstMaterial) {
  102998. //Set the material name to the previous mesh (1 material per mesh)
  102999. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  103000. isFirstMaterial = false;
  103001. }
  103002. //Keyword for loading the mtl file
  103003. }
  103004. else if (this.mtllib.test(line)) {
  103005. //Get the name of mtl file
  103006. fileToLoad = line.substring(7).trim();
  103007. //Apply smoothing
  103008. }
  103009. else if (this.smooth.test(line)) {
  103010. // smooth shading => apply smoothing
  103011. //Toda y I don't know it work with babylon and with obj.
  103012. //With the obj file an integer is set
  103013. }
  103014. else {
  103015. //If there is another possibility
  103016. console.log("Unhandled expression at line : " + line);
  103017. }
  103018. }
  103019. //At the end of the file, add the last mesh into the meshesFromObj array
  103020. if (hasMeshes) {
  103021. //Set the data for the last mesh
  103022. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  103023. //Reverse indices for displaying faces in the good sens
  103024. indicesForBabylon.reverse();
  103025. //Get the good array
  103026. unwrapData();
  103027. //Set array
  103028. handledMesh.indices = indicesForBabylon;
  103029. handledMesh.positions = unwrappedPositionsForBabylon;
  103030. handledMesh.normals = unwrappedNormalsForBabylon;
  103031. handledMesh.uvs = unwrappedUVForBabylon;
  103032. }
  103033. //If any o or g keyword found, create a mesj with a random id
  103034. if (!hasMeshes) {
  103035. // reverse tab of indices
  103036. indicesForBabylon.reverse();
  103037. //Get positions normals uvs
  103038. unwrapData();
  103039. //Set data for one mesh
  103040. meshesFromObj.push({
  103041. name: BABYLON.Geometry.RandomId(),
  103042. indices: indicesForBabylon,
  103043. positions: unwrappedPositionsForBabylon,
  103044. normals: unwrappedNormalsForBabylon,
  103045. uvs: unwrappedUVForBabylon,
  103046. materialName: materialNameFromObj
  103047. });
  103048. }
  103049. //Create a BABYLON.Mesh list
  103050. var babylonMeshesArray = []; //The mesh for babylon
  103051. var materialToUse = new Array();
  103052. //Set data for each mesh
  103053. for (var j = 0; j < meshesFromObj.length; j++) {
  103054. //check meshesNames (stlFileLoader)
  103055. if (meshesNames && meshesFromObj[j].name) {
  103056. if (meshesNames instanceof Array) {
  103057. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  103058. continue;
  103059. }
  103060. }
  103061. else {
  103062. if (meshesFromObj[j].name !== meshesNames) {
  103063. continue;
  103064. }
  103065. }
  103066. }
  103067. //Get the current mesh
  103068. //Set the data with VertexBuffer for each mesh
  103069. handledMesh = meshesFromObj[j];
  103070. //Create a BABYLON.Mesh with the name of the obj mesh
  103071. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  103072. //Push the name of the material to an array
  103073. //This is indispensable for the importMesh function
  103074. materialToUse.push(meshesFromObj[j].materialName);
  103075. var vertexData = new BABYLON.VertexData(); //The container for the values
  103076. //Set the data for the babylonMesh
  103077. vertexData.positions = handledMesh.positions;
  103078. vertexData.normals = handledMesh.normals;
  103079. vertexData.uvs = handledMesh.uvs;
  103080. vertexData.indices = handledMesh.indices;
  103081. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  103082. vertexData.applyToMesh(babylonMesh);
  103083. //Push the mesh into an array
  103084. babylonMeshesArray.push(babylonMesh);
  103085. }
  103086. //load the materials
  103087. //Check if we have a file to load
  103088. if (fileToLoad !== "") {
  103089. //Load the file synchronously
  103090. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  103091. //Create materials thanks MTLLoader function
  103092. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  103093. //Look at each material loaded in the mtl file
  103094. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  103095. //Three variables to get all meshes with the same material
  103096. var startIndex = 0;
  103097. var _indices = [];
  103098. var _index;
  103099. //The material from MTL file is used in the meshes loaded
  103100. //Push the indice in an array
  103101. //Check if the material is not used for another mesh
  103102. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  103103. _indices.push(_index);
  103104. startIndex = _index + 1;
  103105. }
  103106. //If the material is not used dispose it
  103107. if (_index == -1 && _indices.length == 0) {
  103108. //If the material is not needed, remove it
  103109. materialsFromMTLFile.materials[n].dispose();
  103110. }
  103111. else {
  103112. for (var o = 0; o < _indices.length; o++) {
  103113. //Apply the material to the BABYLON.Mesh for each mesh with the material
  103114. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  103115. }
  103116. }
  103117. }
  103118. });
  103119. }
  103120. //Return an array with all BABYLON.Mesh
  103121. return babylonMeshesArray;
  103122. };
  103123. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  103124. return OBJFileLoader;
  103125. }());
  103126. BABYLON.OBJFileLoader = OBJFileLoader;
  103127. if (BABYLON.SceneLoader) {
  103128. //Add this loader into the register plugin
  103129. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  103130. }
  103131. })(BABYLON || (BABYLON = {}));
  103132. //# sourceMappingURL=babylon.objFileLoader.js.map
  103133. var BABYLON;
  103134. (function (BABYLON) {
  103135. var GLTFLoaderCoordinateSystemMode;
  103136. (function (GLTFLoaderCoordinateSystemMode) {
  103137. /**
  103138. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  103139. */
  103140. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  103141. /**
  103142. * Sets the useRightHandedSystem flag on the scene.
  103143. */
  103144. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  103145. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  103146. var GLTFLoaderAnimationStartMode;
  103147. (function (GLTFLoaderAnimationStartMode) {
  103148. /**
  103149. * No animation will start.
  103150. */
  103151. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  103152. /**
  103153. * The first animation will start.
  103154. */
  103155. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  103156. /**
  103157. * All animations will start.
  103158. */
  103159. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  103160. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  103161. var GLTFLoaderState;
  103162. (function (GLTFLoaderState) {
  103163. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  103164. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  103165. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  103166. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  103167. var GLTFFileLoader = /** @class */ (function () {
  103168. function GLTFFileLoader() {
  103169. // #region Common options
  103170. /**
  103171. * Raised when the asset has been parsed.
  103172. * The data.json property stores the glTF JSON.
  103173. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  103174. */
  103175. this.onParsedObservable = new BABYLON.Observable();
  103176. // #endregion
  103177. // #region V2 options
  103178. /**
  103179. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  103180. */
  103181. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  103182. /**
  103183. * The animation start mode (NONE, FIRST, ALL).
  103184. */
  103185. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  103186. /**
  103187. * Set to true to compile materials before raising the success callback.
  103188. */
  103189. this.compileMaterials = false;
  103190. /**
  103191. * Set to true to also compile materials with clip planes.
  103192. */
  103193. this.useClipPlane = false;
  103194. /**
  103195. * Set to true to compile shadow generators before raising the success callback.
  103196. */
  103197. this.compileShadowGenerators = false;
  103198. /**
  103199. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  103200. */
  103201. this.onMeshLoadedObservable = new BABYLON.Observable();
  103202. /**
  103203. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  103204. */
  103205. this.onTextureLoadedObservable = new BABYLON.Observable();
  103206. /**
  103207. * Raised when the loader creates a material after parsing the glTF properties of the material.
  103208. */
  103209. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103210. /**
  103211. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  103212. * For assets with LODs, raised when all of the LODs are complete.
  103213. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  103214. */
  103215. this.onCompleteObservable = new BABYLON.Observable();
  103216. /**
  103217. * Raised when the loader is disposed.
  103218. */
  103219. this.onDisposeObservable = new BABYLON.Observable();
  103220. /**
  103221. * Raised after a loader extension is created.
  103222. * Set additional options for a loader extension in this event.
  103223. */
  103224. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103225. // #endregion
  103226. this._loader = null;
  103227. this.name = "gltf";
  103228. this.extensions = {
  103229. ".gltf": { isBinary: false },
  103230. ".glb": { isBinary: true }
  103231. };
  103232. }
  103233. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  103234. set: function (callback) {
  103235. if (this._onParsedObserver) {
  103236. this.onParsedObservable.remove(this._onParsedObserver);
  103237. }
  103238. this._onParsedObserver = this.onParsedObservable.add(callback);
  103239. },
  103240. enumerable: true,
  103241. configurable: true
  103242. });
  103243. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  103244. set: function (callback) {
  103245. if (this._onMeshLoadedObserver) {
  103246. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  103247. }
  103248. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  103249. },
  103250. enumerable: true,
  103251. configurable: true
  103252. });
  103253. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  103254. set: function (callback) {
  103255. if (this._onTextureLoadedObserver) {
  103256. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  103257. }
  103258. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  103259. },
  103260. enumerable: true,
  103261. configurable: true
  103262. });
  103263. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  103264. set: function (callback) {
  103265. if (this._onMaterialLoadedObserver) {
  103266. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  103267. }
  103268. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  103269. },
  103270. enumerable: true,
  103271. configurable: true
  103272. });
  103273. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  103274. set: function (callback) {
  103275. if (this._onCompleteObserver) {
  103276. this.onCompleteObservable.remove(this._onCompleteObserver);
  103277. }
  103278. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  103279. },
  103280. enumerable: true,
  103281. configurable: true
  103282. });
  103283. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  103284. set: function (callback) {
  103285. if (this._onDisposeObserver) {
  103286. this.onDisposeObservable.remove(this._onDisposeObserver);
  103287. }
  103288. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  103289. },
  103290. enumerable: true,
  103291. configurable: true
  103292. });
  103293. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  103294. set: function (callback) {
  103295. if (this._onExtensionLoadedObserver) {
  103296. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  103297. }
  103298. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  103299. },
  103300. enumerable: true,
  103301. configurable: true
  103302. });
  103303. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  103304. /**
  103305. * The loader state or null if not active.
  103306. */
  103307. get: function () {
  103308. return this._loader ? this._loader.state : null;
  103309. },
  103310. enumerable: true,
  103311. configurable: true
  103312. });
  103313. /**
  103314. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  103315. */
  103316. GLTFFileLoader.prototype.dispose = function () {
  103317. if (this._loader) {
  103318. this._loader.dispose();
  103319. this._loader = null;
  103320. }
  103321. this.onMeshLoadedObservable.clear();
  103322. this.onTextureLoadedObservable.clear();
  103323. this.onMaterialLoadedObservable.clear();
  103324. this.onDisposeObservable.notifyObservers(this);
  103325. this.onDisposeObservable.clear();
  103326. };
  103327. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103328. var _this = this;
  103329. return Promise.resolve().then(function () {
  103330. var loaderData = _this._parse(data);
  103331. _this._loader = _this._getLoader(loaderData);
  103332. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  103333. });
  103334. };
  103335. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103336. var _this = this;
  103337. return Promise.resolve().then(function () {
  103338. var loaderData = _this._parse(data);
  103339. _this._loader = _this._getLoader(loaderData);
  103340. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  103341. });
  103342. };
  103343. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  103344. var _this = this;
  103345. return Promise.resolve().then(function () {
  103346. var loaderData = _this._parse(data);
  103347. _this._loader = _this._getLoader(loaderData);
  103348. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  103349. var container = new BABYLON.AssetContainer(scene);
  103350. Array.prototype.push.apply(container.meshes, result.meshes);
  103351. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  103352. Array.prototype.push.apply(container.skeletons, result.skeletons);
  103353. container.removeAllFromScene();
  103354. return container;
  103355. });
  103356. });
  103357. };
  103358. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  103359. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  103360. };
  103361. GLTFFileLoader.prototype.createPlugin = function () {
  103362. return new GLTFFileLoader();
  103363. };
  103364. GLTFFileLoader.prototype._parse = function (data) {
  103365. var parsedData;
  103366. if (data instanceof ArrayBuffer) {
  103367. parsedData = GLTFFileLoader._parseBinary(data);
  103368. }
  103369. else {
  103370. parsedData = {
  103371. json: JSON.parse(data),
  103372. bin: null
  103373. };
  103374. }
  103375. this.onParsedObservable.notifyObservers(parsedData);
  103376. this.onParsedObservable.clear();
  103377. return parsedData;
  103378. };
  103379. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  103380. var _this = this;
  103381. var loaderVersion = { major: 2, minor: 0 };
  103382. var asset = loaderData.json.asset || {};
  103383. var version = GLTFFileLoader._parseVersion(asset.version);
  103384. if (!version) {
  103385. throw new Error("Invalid version: " + asset.version);
  103386. }
  103387. if (asset.minVersion !== undefined) {
  103388. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  103389. if (!minVersion) {
  103390. throw new Error("Invalid minimum version: " + asset.minVersion);
  103391. }
  103392. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  103393. throw new Error("Incompatible minimum version: " + asset.minVersion);
  103394. }
  103395. }
  103396. var createLoaders = {
  103397. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  103398. 2: GLTFFileLoader.CreateGLTFLoaderV2
  103399. };
  103400. var createLoader = createLoaders[version.major];
  103401. if (!createLoader) {
  103402. throw new Error("Unsupported version: " + asset.version);
  103403. }
  103404. var loader = createLoader();
  103405. loader.coordinateSystemMode = this.coordinateSystemMode;
  103406. loader.animationStartMode = this.animationStartMode;
  103407. loader.compileMaterials = this.compileMaterials;
  103408. loader.useClipPlane = this.useClipPlane;
  103409. loader.compileShadowGenerators = this.compileShadowGenerators;
  103410. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  103411. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  103412. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  103413. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  103414. loader.onCompleteObservable.add(function () {
  103415. _this.onMeshLoadedObservable.clear();
  103416. _this.onTextureLoadedObservable.clear();
  103417. _this.onMaterialLoadedObservable.clear();
  103418. _this.onCompleteObservable.notifyObservers(_this);
  103419. _this.onCompleteObservable.clear();
  103420. });
  103421. return loader;
  103422. };
  103423. GLTFFileLoader._parseBinary = function (data) {
  103424. var Binary = {
  103425. Magic: 0x46546C67
  103426. };
  103427. var binaryReader = new BinaryReader(data);
  103428. var magic = binaryReader.readUint32();
  103429. if (magic !== Binary.Magic) {
  103430. throw new Error("Unexpected magic: " + magic);
  103431. }
  103432. var version = binaryReader.readUint32();
  103433. switch (version) {
  103434. case 1: return GLTFFileLoader._parseV1(binaryReader);
  103435. case 2: return GLTFFileLoader._parseV2(binaryReader);
  103436. }
  103437. throw new Error("Unsupported version: " + version);
  103438. };
  103439. GLTFFileLoader._parseV1 = function (binaryReader) {
  103440. var ContentFormat = {
  103441. JSON: 0
  103442. };
  103443. var length = binaryReader.readUint32();
  103444. if (length != binaryReader.getLength()) {
  103445. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  103446. }
  103447. var contentLength = binaryReader.readUint32();
  103448. var contentFormat = binaryReader.readUint32();
  103449. var content;
  103450. switch (contentFormat) {
  103451. case ContentFormat.JSON: {
  103452. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  103453. break;
  103454. }
  103455. default: {
  103456. throw new Error("Unexpected content format: " + contentFormat);
  103457. }
  103458. }
  103459. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  103460. var body = binaryReader.readUint8Array(bytesRemaining);
  103461. return {
  103462. json: content,
  103463. bin: body
  103464. };
  103465. };
  103466. GLTFFileLoader._parseV2 = function (binaryReader) {
  103467. var ChunkFormat = {
  103468. JSON: 0x4E4F534A,
  103469. BIN: 0x004E4942
  103470. };
  103471. var length = binaryReader.readUint32();
  103472. if (length !== binaryReader.getLength()) {
  103473. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  103474. }
  103475. // JSON chunk
  103476. var chunkLength = binaryReader.readUint32();
  103477. var chunkFormat = binaryReader.readUint32();
  103478. if (chunkFormat !== ChunkFormat.JSON) {
  103479. throw new Error("First chunk format is not JSON");
  103480. }
  103481. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  103482. // Look for BIN chunk
  103483. var bin = null;
  103484. while (binaryReader.getPosition() < binaryReader.getLength()) {
  103485. var chunkLength_1 = binaryReader.readUint32();
  103486. var chunkFormat_1 = binaryReader.readUint32();
  103487. switch (chunkFormat_1) {
  103488. case ChunkFormat.JSON: {
  103489. throw new Error("Unexpected JSON chunk");
  103490. }
  103491. case ChunkFormat.BIN: {
  103492. bin = binaryReader.readUint8Array(chunkLength_1);
  103493. break;
  103494. }
  103495. default: {
  103496. // ignore unrecognized chunkFormat
  103497. binaryReader.skipBytes(chunkLength_1);
  103498. break;
  103499. }
  103500. }
  103501. }
  103502. return {
  103503. json: json,
  103504. bin: bin
  103505. };
  103506. };
  103507. GLTFFileLoader._parseVersion = function (version) {
  103508. if (version === "1.0" || version === "1.0.1") {
  103509. return {
  103510. major: 1,
  103511. minor: 0
  103512. };
  103513. }
  103514. var match = (version + "").match(/^(\d+)\.(\d+)/);
  103515. if (!match) {
  103516. return null;
  103517. }
  103518. return {
  103519. major: parseInt(match[1]),
  103520. minor: parseInt(match[2])
  103521. };
  103522. };
  103523. GLTFFileLoader._compareVersion = function (a, b) {
  103524. if (a.major > b.major)
  103525. return 1;
  103526. if (a.major < b.major)
  103527. return -1;
  103528. if (a.minor > b.minor)
  103529. return 1;
  103530. if (a.minor < b.minor)
  103531. return -1;
  103532. return 0;
  103533. };
  103534. GLTFFileLoader._decodeBufferToText = function (buffer) {
  103535. var result = "";
  103536. var length = buffer.byteLength;
  103537. for (var i = 0; i < length; i++) {
  103538. result += String.fromCharCode(buffer[i]);
  103539. }
  103540. return result;
  103541. };
  103542. // #endregion
  103543. // #region V1 options
  103544. GLTFFileLoader.IncrementalLoading = true;
  103545. GLTFFileLoader.HomogeneousCoordinates = false;
  103546. return GLTFFileLoader;
  103547. }());
  103548. BABYLON.GLTFFileLoader = GLTFFileLoader;
  103549. var BinaryReader = /** @class */ (function () {
  103550. function BinaryReader(arrayBuffer) {
  103551. this._arrayBuffer = arrayBuffer;
  103552. this._dataView = new DataView(arrayBuffer);
  103553. this._byteOffset = 0;
  103554. }
  103555. BinaryReader.prototype.getPosition = function () {
  103556. return this._byteOffset;
  103557. };
  103558. BinaryReader.prototype.getLength = function () {
  103559. return this._arrayBuffer.byteLength;
  103560. };
  103561. BinaryReader.prototype.readUint32 = function () {
  103562. var value = this._dataView.getUint32(this._byteOffset, true);
  103563. this._byteOffset += 4;
  103564. return value;
  103565. };
  103566. BinaryReader.prototype.readUint8Array = function (length) {
  103567. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  103568. this._byteOffset += length;
  103569. return value;
  103570. };
  103571. BinaryReader.prototype.skipBytes = function (length) {
  103572. this._byteOffset += length;
  103573. };
  103574. return BinaryReader;
  103575. }());
  103576. if (BABYLON.SceneLoader) {
  103577. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  103578. }
  103579. })(BABYLON || (BABYLON = {}));
  103580. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  103581. var BABYLON;
  103582. (function (BABYLON) {
  103583. var GLTF1;
  103584. (function (GLTF1) {
  103585. /**
  103586. * Enums
  103587. */
  103588. var EComponentType;
  103589. (function (EComponentType) {
  103590. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  103591. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  103592. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  103593. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  103594. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  103595. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  103596. var EShaderType;
  103597. (function (EShaderType) {
  103598. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  103599. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  103600. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  103601. var EParameterType;
  103602. (function (EParameterType) {
  103603. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  103604. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  103605. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  103606. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  103607. EParameterType[EParameterType["INT"] = 5124] = "INT";
  103608. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  103609. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  103610. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  103611. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  103612. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  103613. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  103614. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  103615. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  103616. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  103617. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  103618. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  103619. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  103620. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  103621. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  103622. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  103623. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  103624. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  103625. var ETextureWrapMode;
  103626. (function (ETextureWrapMode) {
  103627. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  103628. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  103629. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  103630. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  103631. var ETextureFilterType;
  103632. (function (ETextureFilterType) {
  103633. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  103634. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  103635. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  103636. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  103637. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  103638. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  103639. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  103640. var ETextureFormat;
  103641. (function (ETextureFormat) {
  103642. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  103643. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  103644. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  103645. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  103646. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  103647. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  103648. var ECullingType;
  103649. (function (ECullingType) {
  103650. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  103651. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  103652. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  103653. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  103654. var EBlendingFunction;
  103655. (function (EBlendingFunction) {
  103656. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  103657. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  103658. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  103659. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  103660. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  103661. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  103662. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  103663. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  103664. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  103665. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  103666. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  103667. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  103668. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  103669. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  103670. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  103671. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  103672. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103673. })(BABYLON || (BABYLON = {}));
  103674. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  103675. var BABYLON;
  103676. (function (BABYLON) {
  103677. var GLTF1;
  103678. (function (GLTF1) {
  103679. /**
  103680. * Tokenizer. Used for shaders compatibility
  103681. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  103682. */
  103683. var ETokenType;
  103684. (function (ETokenType) {
  103685. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  103686. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  103687. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  103688. })(ETokenType || (ETokenType = {}));
  103689. var Tokenizer = /** @class */ (function () {
  103690. function Tokenizer(toParse) {
  103691. this._pos = 0;
  103692. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  103693. this._toParse = toParse;
  103694. this._maxPos = toParse.length;
  103695. }
  103696. Tokenizer.prototype.getNextToken = function () {
  103697. if (this.isEnd())
  103698. return ETokenType.END_OF_INPUT;
  103699. this.currentString = this.read();
  103700. this.currentToken = ETokenType.UNKNOWN;
  103701. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  103702. this.currentToken = ETokenType.IDENTIFIER;
  103703. this.currentIdentifier = this.currentString;
  103704. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  103705. this.currentIdentifier += this.currentString;
  103706. this.forward();
  103707. }
  103708. }
  103709. return this.currentToken;
  103710. };
  103711. Tokenizer.prototype.peek = function () {
  103712. return this._toParse[this._pos];
  103713. };
  103714. Tokenizer.prototype.read = function () {
  103715. return this._toParse[this._pos++];
  103716. };
  103717. Tokenizer.prototype.forward = function () {
  103718. this._pos++;
  103719. };
  103720. Tokenizer.prototype.isEnd = function () {
  103721. return this._pos >= this._maxPos;
  103722. };
  103723. return Tokenizer;
  103724. }());
  103725. /**
  103726. * Values
  103727. */
  103728. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  103729. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  103730. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  103731. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  103732. /**
  103733. * Parse
  103734. */
  103735. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  103736. for (var buf in parsedBuffers) {
  103737. var parsedBuffer = parsedBuffers[buf];
  103738. gltfRuntime.buffers[buf] = parsedBuffer;
  103739. gltfRuntime.buffersCount++;
  103740. }
  103741. };
  103742. var parseShaders = function (parsedShaders, gltfRuntime) {
  103743. for (var sha in parsedShaders) {
  103744. var parsedShader = parsedShaders[sha];
  103745. gltfRuntime.shaders[sha] = parsedShader;
  103746. gltfRuntime.shaderscount++;
  103747. }
  103748. };
  103749. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  103750. for (var object in parsedObjects) {
  103751. var parsedObject = parsedObjects[object];
  103752. gltfRuntime[runtimeProperty][object] = parsedObject;
  103753. }
  103754. };
  103755. /**
  103756. * Utils
  103757. */
  103758. var normalizeUVs = function (buffer) {
  103759. if (!buffer) {
  103760. return;
  103761. }
  103762. for (var i = 0; i < buffer.length / 2; i++) {
  103763. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  103764. }
  103765. };
  103766. var getAttribute = function (attributeParameter) {
  103767. if (attributeParameter.semantic === "NORMAL") {
  103768. return "normal";
  103769. }
  103770. else if (attributeParameter.semantic === "POSITION") {
  103771. return "position";
  103772. }
  103773. else if (attributeParameter.semantic === "JOINT") {
  103774. return "matricesIndices";
  103775. }
  103776. else if (attributeParameter.semantic === "WEIGHT") {
  103777. return "matricesWeights";
  103778. }
  103779. else if (attributeParameter.semantic === "COLOR") {
  103780. return "color";
  103781. }
  103782. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  103783. var channel = Number(attributeParameter.semantic.split("_")[1]);
  103784. return "uv" + (channel === 0 ? "" : channel + 1);
  103785. }
  103786. return null;
  103787. };
  103788. /**
  103789. * Loads and creates animations
  103790. */
  103791. var loadAnimations = function (gltfRuntime) {
  103792. for (var anim in gltfRuntime.animations) {
  103793. var animation = gltfRuntime.animations[anim];
  103794. if (!animation.channels || !animation.samplers) {
  103795. continue;
  103796. }
  103797. var lastAnimation = null;
  103798. for (var i = 0; i < animation.channels.length; i++) {
  103799. // Get parameters and load buffers
  103800. var channel = animation.channels[i];
  103801. var sampler = animation.samplers[channel.sampler];
  103802. if (!sampler) {
  103803. continue;
  103804. }
  103805. var inputData = null;
  103806. var outputData = null;
  103807. if (animation.parameters) {
  103808. inputData = animation.parameters[sampler.input];
  103809. outputData = animation.parameters[sampler.output];
  103810. }
  103811. else {
  103812. inputData = sampler.input;
  103813. outputData = sampler.output;
  103814. }
  103815. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  103816. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  103817. var targetID = channel.target.id;
  103818. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  103819. if (targetNode === null) {
  103820. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  103821. }
  103822. if (targetNode === null) {
  103823. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  103824. continue;
  103825. }
  103826. var isBone = targetNode instanceof BABYLON.Bone;
  103827. // Get target path (position, rotation or scaling)
  103828. var targetPath = channel.target.path;
  103829. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  103830. if (targetPathIndex !== -1) {
  103831. targetPath = babylonAnimationPaths[targetPathIndex];
  103832. }
  103833. // Determine animation type
  103834. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  103835. if (!isBone) {
  103836. if (targetPath === "rotationQuaternion") {
  103837. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  103838. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  103839. }
  103840. else {
  103841. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  103842. }
  103843. }
  103844. // Create animation and key frames
  103845. var babylonAnimation = null;
  103846. var keys = [];
  103847. var arrayOffset = 0;
  103848. var modifyKey = false;
  103849. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  103850. babylonAnimation = lastAnimation;
  103851. modifyKey = true;
  103852. }
  103853. if (!modifyKey) {
  103854. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  103855. }
  103856. // For each frame
  103857. for (var j = 0; j < bufferInput.length; j++) {
  103858. var value = null;
  103859. if (targetPath === "rotationQuaternion") {
  103860. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  103861. arrayOffset += 4;
  103862. }
  103863. else {
  103864. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  103865. arrayOffset += 3;
  103866. }
  103867. if (isBone) {
  103868. var bone = targetNode;
  103869. var translation = BABYLON.Vector3.Zero();
  103870. var rotationQuaternion = new BABYLON.Quaternion();
  103871. var scaling = BABYLON.Vector3.Zero();
  103872. // Warning on decompose
  103873. var mat = bone.getBaseMatrix();
  103874. if (modifyKey && lastAnimation) {
  103875. mat = lastAnimation.getKeys()[j].value;
  103876. }
  103877. mat.decompose(scaling, rotationQuaternion, translation);
  103878. if (targetPath === "position") {
  103879. translation = value;
  103880. }
  103881. else if (targetPath === "rotationQuaternion") {
  103882. rotationQuaternion = value;
  103883. }
  103884. else {
  103885. scaling = value;
  103886. }
  103887. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  103888. }
  103889. if (!modifyKey) {
  103890. keys.push({
  103891. frame: bufferInput[j],
  103892. value: value
  103893. });
  103894. }
  103895. else if (lastAnimation) {
  103896. lastAnimation.getKeys()[j].value = value;
  103897. }
  103898. }
  103899. // Finish
  103900. if (!modifyKey && babylonAnimation) {
  103901. babylonAnimation.setKeys(keys);
  103902. targetNode.animations.push(babylonAnimation);
  103903. }
  103904. lastAnimation = babylonAnimation;
  103905. gltfRuntime.scene.stopAnimation(targetNode);
  103906. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  103907. }
  103908. }
  103909. };
  103910. /**
  103911. * Returns the bones transformation matrix
  103912. */
  103913. var configureBoneTransformation = function (node) {
  103914. var mat = null;
  103915. if (node.translation || node.rotation || node.scale) {
  103916. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  103917. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  103918. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  103919. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  103920. }
  103921. else {
  103922. mat = BABYLON.Matrix.FromArray(node.matrix);
  103923. }
  103924. return mat;
  103925. };
  103926. /**
  103927. * Returns the parent bone
  103928. */
  103929. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  103930. // Try to find
  103931. for (var i = 0; i < newSkeleton.bones.length; i++) {
  103932. if (newSkeleton.bones[i].name === jointName) {
  103933. return newSkeleton.bones[i];
  103934. }
  103935. }
  103936. // Not found, search in gltf nodes
  103937. var nodes = gltfRuntime.nodes;
  103938. for (var nde in nodes) {
  103939. var node = nodes[nde];
  103940. if (!node.jointName) {
  103941. continue;
  103942. }
  103943. var children = node.children;
  103944. for (var i = 0; i < children.length; i++) {
  103945. var child = gltfRuntime.nodes[children[i]];
  103946. if (!child.jointName) {
  103947. continue;
  103948. }
  103949. if (child.jointName === jointName) {
  103950. var mat = configureBoneTransformation(node);
  103951. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  103952. bone.id = nde;
  103953. return bone;
  103954. }
  103955. }
  103956. }
  103957. return null;
  103958. };
  103959. /**
  103960. * Returns the appropriate root node
  103961. */
  103962. var getNodeToRoot = function (nodesToRoot, id) {
  103963. for (var i = 0; i < nodesToRoot.length; i++) {
  103964. var nodeToRoot = nodesToRoot[i];
  103965. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  103966. var child = nodeToRoot.node.children[j];
  103967. if (child === id) {
  103968. return nodeToRoot.bone;
  103969. }
  103970. }
  103971. }
  103972. return null;
  103973. };
  103974. /**
  103975. * Returns the node with the joint name
  103976. */
  103977. var getJointNode = function (gltfRuntime, jointName) {
  103978. var nodes = gltfRuntime.nodes;
  103979. var node = nodes[jointName];
  103980. if (node) {
  103981. return {
  103982. node: node,
  103983. id: jointName
  103984. };
  103985. }
  103986. for (var nde in nodes) {
  103987. node = nodes[nde];
  103988. if (node.jointName === jointName) {
  103989. return {
  103990. node: node,
  103991. id: nde
  103992. };
  103993. }
  103994. }
  103995. return null;
  103996. };
  103997. /**
  103998. * Checks if a nodes is in joints
  103999. */
  104000. var nodeIsInJoints = function (skins, id) {
  104001. for (var i = 0; i < skins.jointNames.length; i++) {
  104002. if (skins.jointNames[i] === id) {
  104003. return true;
  104004. }
  104005. }
  104006. return false;
  104007. };
  104008. /**
  104009. * Fills the nodes to root for bones and builds hierarchy
  104010. */
  104011. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  104012. // Creates nodes for root
  104013. for (var nde in gltfRuntime.nodes) {
  104014. var node = gltfRuntime.nodes[nde];
  104015. var id = nde;
  104016. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  104017. continue;
  104018. }
  104019. // Create node to root bone
  104020. var mat = configureBoneTransformation(node);
  104021. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  104022. bone.id = id;
  104023. nodesToRoot.push({ bone: bone, node: node, id: id });
  104024. }
  104025. // Parenting
  104026. for (var i = 0; i < nodesToRoot.length; i++) {
  104027. var nodeToRoot = nodesToRoot[i];
  104028. var children = nodeToRoot.node.children;
  104029. for (var j = 0; j < children.length; j++) {
  104030. var child = null;
  104031. for (var k = 0; k < nodesToRoot.length; k++) {
  104032. if (nodesToRoot[k].id === children[j]) {
  104033. child = nodesToRoot[k];
  104034. break;
  104035. }
  104036. }
  104037. if (child) {
  104038. child.bone._parent = nodeToRoot.bone;
  104039. nodeToRoot.bone.children.push(child.bone);
  104040. }
  104041. }
  104042. }
  104043. };
  104044. /**
  104045. * Imports a skeleton
  104046. */
  104047. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  104048. if (!newSkeleton) {
  104049. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  104050. }
  104051. if (!skins.babylonSkeleton) {
  104052. return newSkeleton;
  104053. }
  104054. // Find the root bones
  104055. var nodesToRoot = [];
  104056. var nodesToRootToAdd = [];
  104057. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  104058. newSkeleton.bones = [];
  104059. // Joints
  104060. for (var i = 0; i < skins.jointNames.length; i++) {
  104061. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  104062. if (!jointNode) {
  104063. continue;
  104064. }
  104065. var node = jointNode.node;
  104066. if (!node) {
  104067. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  104068. continue;
  104069. }
  104070. var id = jointNode.id;
  104071. // Optimize, if the bone already exists...
  104072. var existingBone = gltfRuntime.scene.getBoneByID(id);
  104073. if (existingBone) {
  104074. newSkeleton.bones.push(existingBone);
  104075. continue;
  104076. }
  104077. // Search for parent bone
  104078. var foundBone = false;
  104079. var parentBone = null;
  104080. for (var j = 0; j < i; j++) {
  104081. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  104082. if (!jointNode_1) {
  104083. continue;
  104084. }
  104085. var joint = jointNode_1.node;
  104086. if (!joint) {
  104087. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  104088. continue;
  104089. }
  104090. var children = joint.children;
  104091. if (!children) {
  104092. continue;
  104093. }
  104094. foundBone = false;
  104095. for (var k = 0; k < children.length; k++) {
  104096. if (children[k] === id) {
  104097. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  104098. foundBone = true;
  104099. break;
  104100. }
  104101. }
  104102. if (foundBone) {
  104103. break;
  104104. }
  104105. }
  104106. // Create bone
  104107. var mat = configureBoneTransformation(node);
  104108. if (!parentBone && nodesToRoot.length > 0) {
  104109. parentBone = getNodeToRoot(nodesToRoot, id);
  104110. if (parentBone) {
  104111. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  104112. nodesToRootToAdd.push(parentBone);
  104113. }
  104114. }
  104115. }
  104116. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  104117. bone.id = id;
  104118. }
  104119. // Polish
  104120. var bones = newSkeleton.bones;
  104121. newSkeleton.bones = [];
  104122. for (var i = 0; i < skins.jointNames.length; i++) {
  104123. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  104124. if (!jointNode) {
  104125. continue;
  104126. }
  104127. for (var j = 0; j < bones.length; j++) {
  104128. if (bones[j].id === jointNode.id) {
  104129. newSkeleton.bones.push(bones[j]);
  104130. break;
  104131. }
  104132. }
  104133. }
  104134. newSkeleton.prepare();
  104135. // Finish
  104136. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  104137. newSkeleton.bones.push(nodesToRootToAdd[i]);
  104138. }
  104139. return newSkeleton;
  104140. };
  104141. /**
  104142. * Imports a mesh and its geometries
  104143. */
  104144. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  104145. if (!newMesh) {
  104146. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  104147. newMesh.id = id;
  104148. }
  104149. if (!node.babylonNode) {
  104150. return newMesh;
  104151. }
  104152. var subMaterials = [];
  104153. var vertexData = null;
  104154. var verticesStarts = new Array();
  104155. var verticesCounts = new Array();
  104156. var indexStarts = new Array();
  104157. var indexCounts = new Array();
  104158. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  104159. var meshID = meshes[meshIndex];
  104160. var mesh = gltfRuntime.meshes[meshID];
  104161. if (!mesh) {
  104162. continue;
  104163. }
  104164. // Positions, normals and UVs
  104165. for (var i = 0; i < mesh.primitives.length; i++) {
  104166. // Temporary vertex data
  104167. var tempVertexData = new BABYLON.VertexData();
  104168. var primitive = mesh.primitives[i];
  104169. if (primitive.mode !== 4) {
  104170. // continue;
  104171. }
  104172. var attributes = primitive.attributes;
  104173. var accessor = null;
  104174. var buffer = null;
  104175. // Set positions, normal and uvs
  104176. for (var semantic in attributes) {
  104177. // Link accessor and buffer view
  104178. accessor = gltfRuntime.accessors[attributes[semantic]];
  104179. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  104180. if (semantic === "NORMAL") {
  104181. tempVertexData.normals = new Float32Array(buffer.length);
  104182. tempVertexData.normals.set(buffer);
  104183. }
  104184. else if (semantic === "POSITION") {
  104185. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  104186. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  104187. for (var j = 0; j < buffer.length; j += 4) {
  104188. tempVertexData.positions[j] = buffer[j];
  104189. tempVertexData.positions[j + 1] = buffer[j + 1];
  104190. tempVertexData.positions[j + 2] = buffer[j + 2];
  104191. }
  104192. }
  104193. else {
  104194. tempVertexData.positions = new Float32Array(buffer.length);
  104195. tempVertexData.positions.set(buffer);
  104196. }
  104197. verticesCounts.push(tempVertexData.positions.length);
  104198. }
  104199. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  104200. var channel = Number(semantic.split("_")[1]);
  104201. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  104202. var uvs = new Float32Array(buffer.length);
  104203. uvs.set(buffer);
  104204. normalizeUVs(uvs);
  104205. tempVertexData.set(uvs, uvKind);
  104206. }
  104207. else if (semantic === "JOINT") {
  104208. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  104209. tempVertexData.matricesIndices.set(buffer);
  104210. }
  104211. else if (semantic === "WEIGHT") {
  104212. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  104213. tempVertexData.matricesWeights.set(buffer);
  104214. }
  104215. else if (semantic === "COLOR") {
  104216. tempVertexData.colors = new Float32Array(buffer.length);
  104217. tempVertexData.colors.set(buffer);
  104218. }
  104219. }
  104220. // Indices
  104221. accessor = gltfRuntime.accessors[primitive.indices];
  104222. if (accessor) {
  104223. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  104224. tempVertexData.indices = new Int32Array(buffer.length);
  104225. tempVertexData.indices.set(buffer);
  104226. indexCounts.push(tempVertexData.indices.length);
  104227. }
  104228. else {
  104229. // Set indices on the fly
  104230. var indices = [];
  104231. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  104232. indices.push(j);
  104233. }
  104234. tempVertexData.indices = new Int32Array(indices);
  104235. indexCounts.push(tempVertexData.indices.length);
  104236. }
  104237. if (!vertexData) {
  104238. vertexData = tempVertexData;
  104239. }
  104240. else {
  104241. vertexData.merge(tempVertexData);
  104242. }
  104243. // Sub material
  104244. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  104245. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  104246. // Update vertices start and index start
  104247. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  104248. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  104249. }
  104250. }
  104251. var material;
  104252. if (subMaterials.length > 1) {
  104253. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  104254. material.subMaterials = subMaterials;
  104255. }
  104256. else {
  104257. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  104258. }
  104259. if (subMaterials.length === 1) {
  104260. material = subMaterials[0];
  104261. }
  104262. if (!newMesh.material) {
  104263. newMesh.material = material;
  104264. }
  104265. // Apply geometry
  104266. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  104267. newMesh.computeWorldMatrix(true);
  104268. // Apply submeshes
  104269. newMesh.subMeshes = [];
  104270. var index = 0;
  104271. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  104272. var meshID = meshes[meshIndex];
  104273. var mesh = gltfRuntime.meshes[meshID];
  104274. if (!mesh) {
  104275. continue;
  104276. }
  104277. for (var i = 0; i < mesh.primitives.length; i++) {
  104278. if (mesh.primitives[i].mode !== 4) {
  104279. //continue;
  104280. }
  104281. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  104282. index++;
  104283. }
  104284. }
  104285. // Finish
  104286. return newMesh;
  104287. };
  104288. /**
  104289. * Configure node transformation from position, rotation and scaling
  104290. */
  104291. var configureNode = function (newNode, position, rotation, scaling) {
  104292. if (newNode.position) {
  104293. newNode.position = position;
  104294. }
  104295. if (newNode.rotationQuaternion || newNode.rotation) {
  104296. newNode.rotationQuaternion = rotation;
  104297. }
  104298. if (newNode.scaling) {
  104299. newNode.scaling = scaling;
  104300. }
  104301. };
  104302. /**
  104303. * Configures node from transformation matrix
  104304. */
  104305. var configureNodeFromMatrix = function (newNode, node, parent) {
  104306. if (node.matrix) {
  104307. var position = new BABYLON.Vector3(0, 0, 0);
  104308. var rotation = new BABYLON.Quaternion();
  104309. var scaling = new BABYLON.Vector3(0, 0, 0);
  104310. var mat = BABYLON.Matrix.FromArray(node.matrix);
  104311. mat.decompose(scaling, rotation, position);
  104312. configureNode(newNode, position, rotation, scaling);
  104313. }
  104314. else if (node.translation && node.rotation && node.scale) {
  104315. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  104316. }
  104317. newNode.computeWorldMatrix(true);
  104318. };
  104319. /**
  104320. * Imports a node
  104321. */
  104322. var importNode = function (gltfRuntime, node, id, parent) {
  104323. var lastNode = null;
  104324. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  104325. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  104326. return null;
  104327. }
  104328. }
  104329. // Meshes
  104330. if (node.skin) {
  104331. if (node.meshes) {
  104332. var skin = gltfRuntime.skins[node.skin];
  104333. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  104334. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  104335. if (newMesh.skeleton === null) {
  104336. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  104337. if (!skin.babylonSkeleton) {
  104338. skin.babylonSkeleton = newMesh.skeleton;
  104339. }
  104340. }
  104341. lastNode = newMesh;
  104342. }
  104343. }
  104344. else if (node.meshes) {
  104345. /**
  104346. * Improve meshes property
  104347. */
  104348. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  104349. lastNode = newMesh;
  104350. }
  104351. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  104352. var light = gltfRuntime.lights[node.light];
  104353. if (light) {
  104354. if (light.type === "ambient") {
  104355. var ambienLight = light[light.type];
  104356. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104357. hemiLight.name = node.name || "";
  104358. if (ambienLight.color) {
  104359. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  104360. }
  104361. lastNode = hemiLight;
  104362. }
  104363. else if (light.type === "directional") {
  104364. var directionalLight = light[light.type];
  104365. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104366. dirLight.name = node.name || "";
  104367. if (directionalLight.color) {
  104368. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  104369. }
  104370. lastNode = dirLight;
  104371. }
  104372. else if (light.type === "point") {
  104373. var pointLight = light[light.type];
  104374. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104375. ptLight.name = node.name || "";
  104376. if (pointLight.color) {
  104377. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  104378. }
  104379. lastNode = ptLight;
  104380. }
  104381. else if (light.type === "spot") {
  104382. var spotLight = light[light.type];
  104383. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  104384. spLight.name = node.name || "";
  104385. if (spotLight.color) {
  104386. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  104387. }
  104388. if (spotLight.fallOfAngle) {
  104389. spLight.angle = spotLight.fallOfAngle;
  104390. }
  104391. if (spotLight.fallOffExponent) {
  104392. spLight.exponent = spotLight.fallOffExponent;
  104393. }
  104394. lastNode = spLight;
  104395. }
  104396. }
  104397. }
  104398. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  104399. var camera = gltfRuntime.cameras[node.camera];
  104400. if (camera) {
  104401. if (camera.type === "orthographic") {
  104402. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104403. orthoCamera.name = node.name || "";
  104404. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  104405. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  104406. lastNode = orthoCamera;
  104407. }
  104408. else if (camera.type === "perspective") {
  104409. var perspectiveCamera = camera[camera.type];
  104410. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  104411. persCamera.name = node.name || "";
  104412. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  104413. if (!perspectiveCamera.aspectRatio) {
  104414. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  104415. }
  104416. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  104417. persCamera.maxZ = perspectiveCamera.zfar;
  104418. persCamera.minZ = perspectiveCamera.znear;
  104419. }
  104420. lastNode = persCamera;
  104421. }
  104422. }
  104423. }
  104424. // Empty node
  104425. if (!node.jointName) {
  104426. if (node.babylonNode) {
  104427. return node.babylonNode;
  104428. }
  104429. else if (lastNode === null) {
  104430. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  104431. node.babylonNode = dummy;
  104432. lastNode = dummy;
  104433. }
  104434. }
  104435. if (lastNode !== null) {
  104436. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  104437. configureNodeFromMatrix(lastNode, node, parent);
  104438. }
  104439. else {
  104440. var translation = node.translation || [0, 0, 0];
  104441. var rotation = node.rotation || [0, 0, 0, 1];
  104442. var scale = node.scale || [1, 1, 1];
  104443. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  104444. }
  104445. lastNode.updateCache(true);
  104446. node.babylonNode = lastNode;
  104447. }
  104448. return lastNode;
  104449. };
  104450. /**
  104451. * Traverses nodes and creates them
  104452. */
  104453. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  104454. if (meshIncluded === void 0) { meshIncluded = false; }
  104455. var node = gltfRuntime.nodes[id];
  104456. var newNode = null;
  104457. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  104458. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  104459. meshIncluded = true;
  104460. }
  104461. else {
  104462. meshIncluded = false;
  104463. }
  104464. }
  104465. else {
  104466. meshIncluded = true;
  104467. }
  104468. if (!node.jointName && meshIncluded) {
  104469. newNode = importNode(gltfRuntime, node, id, parent);
  104470. if (newNode !== null) {
  104471. newNode.id = id;
  104472. newNode.parent = parent;
  104473. }
  104474. }
  104475. if (node.children) {
  104476. for (var i = 0; i < node.children.length; i++) {
  104477. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  104478. }
  104479. }
  104480. };
  104481. /**
  104482. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  104483. */
  104484. var postLoad = function (gltfRuntime) {
  104485. // Nodes
  104486. var currentScene = gltfRuntime.currentScene;
  104487. if (currentScene) {
  104488. for (var i = 0; i < currentScene.nodes.length; i++) {
  104489. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104490. }
  104491. }
  104492. else {
  104493. for (var thing in gltfRuntime.scenes) {
  104494. currentScene = gltfRuntime.scenes[thing];
  104495. for (var i = 0; i < currentScene.nodes.length; i++) {
  104496. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  104497. }
  104498. }
  104499. }
  104500. // Set animations
  104501. loadAnimations(gltfRuntime);
  104502. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  104503. var skeleton = gltfRuntime.scene.skeletons[i];
  104504. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  104505. }
  104506. };
  104507. /**
  104508. * onBind shaderrs callback to set uniforms and matrices
  104509. */
  104510. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  104511. var materialValues = material.values || technique.parameters;
  104512. for (var unif in unTreatedUniforms) {
  104513. var uniform = unTreatedUniforms[unif];
  104514. var type = uniform.type;
  104515. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  104516. if (uniform.semantic && !uniform.source && !uniform.node) {
  104517. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  104518. }
  104519. else if (uniform.semantic && (uniform.source || uniform.node)) {
  104520. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  104521. if (source === null) {
  104522. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  104523. }
  104524. if (source === null) {
  104525. continue;
  104526. }
  104527. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  104528. }
  104529. }
  104530. else {
  104531. var value = materialValues[technique.uniforms[unif]];
  104532. if (!value) {
  104533. continue;
  104534. }
  104535. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  104536. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  104537. if (texture === null || texture === undefined) {
  104538. continue;
  104539. }
  104540. shaderMaterial.getEffect().setTexture(unif, texture);
  104541. }
  104542. else {
  104543. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  104544. }
  104545. }
  104546. }
  104547. onSuccess(shaderMaterial);
  104548. };
  104549. /**
  104550. * Prepare uniforms to send the only one time
  104551. * Loads the appropriate textures
  104552. */
  104553. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  104554. var materialValues = material.values || technique.parameters;
  104555. var techniqueUniforms = technique.uniforms;
  104556. /**
  104557. * Prepare values here (not matrices)
  104558. */
  104559. for (var unif in unTreatedUniforms) {
  104560. var uniform = unTreatedUniforms[unif];
  104561. var type = uniform.type;
  104562. var value = materialValues[techniqueUniforms[unif]];
  104563. if (value === undefined) {
  104564. // In case the value is the same for all materials
  104565. value = uniform.value;
  104566. }
  104567. if (!value) {
  104568. continue;
  104569. }
  104570. var onLoadTexture = function (uniformName) {
  104571. return function (texture) {
  104572. if (uniform.value && uniformName) {
  104573. // Static uniform
  104574. shaderMaterial.setTexture(uniformName, texture);
  104575. delete unTreatedUniforms[uniformName];
  104576. }
  104577. };
  104578. };
  104579. // Texture (sampler2D)
  104580. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  104581. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  104582. }
  104583. else {
  104584. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  104585. // Static uniform
  104586. delete unTreatedUniforms[unif];
  104587. }
  104588. }
  104589. }
  104590. };
  104591. /**
  104592. * Shader compilation failed
  104593. */
  104594. var onShaderCompileError = function (program, shaderMaterial, onError) {
  104595. return function (effect, error) {
  104596. shaderMaterial.dispose(true);
  104597. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  104598. };
  104599. };
  104600. /**
  104601. * Shader compilation success
  104602. */
  104603. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  104604. return function (_) {
  104605. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  104606. shaderMaterial.onBind = function (mesh) {
  104607. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  104608. };
  104609. };
  104610. };
  104611. /**
  104612. * Returns the appropriate uniform if already handled by babylon
  104613. */
  104614. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  104615. for (var unif in technique.uniforms) {
  104616. var uniform = technique.uniforms[unif];
  104617. var uniformParameter = technique.parameters[uniform];
  104618. if (tokenizer.currentIdentifier === unif) {
  104619. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  104620. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  104621. if (transformIndex !== -1) {
  104622. delete unTreatedUniforms[unif];
  104623. return babylonTransforms[transformIndex];
  104624. }
  104625. }
  104626. }
  104627. }
  104628. return tokenizer.currentIdentifier;
  104629. };
  104630. /**
  104631. * All shaders loaded. Create materials one by one
  104632. */
  104633. var importMaterials = function (gltfRuntime) {
  104634. // Create materials
  104635. for (var mat in gltfRuntime.materials) {
  104636. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  104637. }
  104638. };
  104639. /**
  104640. * Implementation of the base glTF spec
  104641. */
  104642. var GLTFLoaderBase = /** @class */ (function () {
  104643. function GLTFLoaderBase() {
  104644. }
  104645. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  104646. var gltfRuntime = {
  104647. extensions: {},
  104648. accessors: {},
  104649. buffers: {},
  104650. bufferViews: {},
  104651. meshes: {},
  104652. lights: {},
  104653. cameras: {},
  104654. nodes: {},
  104655. images: {},
  104656. textures: {},
  104657. shaders: {},
  104658. programs: {},
  104659. samplers: {},
  104660. techniques: {},
  104661. materials: {},
  104662. animations: {},
  104663. skins: {},
  104664. extensionsUsed: [],
  104665. scenes: {},
  104666. buffersCount: 0,
  104667. shaderscount: 0,
  104668. scene: scene,
  104669. rootUrl: rootUrl,
  104670. loadedBufferCount: 0,
  104671. loadedBufferViews: {},
  104672. loadedShaderCount: 0,
  104673. importOnlyMeshes: false,
  104674. dummyNodes: []
  104675. };
  104676. // Parse
  104677. if (parsedData.extensions) {
  104678. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  104679. }
  104680. if (parsedData.extensionsUsed) {
  104681. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  104682. }
  104683. if (parsedData.buffers) {
  104684. parseBuffers(parsedData.buffers, gltfRuntime);
  104685. }
  104686. if (parsedData.bufferViews) {
  104687. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  104688. }
  104689. if (parsedData.accessors) {
  104690. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  104691. }
  104692. if (parsedData.meshes) {
  104693. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  104694. }
  104695. if (parsedData.lights) {
  104696. parseObject(parsedData.lights, "lights", gltfRuntime);
  104697. }
  104698. if (parsedData.cameras) {
  104699. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  104700. }
  104701. if (parsedData.nodes) {
  104702. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  104703. }
  104704. if (parsedData.images) {
  104705. parseObject(parsedData.images, "images", gltfRuntime);
  104706. }
  104707. if (parsedData.textures) {
  104708. parseObject(parsedData.textures, "textures", gltfRuntime);
  104709. }
  104710. if (parsedData.shaders) {
  104711. parseShaders(parsedData.shaders, gltfRuntime);
  104712. }
  104713. if (parsedData.programs) {
  104714. parseObject(parsedData.programs, "programs", gltfRuntime);
  104715. }
  104716. if (parsedData.samplers) {
  104717. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  104718. }
  104719. if (parsedData.techniques) {
  104720. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  104721. }
  104722. if (parsedData.materials) {
  104723. parseObject(parsedData.materials, "materials", gltfRuntime);
  104724. }
  104725. if (parsedData.animations) {
  104726. parseObject(parsedData.animations, "animations", gltfRuntime);
  104727. }
  104728. if (parsedData.skins) {
  104729. parseObject(parsedData.skins, "skins", gltfRuntime);
  104730. }
  104731. if (parsedData.scenes) {
  104732. gltfRuntime.scenes = parsedData.scenes;
  104733. }
  104734. if (parsedData.scene && parsedData.scenes) {
  104735. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  104736. }
  104737. return gltfRuntime;
  104738. };
  104739. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104740. var buffer = gltfRuntime.buffers[id];
  104741. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  104742. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  104743. }
  104744. else {
  104745. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  104746. if (request) {
  104747. onError(request.status + " " + request.statusText);
  104748. }
  104749. });
  104750. }
  104751. };
  104752. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104753. var texture = gltfRuntime.textures[id];
  104754. if (!texture || !texture.source) {
  104755. onError("");
  104756. return;
  104757. }
  104758. if (texture.babylonTexture) {
  104759. onSuccess(null);
  104760. return;
  104761. }
  104762. var source = gltfRuntime.images[texture.source];
  104763. if (BABYLON.Tools.IsBase64(source.uri)) {
  104764. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  104765. }
  104766. else {
  104767. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  104768. if (request) {
  104769. onError(request.status + " " + request.statusText);
  104770. }
  104771. });
  104772. }
  104773. };
  104774. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104775. var texture = gltfRuntime.textures[id];
  104776. if (texture.babylonTexture) {
  104777. onSuccess(texture.babylonTexture);
  104778. return;
  104779. }
  104780. var sampler = gltfRuntime.samplers[texture.sampler];
  104781. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  104782. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  104783. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  104784. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  104785. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  104786. var blob = new Blob([buffer]);
  104787. var blobURL = URL.createObjectURL(blob);
  104788. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  104789. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  104790. if (sampler.wrapS !== undefined) {
  104791. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  104792. }
  104793. if (sampler.wrapT !== undefined) {
  104794. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  104795. }
  104796. newTexture.name = id;
  104797. texture.babylonTexture = newTexture;
  104798. onSuccess(newTexture);
  104799. };
  104800. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104801. var shader = gltfRuntime.shaders[id];
  104802. if (BABYLON.Tools.IsBase64(shader.uri)) {
  104803. var shaderString = atob(shader.uri.split(",")[1]);
  104804. onSuccess(shaderString);
  104805. }
  104806. else {
  104807. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  104808. if (request) {
  104809. onError(request.status + " " + request.statusText);
  104810. }
  104811. });
  104812. }
  104813. };
  104814. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104815. var material = gltfRuntime.materials[id];
  104816. if (!material.technique) {
  104817. if (onError) {
  104818. onError("No technique found.");
  104819. }
  104820. return;
  104821. }
  104822. var technique = gltfRuntime.techniques[material.technique];
  104823. if (!technique) {
  104824. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  104825. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  104826. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104827. onSuccess(defaultMaterial);
  104828. return;
  104829. }
  104830. var program = gltfRuntime.programs[technique.program];
  104831. var states = technique.states;
  104832. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  104833. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  104834. var newVertexShader = "";
  104835. var newPixelShader = "";
  104836. var vertexTokenizer = new Tokenizer(vertexShader);
  104837. var pixelTokenizer = new Tokenizer(pixelShader);
  104838. var unTreatedUniforms = {};
  104839. var uniforms = [];
  104840. var attributes = [];
  104841. var samplers = [];
  104842. // Fill uniform, sampler2D and attributes
  104843. for (var unif in technique.uniforms) {
  104844. var uniform = technique.uniforms[unif];
  104845. var uniformParameter = technique.parameters[uniform];
  104846. unTreatedUniforms[unif] = uniformParameter;
  104847. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  104848. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  104849. if (transformIndex !== -1) {
  104850. uniforms.push(babylonTransforms[transformIndex]);
  104851. delete unTreatedUniforms[unif];
  104852. }
  104853. else {
  104854. uniforms.push(unif);
  104855. }
  104856. }
  104857. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  104858. samplers.push(unif);
  104859. }
  104860. else {
  104861. uniforms.push(unif);
  104862. }
  104863. }
  104864. for (var attr in technique.attributes) {
  104865. var attribute = technique.attributes[attr];
  104866. var attributeParameter = technique.parameters[attribute];
  104867. if (attributeParameter.semantic) {
  104868. attributes.push(getAttribute(attributeParameter));
  104869. }
  104870. }
  104871. // Configure vertex shader
  104872. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  104873. var tokenType = vertexTokenizer.currentToken;
  104874. if (tokenType !== ETokenType.IDENTIFIER) {
  104875. newVertexShader += vertexTokenizer.currentString;
  104876. continue;
  104877. }
  104878. var foundAttribute = false;
  104879. for (var attr in technique.attributes) {
  104880. var attribute = technique.attributes[attr];
  104881. var attributeParameter = technique.parameters[attribute];
  104882. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  104883. newVertexShader += getAttribute(attributeParameter);
  104884. foundAttribute = true;
  104885. break;
  104886. }
  104887. }
  104888. if (foundAttribute) {
  104889. continue;
  104890. }
  104891. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  104892. }
  104893. // Configure pixel shader
  104894. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  104895. var tokenType = pixelTokenizer.currentToken;
  104896. if (tokenType !== ETokenType.IDENTIFIER) {
  104897. newPixelShader += pixelTokenizer.currentString;
  104898. continue;
  104899. }
  104900. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  104901. }
  104902. // Create shader material
  104903. var shaderPath = {
  104904. vertex: program.vertexShader + id,
  104905. fragment: program.fragmentShader + id
  104906. };
  104907. var options = {
  104908. attributes: attributes,
  104909. uniforms: uniforms,
  104910. samplers: samplers,
  104911. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  104912. };
  104913. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  104914. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  104915. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  104916. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  104917. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  104918. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104919. if (states && states.functions) {
  104920. var functions = states.functions;
  104921. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  104922. shaderMaterial.backFaceCulling = false;
  104923. }
  104924. var blendFunc = functions.blendFuncSeparate;
  104925. if (blendFunc) {
  104926. 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) {
  104927. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  104928. }
  104929. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104930. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  104931. }
  104932. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104933. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  104934. }
  104935. 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) {
  104936. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  104937. }
  104938. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  104939. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  104940. }
  104941. 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) {
  104942. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  104943. }
  104944. }
  104945. }
  104946. };
  104947. return GLTFLoaderBase;
  104948. }());
  104949. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  104950. /**
  104951. * glTF V1 Loader
  104952. */
  104953. var GLTFLoader = /** @class */ (function () {
  104954. function GLTFLoader() {
  104955. // #region Stubs for IGLTFLoader interface
  104956. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104957. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104958. this.compileMaterials = false;
  104959. this.useClipPlane = false;
  104960. this.compileShadowGenerators = false;
  104961. this.onDisposeObservable = new BABYLON.Observable();
  104962. this.onMeshLoadedObservable = new BABYLON.Observable();
  104963. this.onTextureLoadedObservable = new BABYLON.Observable();
  104964. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104965. this.onCompleteObservable = new BABYLON.Observable();
  104966. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104967. this.state = null;
  104968. }
  104969. GLTFLoader.RegisterExtension = function (extension) {
  104970. if (GLTFLoader.Extensions[extension.name]) {
  104971. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  104972. return;
  104973. }
  104974. GLTFLoader.Extensions[extension.name] = extension;
  104975. };
  104976. GLTFLoader.prototype.dispose = function () { };
  104977. // #endregion
  104978. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  104979. var _this = this;
  104980. scene.useRightHandedSystem = true;
  104981. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  104982. gltfRuntime.importOnlyMeshes = true;
  104983. if (meshesNames === "") {
  104984. gltfRuntime.importMeshesNames = [];
  104985. }
  104986. else if (typeof meshesNames === "string") {
  104987. gltfRuntime.importMeshesNames = [meshesNames];
  104988. }
  104989. else if (meshesNames && !(meshesNames instanceof Array)) {
  104990. gltfRuntime.importMeshesNames = [meshesNames];
  104991. }
  104992. else {
  104993. gltfRuntime.importMeshesNames = [];
  104994. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  104995. }
  104996. // Create nodes
  104997. _this._createNodes(gltfRuntime);
  104998. var meshes = new Array();
  104999. var skeletons = new Array();
  105000. // Fill arrays of meshes and skeletons
  105001. for (var nde in gltfRuntime.nodes) {
  105002. var node = gltfRuntime.nodes[nde];
  105003. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  105004. meshes.push(node.babylonNode);
  105005. }
  105006. }
  105007. for (var skl in gltfRuntime.skins) {
  105008. var skin = gltfRuntime.skins[skl];
  105009. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  105010. skeletons.push(skin.babylonSkeleton);
  105011. }
  105012. }
  105013. // Load buffers, shaders, materials, etc.
  105014. _this._loadBuffersAsync(gltfRuntime, function () {
  105015. _this._loadShadersAsync(gltfRuntime, function () {
  105016. importMaterials(gltfRuntime);
  105017. postLoad(gltfRuntime);
  105018. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  105019. onSuccess(meshes, [], skeletons);
  105020. }
  105021. });
  105022. }, onProgress);
  105023. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  105024. onSuccess(meshes, [], skeletons);
  105025. }
  105026. }, onError);
  105027. return true;
  105028. };
  105029. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105030. var _this = this;
  105031. return new Promise(function (resolve, reject) {
  105032. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  105033. resolve({
  105034. meshes: meshes,
  105035. particleSystems: particleSystems,
  105036. skeletons: skeletons
  105037. });
  105038. }, onProgress, function (message) {
  105039. reject(new Error(message));
  105040. });
  105041. });
  105042. };
  105043. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  105044. var _this = this;
  105045. scene.useRightHandedSystem = true;
  105046. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  105047. // Load runtime extensios
  105048. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  105049. // Create nodes
  105050. _this._createNodes(gltfRuntime);
  105051. // Load buffers, shaders, materials, etc.
  105052. _this._loadBuffersAsync(gltfRuntime, function () {
  105053. _this._loadShadersAsync(gltfRuntime, function () {
  105054. importMaterials(gltfRuntime);
  105055. postLoad(gltfRuntime);
  105056. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  105057. onSuccess();
  105058. }
  105059. });
  105060. });
  105061. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  105062. onSuccess();
  105063. }
  105064. }, onError);
  105065. }, onError);
  105066. };
  105067. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105068. var _this = this;
  105069. return new Promise(function (resolve, reject) {
  105070. _this._loadAsync(scene, data, rootUrl, function () {
  105071. resolve();
  105072. }, onProgress, function (message) {
  105073. reject(new Error(message));
  105074. });
  105075. });
  105076. };
  105077. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  105078. var hasShaders = false;
  105079. var processShader = function (sha, shader) {
  105080. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  105081. gltfRuntime.loadedShaderCount++;
  105082. if (shaderString) {
  105083. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  105084. }
  105085. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  105086. onload();
  105087. }
  105088. }, function () {
  105089. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  105090. });
  105091. };
  105092. for (var sha in gltfRuntime.shaders) {
  105093. hasShaders = true;
  105094. var shader = gltfRuntime.shaders[sha];
  105095. if (shader) {
  105096. processShader.bind(this, sha, shader)();
  105097. }
  105098. else {
  105099. BABYLON.Tools.Error("No shader named: " + sha);
  105100. }
  105101. }
  105102. if (!hasShaders) {
  105103. onload();
  105104. }
  105105. };
  105106. ;
  105107. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  105108. var hasBuffers = false;
  105109. var processBuffer = function (buf, buffer) {
  105110. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  105111. gltfRuntime.loadedBufferCount++;
  105112. if (bufferView) {
  105113. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  105114. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  105115. }
  105116. gltfRuntime.loadedBufferViews[buf] = bufferView;
  105117. }
  105118. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  105119. onLoad();
  105120. }
  105121. }, function () {
  105122. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  105123. });
  105124. };
  105125. for (var buf in gltfRuntime.buffers) {
  105126. hasBuffers = true;
  105127. var buffer = gltfRuntime.buffers[buf];
  105128. if (buffer) {
  105129. processBuffer.bind(this, buf, buffer)();
  105130. }
  105131. else {
  105132. BABYLON.Tools.Error("No buffer named: " + buf);
  105133. }
  105134. }
  105135. if (!hasBuffers) {
  105136. onLoad();
  105137. }
  105138. };
  105139. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  105140. var currentScene = gltfRuntime.currentScene;
  105141. if (currentScene) {
  105142. // Only one scene even if multiple scenes are defined
  105143. for (var i = 0; i < currentScene.nodes.length; i++) {
  105144. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105145. }
  105146. }
  105147. else {
  105148. // Load all scenes
  105149. for (var thing in gltfRuntime.scenes) {
  105150. currentScene = gltfRuntime.scenes[thing];
  105151. for (var i = 0; i < currentScene.nodes.length; i++) {
  105152. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  105153. }
  105154. }
  105155. }
  105156. };
  105157. GLTFLoader.Extensions = {};
  105158. return GLTFLoader;
  105159. }());
  105160. GLTF1.GLTFLoader = GLTFLoader;
  105161. ;
  105162. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  105163. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105164. })(BABYLON || (BABYLON = {}));
  105165. //# sourceMappingURL=babylon.glTFLoader.js.map
  105166. var BABYLON;
  105167. (function (BABYLON) {
  105168. var GLTF1;
  105169. (function (GLTF1) {
  105170. /**
  105171. * Utils functions for GLTF
  105172. */
  105173. var GLTFUtils = /** @class */ (function () {
  105174. function GLTFUtils() {
  105175. }
  105176. /**
  105177. * Sets the given "parameter" matrix
  105178. * @param scene: the {BABYLON.Scene} object
  105179. * @param source: the source node where to pick the matrix
  105180. * @param parameter: the GLTF technique parameter
  105181. * @param uniformName: the name of the shader's uniform
  105182. * @param shaderMaterial: the shader material
  105183. */
  105184. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  105185. var mat = null;
  105186. if (parameter.semantic === "MODEL") {
  105187. mat = source.getWorldMatrix();
  105188. }
  105189. else if (parameter.semantic === "PROJECTION") {
  105190. mat = scene.getProjectionMatrix();
  105191. }
  105192. else if (parameter.semantic === "VIEW") {
  105193. mat = scene.getViewMatrix();
  105194. }
  105195. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  105196. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  105197. }
  105198. else if (parameter.semantic === "MODELVIEW") {
  105199. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  105200. }
  105201. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  105202. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  105203. }
  105204. else if (parameter.semantic === "MODELINVERSE") {
  105205. mat = source.getWorldMatrix().invert();
  105206. }
  105207. else if (parameter.semantic === "VIEWINVERSE") {
  105208. mat = scene.getViewMatrix().invert();
  105209. }
  105210. else if (parameter.semantic === "PROJECTIONINVERSE") {
  105211. mat = scene.getProjectionMatrix().invert();
  105212. }
  105213. else if (parameter.semantic === "MODELVIEWINVERSE") {
  105214. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  105215. }
  105216. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  105217. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  105218. }
  105219. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  105220. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  105221. }
  105222. else {
  105223. debugger;
  105224. }
  105225. if (mat) {
  105226. switch (parameter.type) {
  105227. case GLTF1.EParameterType.FLOAT_MAT2:
  105228. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  105229. break;
  105230. case GLTF1.EParameterType.FLOAT_MAT3:
  105231. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  105232. break;
  105233. case GLTF1.EParameterType.FLOAT_MAT4:
  105234. shaderMaterial.setMatrix(uniformName, mat);
  105235. break;
  105236. default: break;
  105237. }
  105238. }
  105239. };
  105240. /**
  105241. * Sets the given "parameter" matrix
  105242. * @param shaderMaterial: the shader material
  105243. * @param uniform: the name of the shader's uniform
  105244. * @param value: the value of the uniform
  105245. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  105246. */
  105247. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  105248. switch (type) {
  105249. case GLTF1.EParameterType.FLOAT:
  105250. shaderMaterial.setFloat(uniform, value);
  105251. return true;
  105252. case GLTF1.EParameterType.FLOAT_VEC2:
  105253. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  105254. return true;
  105255. case GLTF1.EParameterType.FLOAT_VEC3:
  105256. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  105257. return true;
  105258. case GLTF1.EParameterType.FLOAT_VEC4:
  105259. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  105260. return true;
  105261. default: return false;
  105262. }
  105263. };
  105264. /**
  105265. * Returns the wrap mode of the texture
  105266. * @param mode: the mode value
  105267. */
  105268. GLTFUtils.GetWrapMode = function (mode) {
  105269. switch (mode) {
  105270. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105271. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105272. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105273. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105274. }
  105275. };
  105276. /**
  105277. * Returns the byte stride giving an accessor
  105278. * @param accessor: the GLTF accessor objet
  105279. */
  105280. GLTFUtils.GetByteStrideFromType = function (accessor) {
  105281. // Needs this function since "byteStride" isn't requiered in glTF format
  105282. var type = accessor.type;
  105283. switch (type) {
  105284. case "VEC2": return 2;
  105285. case "VEC3": return 3;
  105286. case "VEC4": return 4;
  105287. case "MAT2": return 4;
  105288. case "MAT3": return 9;
  105289. case "MAT4": return 16;
  105290. default: return 1;
  105291. }
  105292. };
  105293. /**
  105294. * Returns the texture filter mode giving a mode value
  105295. * @param mode: the filter mode value
  105296. */
  105297. GLTFUtils.GetTextureFilterMode = function (mode) {
  105298. switch (mode) {
  105299. case GLTF1.ETextureFilterType.LINEAR:
  105300. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  105301. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  105302. case GLTF1.ETextureFilterType.NEAREST:
  105303. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  105304. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  105305. }
  105306. };
  105307. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  105308. var byteOffset = bufferView.byteOffset + byteOffset;
  105309. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  105310. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  105311. throw new Error("Buffer access is out of range");
  105312. }
  105313. var buffer = loadedBufferView.buffer;
  105314. byteOffset += loadedBufferView.byteOffset;
  105315. switch (componentType) {
  105316. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  105317. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  105318. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  105319. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  105320. default: return new Float32Array(buffer, byteOffset, byteLength);
  105321. }
  105322. };
  105323. /**
  105324. * Returns a buffer from its accessor
  105325. * @param gltfRuntime: the GLTF runtime
  105326. * @param accessor: the GLTF accessor
  105327. */
  105328. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  105329. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  105330. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  105331. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  105332. };
  105333. /**
  105334. * Decodes a buffer view into a string
  105335. * @param view: the buffer view
  105336. */
  105337. GLTFUtils.DecodeBufferToText = function (view) {
  105338. var result = "";
  105339. var length = view.byteLength;
  105340. for (var i = 0; i < length; ++i) {
  105341. result += String.fromCharCode(view[i]);
  105342. }
  105343. return result;
  105344. };
  105345. /**
  105346. * Returns the default material of gltf. Related to
  105347. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  105348. * @param scene: the Babylon.js scene
  105349. */
  105350. GLTFUtils.GetDefaultMaterial = function (scene) {
  105351. if (!GLTFUtils._DefaultMaterial) {
  105352. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  105353. "precision highp float;",
  105354. "",
  105355. "uniform mat4 worldView;",
  105356. "uniform mat4 projection;",
  105357. "",
  105358. "attribute vec3 position;",
  105359. "",
  105360. "void main(void)",
  105361. "{",
  105362. " gl_Position = projection * worldView * vec4(position, 1.0);",
  105363. "}"
  105364. ].join("\n");
  105365. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  105366. "precision highp float;",
  105367. "",
  105368. "uniform vec4 u_emission;",
  105369. "",
  105370. "void main(void)",
  105371. "{",
  105372. " gl_FragColor = u_emission;",
  105373. "}"
  105374. ].join("\n");
  105375. var shaderPath = {
  105376. vertex: "GLTFDefaultMaterial",
  105377. fragment: "GLTFDefaultMaterial"
  105378. };
  105379. var options = {
  105380. attributes: ["position"],
  105381. uniforms: ["worldView", "projection", "u_emission"],
  105382. samplers: new Array(),
  105383. needAlphaBlending: false
  105384. };
  105385. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  105386. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  105387. }
  105388. return GLTFUtils._DefaultMaterial;
  105389. };
  105390. // The GLTF default material
  105391. GLTFUtils._DefaultMaterial = null;
  105392. return GLTFUtils;
  105393. }());
  105394. GLTF1.GLTFUtils = GLTFUtils;
  105395. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105396. })(BABYLON || (BABYLON = {}));
  105397. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  105398. var BABYLON;
  105399. (function (BABYLON) {
  105400. var GLTF1;
  105401. (function (GLTF1) {
  105402. var GLTFLoaderExtension = /** @class */ (function () {
  105403. function GLTFLoaderExtension(name) {
  105404. this._name = name;
  105405. }
  105406. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  105407. get: function () {
  105408. return this._name;
  105409. },
  105410. enumerable: true,
  105411. configurable: true
  105412. });
  105413. /**
  105414. * Defines an override for loading the runtime
  105415. * Return true to stop further extensions from loading the runtime
  105416. */
  105417. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105418. return false;
  105419. };
  105420. /**
  105421. * Defines an onverride for creating gltf runtime
  105422. * Return true to stop further extensions from creating the runtime
  105423. */
  105424. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105425. return false;
  105426. };
  105427. /**
  105428. * Defines an override for loading buffers
  105429. * Return true to stop further extensions from loading this buffer
  105430. */
  105431. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105432. return false;
  105433. };
  105434. /**
  105435. * Defines an override for loading texture buffers
  105436. * Return true to stop further extensions from loading this texture data
  105437. */
  105438. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105439. return false;
  105440. };
  105441. /**
  105442. * Defines an override for creating textures
  105443. * Return true to stop further extensions from loading this texture
  105444. */
  105445. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105446. return false;
  105447. };
  105448. /**
  105449. * Defines an override for loading shader strings
  105450. * Return true to stop further extensions from loading this shader data
  105451. */
  105452. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105453. return false;
  105454. };
  105455. /**
  105456. * Defines an override for loading materials
  105457. * Return true to stop further extensions from loading this material
  105458. */
  105459. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105460. return false;
  105461. };
  105462. // ---------
  105463. // Utilities
  105464. // ---------
  105465. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105466. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105467. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  105468. }, function () {
  105469. setTimeout(function () {
  105470. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  105471. });
  105472. });
  105473. };
  105474. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105475. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105476. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  105477. }, function () {
  105478. setTimeout(function () {
  105479. onSuccess();
  105480. });
  105481. });
  105482. };
  105483. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  105484. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105485. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  105486. }, function () {
  105487. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  105488. });
  105489. };
  105490. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  105491. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  105492. };
  105493. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105494. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105495. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  105496. }, function () {
  105497. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  105498. });
  105499. };
  105500. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105501. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105502. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  105503. }, function () {
  105504. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  105505. });
  105506. };
  105507. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105508. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105509. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  105510. }, function () {
  105511. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  105512. });
  105513. };
  105514. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  105515. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  105516. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105517. }, function () {
  105518. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  105519. });
  105520. };
  105521. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  105522. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  105523. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  105524. if (func(loaderExtension)) {
  105525. return;
  105526. }
  105527. }
  105528. defaultFunc();
  105529. };
  105530. return GLTFLoaderExtension;
  105531. }());
  105532. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  105533. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105534. })(BABYLON || (BABYLON = {}));
  105535. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105536. var BABYLON;
  105537. (function (BABYLON) {
  105538. var GLTF1;
  105539. (function (GLTF1) {
  105540. var BinaryExtensionBufferName = "binary_glTF";
  105541. ;
  105542. ;
  105543. var GLTFBinaryExtension = /** @class */ (function (_super) {
  105544. __extends(GLTFBinaryExtension, _super);
  105545. function GLTFBinaryExtension() {
  105546. return _super.call(this, "KHR_binary_glTF") || this;
  105547. }
  105548. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  105549. var extensionsUsed = data.json.extensionsUsed;
  105550. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  105551. return false;
  105552. }
  105553. this._bin = data.bin;
  105554. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  105555. return true;
  105556. };
  105557. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105558. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  105559. return false;
  105560. }
  105561. if (id !== BinaryExtensionBufferName) {
  105562. return false;
  105563. }
  105564. onSuccess(this._bin);
  105565. return true;
  105566. };
  105567. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  105568. var texture = gltfRuntime.textures[id];
  105569. var source = gltfRuntime.images[texture.source];
  105570. if (!source.extensions || !(this.name in source.extensions)) {
  105571. return false;
  105572. }
  105573. var sourceExt = source.extensions[this.name];
  105574. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  105575. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  105576. onSuccess(buffer);
  105577. return true;
  105578. };
  105579. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  105580. var shader = gltfRuntime.shaders[id];
  105581. if (!shader.extensions || !(this.name in shader.extensions)) {
  105582. return false;
  105583. }
  105584. var binaryExtensionShader = shader.extensions[this.name];
  105585. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  105586. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  105587. setTimeout(function () {
  105588. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  105589. onSuccess(shaderString);
  105590. });
  105591. return true;
  105592. };
  105593. return GLTFBinaryExtension;
  105594. }(GLTF1.GLTFLoaderExtension));
  105595. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  105596. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  105597. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105598. })(BABYLON || (BABYLON = {}));
  105599. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  105600. var BABYLON;
  105601. (function (BABYLON) {
  105602. var GLTF1;
  105603. (function (GLTF1) {
  105604. ;
  105605. ;
  105606. ;
  105607. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  105608. __extends(GLTFMaterialsCommonExtension, _super);
  105609. function GLTFMaterialsCommonExtension() {
  105610. return _super.call(this, "KHR_materials_common") || this;
  105611. }
  105612. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  105613. if (!gltfRuntime.extensions)
  105614. return false;
  105615. var extension = gltfRuntime.extensions[this.name];
  105616. if (!extension)
  105617. return false;
  105618. // Create lights
  105619. var lights = extension.lights;
  105620. if (lights) {
  105621. for (var thing in lights) {
  105622. var light = lights[thing];
  105623. switch (light.type) {
  105624. case "ambient":
  105625. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  105626. var ambient = light.ambient;
  105627. if (ambient) {
  105628. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  105629. }
  105630. break;
  105631. case "point":
  105632. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  105633. var point = light.point;
  105634. if (point) {
  105635. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  105636. }
  105637. break;
  105638. case "directional":
  105639. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  105640. var directional = light.directional;
  105641. if (directional) {
  105642. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  105643. }
  105644. break;
  105645. case "spot":
  105646. var spot = light.spot;
  105647. if (spot) {
  105648. 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);
  105649. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  105650. }
  105651. break;
  105652. default:
  105653. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  105654. break;
  105655. }
  105656. }
  105657. }
  105658. return false;
  105659. };
  105660. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  105661. var material = gltfRuntime.materials[id];
  105662. if (!material || !material.extensions)
  105663. return false;
  105664. var extension = material.extensions[this.name];
  105665. if (!extension)
  105666. return false;
  105667. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  105668. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  105669. if (extension.technique === "CONSTANT") {
  105670. standardMaterial.disableLighting = true;
  105671. }
  105672. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  105673. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  105674. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  105675. // Ambient
  105676. if (typeof extension.values.ambient === "string") {
  105677. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  105678. }
  105679. else {
  105680. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  105681. }
  105682. // Diffuse
  105683. if (typeof extension.values.diffuse === "string") {
  105684. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  105685. }
  105686. else {
  105687. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  105688. }
  105689. // Emission
  105690. if (typeof extension.values.emission === "string") {
  105691. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  105692. }
  105693. else {
  105694. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  105695. }
  105696. // Specular
  105697. if (typeof extension.values.specular === "string") {
  105698. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  105699. }
  105700. else {
  105701. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  105702. }
  105703. return true;
  105704. };
  105705. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  105706. // Create buffer from texture url
  105707. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  105708. // Create texture from buffer
  105709. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  105710. }, onError);
  105711. };
  105712. return GLTFMaterialsCommonExtension;
  105713. }(GLTF1.GLTFLoaderExtension));
  105714. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  105715. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  105716. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  105717. })(BABYLON || (BABYLON = {}));
  105718. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  105719. var BABYLON;
  105720. (function (BABYLON) {
  105721. var GLTF2;
  105722. (function (GLTF2) {
  105723. var ArrayItem = /** @class */ (function () {
  105724. function ArrayItem() {
  105725. }
  105726. ArrayItem.Assign = function (values) {
  105727. if (values) {
  105728. for (var index = 0; index < values.length; index++) {
  105729. values[index]._index = index;
  105730. }
  105731. }
  105732. };
  105733. return ArrayItem;
  105734. }());
  105735. GLTF2.ArrayItem = ArrayItem;
  105736. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105737. })(BABYLON || (BABYLON = {}));
  105738. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  105739. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  105740. var BABYLON;
  105741. (function (BABYLON) {
  105742. var GLTF2;
  105743. (function (GLTF2) {
  105744. var GLTFLoader = /** @class */ (function () {
  105745. function GLTFLoader() {
  105746. this._completePromises = new Array();
  105747. this._disposed = false;
  105748. this._state = null;
  105749. this._extensions = {};
  105750. this._defaultSampler = {};
  105751. this._requests = new Array();
  105752. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  105753. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  105754. this.compileMaterials = false;
  105755. this.useClipPlane = false;
  105756. this.compileShadowGenerators = false;
  105757. this.onDisposeObservable = new BABYLON.Observable();
  105758. this.onMeshLoadedObservable = new BABYLON.Observable();
  105759. this.onTextureLoadedObservable = new BABYLON.Observable();
  105760. this.onMaterialLoadedObservable = new BABYLON.Observable();
  105761. this.onExtensionLoadedObservable = new BABYLON.Observable();
  105762. this.onCompleteObservable = new BABYLON.Observable();
  105763. }
  105764. GLTFLoader._Register = function (name, factory) {
  105765. if (GLTFLoader._Factories[name]) {
  105766. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  105767. return;
  105768. }
  105769. GLTFLoader._Factories[name] = factory;
  105770. // Keep the order of registration so that extensions registered first are called first.
  105771. GLTFLoader._Names.push(name);
  105772. };
  105773. Object.defineProperty(GLTFLoader.prototype, "state", {
  105774. get: function () {
  105775. return this._state;
  105776. },
  105777. enumerable: true,
  105778. configurable: true
  105779. });
  105780. GLTFLoader.prototype.dispose = function () {
  105781. if (this._disposed) {
  105782. return;
  105783. }
  105784. this._disposed = true;
  105785. this.onDisposeObservable.notifyObservers(this);
  105786. this.onDisposeObservable.clear();
  105787. this._clear();
  105788. };
  105789. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105790. var _this = this;
  105791. return Promise.resolve().then(function () {
  105792. var nodes = null;
  105793. if (meshesNames) {
  105794. var nodeMap_1 = {};
  105795. if (_this._gltf.nodes) {
  105796. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  105797. var node = _a[_i];
  105798. if (node.name) {
  105799. nodeMap_1[node.name] = node;
  105800. }
  105801. }
  105802. }
  105803. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  105804. nodes = names.map(function (name) {
  105805. var node = nodeMap_1[name];
  105806. if (!node) {
  105807. throw new Error("Failed to find node " + name);
  105808. }
  105809. return node;
  105810. });
  105811. }
  105812. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  105813. return {
  105814. meshes: _this._getMeshes(),
  105815. particleSystems: [],
  105816. skeletons: _this._getSkeletons(),
  105817. };
  105818. });
  105819. });
  105820. };
  105821. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105822. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  105823. };
  105824. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  105825. var _this = this;
  105826. return Promise.resolve().then(function () {
  105827. _this._loadExtensions();
  105828. _this._babylonScene = scene;
  105829. _this._rootUrl = rootUrl;
  105830. _this._progressCallback = onProgress;
  105831. _this._state = BABYLON.GLTFLoaderState.Loading;
  105832. _this._loadData(data);
  105833. var promises = new Array();
  105834. if (nodes) {
  105835. promises.push(_this._loadNodesAsync(nodes));
  105836. }
  105837. else {
  105838. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  105839. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  105840. }
  105841. if (_this.compileMaterials) {
  105842. promises.push(_this._compileMaterialsAsync());
  105843. }
  105844. if (_this.compileShadowGenerators) {
  105845. promises.push(_this._compileShadowGeneratorsAsync());
  105846. }
  105847. return Promise.all(promises).then(function () {
  105848. _this._state = BABYLON.GLTFLoaderState.Ready;
  105849. _this._startAnimations();
  105850. BABYLON.Tools.SetImmediate(function () {
  105851. if (!_this._disposed) {
  105852. Promise.all(_this._completePromises).then(function () {
  105853. _this._state = BABYLON.GLTFLoaderState.Complete;
  105854. _this.onCompleteObservable.notifyObservers(_this);
  105855. _this.onCompleteObservable.clear();
  105856. _this._clear();
  105857. }).catch(function (error) {
  105858. BABYLON.Tools.Error("glTF Loader: " + error.message);
  105859. _this._clear();
  105860. });
  105861. }
  105862. });
  105863. });
  105864. }).catch(function (error) {
  105865. BABYLON.Tools.Error("glTF Loader: " + error.message);
  105866. _this._clear();
  105867. throw error;
  105868. });
  105869. };
  105870. GLTFLoader.prototype._loadExtensions = function () {
  105871. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  105872. var name_1 = _a[_i];
  105873. var extension = GLTFLoader._Factories[name_1](this);
  105874. this._extensions[name_1] = extension;
  105875. this.onExtensionLoadedObservable.notifyObservers(extension);
  105876. }
  105877. this.onExtensionLoadedObservable.clear();
  105878. };
  105879. GLTFLoader.prototype._loadData = function (data) {
  105880. this._gltf = data.json;
  105881. this._setupData();
  105882. if (data.bin) {
  105883. var buffers = this._gltf.buffers;
  105884. if (buffers && buffers[0] && !buffers[0].uri) {
  105885. var binaryBuffer = buffers[0];
  105886. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  105887. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  105888. }
  105889. binaryBuffer._data = Promise.resolve(data.bin);
  105890. }
  105891. else {
  105892. BABYLON.Tools.Warn("Unexpected BIN chunk");
  105893. }
  105894. }
  105895. };
  105896. GLTFLoader.prototype._setupData = function () {
  105897. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  105898. GLTF2.ArrayItem.Assign(this._gltf.animations);
  105899. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  105900. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  105901. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  105902. GLTF2.ArrayItem.Assign(this._gltf.images);
  105903. GLTF2.ArrayItem.Assign(this._gltf.materials);
  105904. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  105905. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  105906. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  105907. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  105908. GLTF2.ArrayItem.Assign(this._gltf.skins);
  105909. GLTF2.ArrayItem.Assign(this._gltf.textures);
  105910. if (this._gltf.nodes) {
  105911. var nodeParents = {};
  105912. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  105913. var node = _a[_i];
  105914. if (node.children) {
  105915. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  105916. var index = _c[_b];
  105917. nodeParents[index] = node._index;
  105918. }
  105919. }
  105920. }
  105921. var rootNode = this._createRootNode();
  105922. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  105923. var node = _e[_d];
  105924. var parentIndex = nodeParents[node._index];
  105925. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  105926. }
  105927. }
  105928. };
  105929. GLTFLoader.prototype._createRootNode = function () {
  105930. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  105931. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  105932. switch (this.coordinateSystemMode) {
  105933. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  105934. if (!this._babylonScene.useRightHandedSystem) {
  105935. rootNode.rotation = [0, 1, 0, 0];
  105936. rootNode.scale = [1, 1, -1];
  105937. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  105938. }
  105939. break;
  105940. }
  105941. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  105942. this._babylonScene.useRightHandedSystem = true;
  105943. break;
  105944. }
  105945. default: {
  105946. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  105947. }
  105948. }
  105949. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  105950. return rootNode;
  105951. };
  105952. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  105953. var promises = new Array();
  105954. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  105955. var node = nodes_1[_i];
  105956. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  105957. }
  105958. promises.push(this._loadAnimationsAsync());
  105959. return Promise.all(promises).then(function () { });
  105960. };
  105961. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  105962. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  105963. if (promise) {
  105964. return promise;
  105965. }
  105966. var promises = new Array();
  105967. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  105968. var index = _a[_i];
  105969. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  105970. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  105971. }
  105972. promises.push(this._loadAnimationsAsync());
  105973. return Promise.all(promises).then(function () { });
  105974. };
  105975. GLTFLoader.prototype._getMeshes = function () {
  105976. var meshes = new Array();
  105977. // Root mesh is always first.
  105978. meshes.push(this._rootBabylonMesh);
  105979. var nodes = this._gltf.nodes;
  105980. if (nodes) {
  105981. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  105982. var node = nodes_2[_i];
  105983. if (node._babylonMesh) {
  105984. meshes.push(node._babylonMesh);
  105985. }
  105986. if (node._primitiveBabylonMeshes) {
  105987. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  105988. var babylonMesh = _b[_a];
  105989. meshes.push(babylonMesh);
  105990. }
  105991. }
  105992. }
  105993. }
  105994. return meshes;
  105995. };
  105996. GLTFLoader.prototype._getSkeletons = function () {
  105997. var skeletons = new Array();
  105998. var skins = this._gltf.skins;
  105999. if (skins) {
  106000. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  106001. var skin = skins_1[_i];
  106002. if (skin._babylonSkeleton) {
  106003. skeletons.push(skin._babylonSkeleton);
  106004. }
  106005. }
  106006. }
  106007. return skeletons;
  106008. };
  106009. GLTFLoader.prototype._startAnimations = function () {
  106010. var animations = this._gltf.animations;
  106011. if (!animations) {
  106012. return;
  106013. }
  106014. switch (this.animationStartMode) {
  106015. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  106016. // do nothing
  106017. break;
  106018. }
  106019. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  106020. var animation = animations[0];
  106021. animation._babylonAnimationGroup.start(true);
  106022. break;
  106023. }
  106024. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  106025. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  106026. var animation = animations_1[_i];
  106027. animation._babylonAnimationGroup.start(true);
  106028. }
  106029. break;
  106030. }
  106031. default: {
  106032. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  106033. return;
  106034. }
  106035. }
  106036. };
  106037. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  106038. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  106039. if (promise) {
  106040. return promise;
  106041. }
  106042. if (node._babylonMesh) {
  106043. throw new Error(context + ": Invalid recursive node hierarchy");
  106044. }
  106045. var promises = new Array();
  106046. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  106047. node._babylonMesh = babylonMesh;
  106048. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  106049. node._babylonAnimationTargets.push(babylonMesh);
  106050. GLTFLoader._LoadTransform(node, babylonMesh);
  106051. if (node.mesh != undefined) {
  106052. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  106053. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  106054. }
  106055. if (node.children) {
  106056. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  106057. var index = _a[_i];
  106058. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  106059. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  106060. }
  106061. }
  106062. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  106063. return Promise.all(promises).then(function () { });
  106064. };
  106065. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  106066. // TODO: instancing
  106067. var promises = new Array();
  106068. var primitives = mesh.primitives;
  106069. if (!primitives || primitives.length === 0) {
  106070. throw new Error(context + ": Primitives are missing");
  106071. }
  106072. GLTF2.ArrayItem.Assign(primitives);
  106073. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  106074. var primitive = primitives_1[_i];
  106075. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  106076. }
  106077. if (node.skin != undefined) {
  106078. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  106079. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  106080. }
  106081. return Promise.all(promises).then(function () {
  106082. if (node._primitiveBabylonMeshes) {
  106083. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  106084. var primitiveBabylonMesh = _a[_i];
  106085. primitiveBabylonMesh._refreshBoundingInfo(true);
  106086. }
  106087. }
  106088. });
  106089. };
  106090. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  106091. var _this = this;
  106092. var promises = new Array();
  106093. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  106094. babylonMesh.setEnabled(false);
  106095. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  106096. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  106097. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  106098. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  106099. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  106100. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  106101. }));
  106102. if (primitive.material == undefined) {
  106103. babylonMesh.material = this._getDefaultMaterial();
  106104. }
  106105. else {
  106106. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  106107. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  106108. }
  106109. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  106110. return Promise.all(promises).then(function () {
  106111. babylonMesh.setEnabled(true);
  106112. });
  106113. };
  106114. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  106115. var _this = this;
  106116. var attributes = primitive.attributes;
  106117. if (!attributes) {
  106118. throw new Error(context + ": Attributes are missing");
  106119. }
  106120. if (primitive.mode && primitive.mode !== 4 /* TRIANGLES */) {
  106121. // TODO: handle other primitive modes
  106122. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  106123. }
  106124. var promises = new Array();
  106125. var babylonVertexData = new BABYLON.VertexData();
  106126. if (primitive.indices == undefined) {
  106127. var positionAccessorIndex = attributes["POSITION"];
  106128. if (positionAccessorIndex != undefined) {
  106129. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  106130. babylonVertexData.indices = new Uint32Array(accessor.count);
  106131. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  106132. babylonVertexData.indices[i] = i;
  106133. }
  106134. }
  106135. }
  106136. else {
  106137. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  106138. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  106139. babylonVertexData.indices = data;
  106140. }));
  106141. }
  106142. var loadAttribute = function (attribute, kind) {
  106143. if (attributes[attribute] == undefined) {
  106144. return;
  106145. }
  106146. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  106147. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  106148. babylonMesh._delayInfo.push(kind);
  106149. }
  106150. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  106151. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  106152. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  106153. if (attribute === "COLOR_0") {
  106154. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  106155. babylonMesh.hasVertexAlpha = true;
  106156. if (accessor.type === "VEC3") {
  106157. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  106158. }
  106159. }
  106160. babylonVertexData.set(attributeData, kind);
  106161. }));
  106162. };
  106163. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  106164. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  106165. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  106166. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  106167. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  106168. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  106169. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  106170. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  106171. return Promise.all(promises).then(function () {
  106172. return babylonVertexData;
  106173. });
  106174. };
  106175. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  106176. if (!primitive.targets) {
  106177. return;
  106178. }
  106179. if (node._numMorphTargets == undefined) {
  106180. node._numMorphTargets = primitive.targets.length;
  106181. }
  106182. else if (primitive.targets.length !== node._numMorphTargets) {
  106183. throw new Error(context + ": Primitives do not have the same number of targets");
  106184. }
  106185. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  106186. for (var index = 0; index < primitive.targets.length; index++) {
  106187. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  106188. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  106189. // TODO: tell the target whether it has positions, normals, tangents
  106190. }
  106191. };
  106192. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  106193. if (!primitive.targets) {
  106194. return Promise.resolve();
  106195. }
  106196. var promises = new Array();
  106197. var morphTargetManager = babylonMesh.morphTargetManager;
  106198. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  106199. var babylonMorphTarget = morphTargetManager.getTarget(index);
  106200. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  106201. }
  106202. return Promise.all(promises).then(function () { });
  106203. };
  106204. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  106205. var _this = this;
  106206. var promises = new Array();
  106207. var loadAttribute = function (attribute, setData) {
  106208. if (attributes[attribute] == undefined) {
  106209. return;
  106210. }
  106211. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  106212. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  106213. setData(data);
  106214. }));
  106215. };
  106216. loadAttribute("POSITION", function (data) {
  106217. if (babylonVertexData.positions) {
  106218. for (var i = 0; i < data.length; i++) {
  106219. data[i] += babylonVertexData.positions[i];
  106220. }
  106221. babylonMorphTarget.setPositions(data);
  106222. }
  106223. });
  106224. loadAttribute("NORMAL", function (data) {
  106225. if (babylonVertexData.normals) {
  106226. for (var i = 0; i < data.length; i++) {
  106227. data[i] += babylonVertexData.normals[i];
  106228. }
  106229. babylonMorphTarget.setNormals(data);
  106230. }
  106231. });
  106232. loadAttribute("TANGENT", function (data) {
  106233. if (babylonVertexData.tangents) {
  106234. // Tangent data for morph targets is stored as xyz delta.
  106235. // The vertexData.tangent is stored as xyzw.
  106236. // So we need to skip every fourth vertexData.tangent.
  106237. for (var i = 0, j = 0; i < data.length; i++) {
  106238. data[i] += babylonVertexData.tangents[j++];
  106239. if ((i + 1) % 3 == 0) {
  106240. j++;
  106241. }
  106242. }
  106243. babylonMorphTarget.setTangents(data);
  106244. }
  106245. });
  106246. return Promise.all(promises).then(function () { });
  106247. };
  106248. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  106249. if (accessor.componentType == 5126 /* FLOAT */) {
  106250. return data;
  106251. }
  106252. var factor = 1;
  106253. if (accessor.normalized) {
  106254. switch (accessor.componentType) {
  106255. case 5121 /* UNSIGNED_BYTE */: {
  106256. factor = 1 / 255;
  106257. break;
  106258. }
  106259. case 5123 /* UNSIGNED_SHORT */: {
  106260. factor = 1 / 65535;
  106261. break;
  106262. }
  106263. default: {
  106264. throw new Error(context + ": Invalid component type " + accessor.componentType);
  106265. }
  106266. }
  106267. }
  106268. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  106269. for (var i = 0; i < result.length; i++) {
  106270. result[i] = data[i] * factor;
  106271. }
  106272. return result;
  106273. };
  106274. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  106275. var result = new Float32Array(data.length / 3 * 4);
  106276. var offset = 0;
  106277. for (var i = 0; i < result.length; i++) {
  106278. if ((i + 1) % 4 === 0) {
  106279. result[i] = 1;
  106280. }
  106281. else {
  106282. result[i] = data[offset++];
  106283. }
  106284. }
  106285. return result;
  106286. };
  106287. GLTFLoader._LoadTransform = function (node, babylonNode) {
  106288. var position = BABYLON.Vector3.Zero();
  106289. var rotation = BABYLON.Quaternion.Identity();
  106290. var scaling = BABYLON.Vector3.One();
  106291. if (node.matrix) {
  106292. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  106293. matrix.decompose(scaling, rotation, position);
  106294. }
  106295. else {
  106296. if (node.translation)
  106297. position = BABYLON.Vector3.FromArray(node.translation);
  106298. if (node.rotation)
  106299. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  106300. if (node.scale)
  106301. scaling = BABYLON.Vector3.FromArray(node.scale);
  106302. }
  106303. babylonNode.position = position;
  106304. babylonNode.rotationQuaternion = rotation;
  106305. babylonNode.scaling = scaling;
  106306. };
  106307. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  106308. var _this = this;
  106309. var assignSkeleton = function () {
  106310. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  106311. var babylonMesh = _a[_i];
  106312. babylonMesh.skeleton = skin._babylonSkeleton;
  106313. }
  106314. node._babylonMesh.parent = _this._rootBabylonMesh;
  106315. node._babylonMesh.position = BABYLON.Vector3.Zero();
  106316. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  106317. node._babylonMesh.scaling = BABYLON.Vector3.One();
  106318. };
  106319. if (skin._loaded) {
  106320. assignSkeleton();
  106321. return skin._loaded;
  106322. }
  106323. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  106324. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  106325. var skeletonId = "skeleton" + skin._index;
  106326. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  106327. skin._babylonSkeleton = babylonSkeleton;
  106328. _this._loadBones(context, skin, inverseBindMatricesData);
  106329. assignSkeleton();
  106330. }));
  106331. };
  106332. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  106333. if (skin.inverseBindMatrices == undefined) {
  106334. return Promise.resolve(null);
  106335. }
  106336. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  106337. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  106338. return data;
  106339. });
  106340. };
  106341. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  106342. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  106343. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  106344. node._babylonAnimationTargets.push(babylonBone);
  106345. return babylonBone;
  106346. };
  106347. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  106348. var babylonBones = {};
  106349. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  106350. var index = _a[_i];
  106351. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  106352. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  106353. }
  106354. };
  106355. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  106356. var babylonBone = babylonBones[node._index];
  106357. if (babylonBone) {
  106358. return babylonBone;
  106359. }
  106360. var boneIndex = skin.joints.indexOf(node._index);
  106361. var baseMatrix = BABYLON.Matrix.Identity();
  106362. if (inverseBindMatricesData && boneIndex !== -1) {
  106363. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  106364. baseMatrix.invertToRef(baseMatrix);
  106365. }
  106366. var babylonParentBone = null;
  106367. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  106368. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  106369. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  106370. }
  106371. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  106372. babylonBones[node._index] = babylonBone;
  106373. return babylonBone;
  106374. };
  106375. GLTFLoader.prototype._getNodeMatrix = function (node) {
  106376. return node.matrix ?
  106377. BABYLON.Matrix.FromArray(node.matrix) :
  106378. 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());
  106379. };
  106380. GLTFLoader.prototype._loadAnimationsAsync = function () {
  106381. var animations = this._gltf.animations;
  106382. if (!animations) {
  106383. return Promise.resolve();
  106384. }
  106385. var promises = new Array();
  106386. for (var index = 0; index < animations.length; index++) {
  106387. var animation = animations[index];
  106388. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  106389. }
  106390. return Promise.all(promises).then(function () { });
  106391. };
  106392. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  106393. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  106394. animation._babylonAnimationGroup = babylonAnimationGroup;
  106395. var promises = new Array();
  106396. GLTF2.ArrayItem.Assign(animation.channels);
  106397. GLTF2.ArrayItem.Assign(animation.samplers);
  106398. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  106399. var channel = _a[_i];
  106400. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  106401. }
  106402. return Promise.all(promises).then(function () {
  106403. babylonAnimationGroup.normalize();
  106404. });
  106405. };
  106406. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  106407. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  106408. if (!targetNode._babylonMesh) {
  106409. return Promise.resolve();
  106410. }
  106411. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  106412. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  106413. var targetPath;
  106414. var animationType;
  106415. switch (channel.target.path) {
  106416. case "translation" /* TRANSLATION */: {
  106417. targetPath = "position";
  106418. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106419. break;
  106420. }
  106421. case "rotation" /* ROTATION */: {
  106422. targetPath = "rotationQuaternion";
  106423. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  106424. break;
  106425. }
  106426. case "scale" /* SCALE */: {
  106427. targetPath = "scaling";
  106428. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  106429. break;
  106430. }
  106431. case "weights" /* WEIGHTS */: {
  106432. targetPath = "influence";
  106433. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  106434. break;
  106435. }
  106436. default: {
  106437. throw new Error(context + ": Invalid target path " + channel.target.path);
  106438. }
  106439. }
  106440. var outputBufferOffset = 0;
  106441. var getNextOutputValue;
  106442. switch (targetPath) {
  106443. case "position": {
  106444. getNextOutputValue = function () {
  106445. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  106446. outputBufferOffset += 3;
  106447. return value;
  106448. };
  106449. break;
  106450. }
  106451. case "rotationQuaternion": {
  106452. getNextOutputValue = function () {
  106453. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  106454. outputBufferOffset += 4;
  106455. return value;
  106456. };
  106457. break;
  106458. }
  106459. case "scaling": {
  106460. getNextOutputValue = function () {
  106461. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  106462. outputBufferOffset += 3;
  106463. return value;
  106464. };
  106465. break;
  106466. }
  106467. case "influence": {
  106468. getNextOutputValue = function () {
  106469. var value = new Array(targetNode._numMorphTargets);
  106470. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  106471. value[i] = data.output[outputBufferOffset++];
  106472. }
  106473. return value;
  106474. };
  106475. break;
  106476. }
  106477. }
  106478. var getNextKey;
  106479. switch (data.interpolation) {
  106480. case "STEP" /* STEP */: {
  106481. getNextKey = function (frameIndex) { return ({
  106482. frame: data.input[frameIndex],
  106483. value: getNextOutputValue(),
  106484. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  106485. }); };
  106486. break;
  106487. }
  106488. case "LINEAR" /* LINEAR */: {
  106489. getNextKey = function (frameIndex) { return ({
  106490. frame: data.input[frameIndex],
  106491. value: getNextOutputValue()
  106492. }); };
  106493. break;
  106494. }
  106495. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106496. getNextKey = function (frameIndex) { return ({
  106497. frame: data.input[frameIndex],
  106498. inTangent: getNextOutputValue(),
  106499. value: getNextOutputValue(),
  106500. outTangent: getNextOutputValue()
  106501. }); };
  106502. break;
  106503. }
  106504. }
  106505. var keys;
  106506. if (data.input.length === 1) {
  106507. var key = getNextKey(0);
  106508. keys = [
  106509. { frame: key.frame, value: key.value },
  106510. { frame: key.frame + 1, value: key.value }
  106511. ];
  106512. }
  106513. else {
  106514. keys = new Array(data.input.length);
  106515. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  106516. keys[frameIndex] = getNextKey(frameIndex);
  106517. }
  106518. }
  106519. if (targetPath === "influence") {
  106520. var _loop_1 = function (targetIndex) {
  106521. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106522. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106523. babylonAnimation.setKeys(keys.map(function (key) { return ({
  106524. frame: key.frame,
  106525. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  106526. value: key.value[targetIndex],
  106527. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  106528. }); }));
  106529. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  106530. var babylonMesh = _a[_i];
  106531. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  106532. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  106533. }
  106534. };
  106535. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  106536. _loop_1(targetIndex);
  106537. }
  106538. }
  106539. else {
  106540. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  106541. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  106542. babylonAnimation.setKeys(keys);
  106543. if (targetNode._babylonAnimationTargets) {
  106544. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  106545. var target = _a[_i];
  106546. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  106547. }
  106548. }
  106549. }
  106550. });
  106551. };
  106552. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  106553. if (sampler._data) {
  106554. return sampler._data;
  106555. }
  106556. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  106557. switch (interpolation) {
  106558. case "STEP" /* STEP */:
  106559. case "LINEAR" /* LINEAR */:
  106560. case "CUBICSPLINE" /* CUBICSPLINE */: {
  106561. break;
  106562. }
  106563. default: {
  106564. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  106565. }
  106566. }
  106567. var inputData;
  106568. var outputData;
  106569. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  106570. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  106571. sampler._data = Promise.all([
  106572. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  106573. inputData = data;
  106574. }),
  106575. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  106576. outputData = data;
  106577. })
  106578. ]).then(function () {
  106579. return {
  106580. input: inputData,
  106581. interpolation: interpolation,
  106582. output: outputData,
  106583. };
  106584. });
  106585. return sampler._data;
  106586. };
  106587. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  106588. if (buffer._data) {
  106589. return buffer._data;
  106590. }
  106591. if (!buffer.uri) {
  106592. throw new Error(context + ": Uri is missing");
  106593. }
  106594. buffer._data = this._loadUriAsync(context, buffer.uri);
  106595. return buffer._data;
  106596. };
  106597. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  106598. if (bufferView._data) {
  106599. return bufferView._data;
  106600. }
  106601. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  106602. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  106603. try {
  106604. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  106605. }
  106606. catch (e) {
  106607. throw new Error(context + ": " + e.message);
  106608. }
  106609. });
  106610. return bufferView._data;
  106611. };
  106612. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  106613. var _this = this;
  106614. if (accessor.sparse) {
  106615. throw new Error(context + ": Sparse accessors are not currently supported");
  106616. }
  106617. if (accessor._data) {
  106618. return accessor._data;
  106619. }
  106620. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  106621. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  106622. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  106623. var byteOffset = accessor.byteOffset || 0;
  106624. var byteStride = bufferView.byteStride;
  106625. if (byteStride === 0) {
  106626. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  106627. }
  106628. try {
  106629. switch (accessor.componentType) {
  106630. case 5120 /* BYTE */: {
  106631. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  106632. }
  106633. case 5121 /* UNSIGNED_BYTE */: {
  106634. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  106635. }
  106636. case 5122 /* SHORT */: {
  106637. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  106638. }
  106639. case 5123 /* UNSIGNED_SHORT */: {
  106640. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  106641. }
  106642. case 5125 /* UNSIGNED_INT */: {
  106643. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  106644. }
  106645. case 5126 /* FLOAT */: {
  106646. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  106647. }
  106648. default: {
  106649. throw new Error(context + ": Invalid component type " + accessor.componentType);
  106650. }
  106651. }
  106652. }
  106653. catch (e) {
  106654. throw new Error(context + ": " + e);
  106655. }
  106656. });
  106657. return accessor._data;
  106658. };
  106659. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  106660. byteOffset += data.byteOffset;
  106661. var targetLength = count * numComponents;
  106662. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  106663. return new typedArray(data.buffer, byteOffset, targetLength);
  106664. }
  106665. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  106666. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  106667. var targetBuffer = new typedArray(targetLength);
  106668. var sourceIndex = 0;
  106669. var targetIndex = 0;
  106670. while (targetIndex < targetLength) {
  106671. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  106672. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  106673. targetIndex++;
  106674. }
  106675. sourceIndex += elementStride;
  106676. }
  106677. return targetBuffer;
  106678. };
  106679. GLTFLoader.prototype._getDefaultMaterial = function () {
  106680. var id = "__gltf_default";
  106681. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  106682. if (!babylonMaterial) {
  106683. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  106684. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  106685. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  106686. babylonMaterial.metallic = 1;
  106687. babylonMaterial.roughness = 1;
  106688. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106689. }
  106690. return babylonMaterial;
  106691. };
  106692. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  106693. var promises = new Array();
  106694. var babylonMaterial = material._babylonMaterial;
  106695. // Ensure metallic workflow
  106696. babylonMaterial.metallic = 1;
  106697. babylonMaterial.roughness = 1;
  106698. var properties = material.pbrMetallicRoughness;
  106699. if (properties) {
  106700. if (properties.baseColorFactor) {
  106701. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106702. babylonMaterial.alpha = properties.baseColorFactor[3];
  106703. }
  106704. else {
  106705. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106706. }
  106707. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  106708. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  106709. if (properties.baseColorTexture) {
  106710. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106711. babylonMaterial.albedoTexture = texture;
  106712. }));
  106713. }
  106714. if (properties.metallicRoughnessTexture) {
  106715. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  106716. babylonMaterial.metallicTexture = texture;
  106717. }));
  106718. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  106719. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  106720. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  106721. }
  106722. }
  106723. this._loadMaterialAlphaProperties(context, material);
  106724. return Promise.all(promises).then(function () { });
  106725. };
  106726. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  106727. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  106728. if (promise) {
  106729. return promise;
  106730. }
  106731. material._babylonMeshes = material._babylonMeshes || [];
  106732. material._babylonMeshes.push(babylonMesh);
  106733. if (material._loaded) {
  106734. babylonMesh.material = material._babylonMaterial;
  106735. return material._loaded;
  106736. }
  106737. var promises = new Array();
  106738. var babylonMaterial = this._createMaterial(material);
  106739. material._babylonMaterial = babylonMaterial;
  106740. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  106741. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  106742. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106743. babylonMesh.material = babylonMaterial;
  106744. return (material._loaded = Promise.all(promises).then(function () { }));
  106745. };
  106746. GLTFLoader.prototype._createMaterial = function (material) {
  106747. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  106748. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  106749. return babylonMaterial;
  106750. };
  106751. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  106752. var promises = new Array();
  106753. var babylonMaterial = material._babylonMaterial;
  106754. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  106755. if (material.doubleSided) {
  106756. babylonMaterial.backFaceCulling = false;
  106757. babylonMaterial.twoSidedLighting = true;
  106758. }
  106759. if (material.normalTexture) {
  106760. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  106761. babylonMaterial.bumpTexture = texture;
  106762. }));
  106763. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  106764. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  106765. if (material.normalTexture.scale != undefined) {
  106766. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  106767. }
  106768. }
  106769. if (material.occlusionTexture) {
  106770. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  106771. babylonMaterial.ambientTexture = texture;
  106772. }));
  106773. babylonMaterial.useAmbientInGrayScale = true;
  106774. if (material.occlusionTexture.strength != undefined) {
  106775. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  106776. }
  106777. }
  106778. if (material.emissiveTexture) {
  106779. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  106780. babylonMaterial.emissiveTexture = texture;
  106781. }));
  106782. }
  106783. return Promise.all(promises).then(function () { });
  106784. };
  106785. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  106786. var babylonMaterial = material._babylonMaterial;
  106787. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  106788. switch (alphaMode) {
  106789. case "OPAQUE" /* OPAQUE */: {
  106790. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  106791. break;
  106792. }
  106793. case "MASK" /* MASK */: {
  106794. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  106795. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  106796. if (babylonMaterial.alpha) {
  106797. if (babylonMaterial.alpha === 0) {
  106798. babylonMaterial.alphaCutOff = 1;
  106799. }
  106800. else {
  106801. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  106802. }
  106803. babylonMaterial.alpha = 1;
  106804. }
  106805. if (babylonMaterial.albedoTexture) {
  106806. babylonMaterial.albedoTexture.hasAlpha = true;
  106807. }
  106808. break;
  106809. }
  106810. case "BLEND" /* BLEND */: {
  106811. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  106812. if (babylonMaterial.albedoTexture) {
  106813. babylonMaterial.albedoTexture.hasAlpha = true;
  106814. babylonMaterial.useAlphaFromAlbedoTexture = true;
  106815. }
  106816. break;
  106817. }
  106818. default: {
  106819. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  106820. }
  106821. }
  106822. };
  106823. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  106824. var _this = this;
  106825. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  106826. context = "#/textures/" + textureInfo.index;
  106827. var promises = new Array();
  106828. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  106829. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  106830. var deferred = new BABYLON.Deferred();
  106831. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  106832. if (!_this._disposed) {
  106833. deferred.resolve();
  106834. }
  106835. }, function (message, exception) {
  106836. if (!_this._disposed) {
  106837. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  106838. }
  106839. });
  106840. promises.push(deferred.promise);
  106841. babylonTexture.name = texture.name || "texture" + texture._index;
  106842. babylonTexture.wrapU = samplerData.wrapU;
  106843. babylonTexture.wrapV = samplerData.wrapV;
  106844. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  106845. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  106846. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  106847. babylonTexture.updateURL(objectURL);
  106848. }));
  106849. assign(babylonTexture);
  106850. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  106851. return Promise.all(promises).then(function () { });
  106852. };
  106853. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  106854. if (!sampler._data) {
  106855. sampler._data = {
  106856. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  106857. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  106858. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  106859. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  106860. };
  106861. }
  106862. ;
  106863. return sampler._data;
  106864. };
  106865. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  106866. if (image._objectURL) {
  106867. return image._objectURL;
  106868. }
  106869. var promise;
  106870. if (image.uri) {
  106871. promise = this._loadUriAsync(context, image.uri);
  106872. }
  106873. else {
  106874. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  106875. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  106876. }
  106877. image._objectURL = promise.then(function (data) {
  106878. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  106879. });
  106880. return image._objectURL;
  106881. };
  106882. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  106883. var _this = this;
  106884. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  106885. if (promise) {
  106886. return promise;
  106887. }
  106888. if (!GLTFLoader._ValidateUri(uri)) {
  106889. throw new Error(context + ": Uri '" + uri + "' is invalid");
  106890. }
  106891. if (BABYLON.Tools.IsBase64(uri)) {
  106892. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  106893. }
  106894. return new Promise(function (resolve, reject) {
  106895. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  106896. if (!_this._disposed) {
  106897. resolve(new Uint8Array(data));
  106898. }
  106899. }, function (event) {
  106900. if (!_this._disposed) {
  106901. try {
  106902. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  106903. request._lengthComputable = event.lengthComputable;
  106904. request._loaded = event.loaded;
  106905. request._total = event.total;
  106906. _this._onProgress();
  106907. }
  106908. }
  106909. catch (e) {
  106910. reject(e);
  106911. }
  106912. }
  106913. }, _this._babylonScene.database, true, function (request, exception) {
  106914. if (!_this._disposed) {
  106915. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  106916. }
  106917. });
  106918. _this._requests.push(request);
  106919. });
  106920. };
  106921. GLTFLoader.prototype._onProgress = function () {
  106922. if (!this._progressCallback) {
  106923. return;
  106924. }
  106925. var lengthComputable = true;
  106926. var loaded = 0;
  106927. var total = 0;
  106928. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  106929. var request = _a[_i];
  106930. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  106931. return;
  106932. }
  106933. lengthComputable = lengthComputable && request._lengthComputable;
  106934. loaded += request._loaded;
  106935. total += request._total;
  106936. }
  106937. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  106938. };
  106939. GLTFLoader._GetProperty = function (context, array, index) {
  106940. if (!array || index == undefined || !array[index]) {
  106941. throw new Error(context + ": Failed to find index " + index);
  106942. }
  106943. return array[index];
  106944. };
  106945. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  106946. // Set defaults if undefined
  106947. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  106948. switch (mode) {
  106949. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  106950. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  106951. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  106952. default:
  106953. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  106954. return BABYLON.Texture.WRAP_ADDRESSMODE;
  106955. }
  106956. };
  106957. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  106958. // Set defaults if undefined
  106959. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  106960. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  106961. if (magFilter === 9729 /* LINEAR */) {
  106962. switch (minFilter) {
  106963. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  106964. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  106965. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  106966. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  106967. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  106968. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106969. default:
  106970. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  106971. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  106972. }
  106973. }
  106974. else {
  106975. if (magFilter !== 9728 /* NEAREST */) {
  106976. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  106977. }
  106978. switch (minFilter) {
  106979. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  106980. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  106981. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106982. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  106983. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  106984. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  106985. default:
  106986. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  106987. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  106988. }
  106989. }
  106990. };
  106991. GLTFLoader._GetNumComponents = function (context, type) {
  106992. switch (type) {
  106993. case "SCALAR": return 1;
  106994. case "VEC2": return 2;
  106995. case "VEC3": return 3;
  106996. case "VEC4": return 4;
  106997. case "MAT2": return 4;
  106998. case "MAT3": return 9;
  106999. case "MAT4": return 16;
  107000. }
  107001. throw new Error(context + ": Invalid type " + type);
  107002. };
  107003. GLTFLoader._ValidateUri = function (uri) {
  107004. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  107005. };
  107006. GLTFLoader.prototype._compileMaterialsAsync = function () {
  107007. var promises = new Array();
  107008. if (this._gltf.materials) {
  107009. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  107010. var material = _a[_i];
  107011. var babylonMaterial = material._babylonMaterial;
  107012. var babylonMeshes = material._babylonMeshes;
  107013. if (babylonMaterial && babylonMeshes) {
  107014. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  107015. var babylonMesh = babylonMeshes_1[_b];
  107016. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  107017. if (this.useClipPlane) {
  107018. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  107019. }
  107020. }
  107021. }
  107022. }
  107023. }
  107024. return Promise.all(promises).then(function () { });
  107025. };
  107026. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  107027. var promises = new Array();
  107028. var lights = this._babylonScene.lights;
  107029. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  107030. var light = lights_1[_i];
  107031. var generator = light.getShadowGenerator();
  107032. if (generator) {
  107033. promises.push(generator.forceCompilationAsync());
  107034. }
  107035. }
  107036. return Promise.all(promises).then(function () { });
  107037. };
  107038. GLTFLoader.prototype._clear = function () {
  107039. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  107040. var request = _a[_i];
  107041. request.abort();
  107042. }
  107043. this._requests.length = 0;
  107044. if (this._gltf && this._gltf.images) {
  107045. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  107046. var image = _c[_b];
  107047. if (image._objectURL) {
  107048. image._objectURL.then(function (value) {
  107049. URL.revokeObjectURL(value);
  107050. });
  107051. image._objectURL = undefined;
  107052. }
  107053. }
  107054. }
  107055. delete this._gltf;
  107056. delete this._babylonScene;
  107057. this._completePromises.length = 0;
  107058. this._extensions = {};
  107059. delete this._rootBabylonMesh;
  107060. delete this._progressCallback;
  107061. this.onMeshLoadedObservable.clear();
  107062. this.onTextureLoadedObservable.clear();
  107063. this.onMaterialLoadedObservable.clear();
  107064. };
  107065. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  107066. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  107067. var name_2 = _a[_i];
  107068. var extension = this._extensions[name_2];
  107069. if (extension.enabled) {
  107070. var promise = actionAsync(extension);
  107071. if (promise) {
  107072. return promise;
  107073. }
  107074. }
  107075. }
  107076. return null;
  107077. };
  107078. GLTFLoader._Names = new Array();
  107079. GLTFLoader._Factories = {};
  107080. return GLTFLoader;
  107081. }());
  107082. GLTF2.GLTFLoader = GLTFLoader;
  107083. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  107084. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107085. })(BABYLON || (BABYLON = {}));
  107086. //# sourceMappingURL=babylon.glTFLoader.js.map
  107087. var BABYLON;
  107088. (function (BABYLON) {
  107089. var GLTF2;
  107090. (function (GLTF2) {
  107091. var GLTFLoaderExtension = /** @class */ (function () {
  107092. function GLTFLoaderExtension(loader) {
  107093. this.enabled = true;
  107094. this._loader = loader;
  107095. }
  107096. // #region Overridable Methods
  107097. /** Override this method to modify the default behavior for loading scenes. */
  107098. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  107099. /** Override this method to modify the default behavior for loading nodes. */
  107100. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  107101. /** Override this method to modify the default behavior for loading materials. */
  107102. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  107103. /** Override this method to modify the default behavior for loading uris. */
  107104. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  107105. // #endregion
  107106. /** Helper method called by a loader extension to load an glTF extension. */
  107107. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  107108. var _this = this;
  107109. if (!property.extensions) {
  107110. return null;
  107111. }
  107112. var extensions = property.extensions;
  107113. var extension = extensions[this.name];
  107114. if (!extension) {
  107115. return null;
  107116. }
  107117. // Clear out the extension before executing the action to avoid recursing into the same property.
  107118. delete extensions[this.name];
  107119. return actionAsync(context + "/extensions/" + this.name, extension).then(function () {
  107120. // Restore the extension after completing the action.
  107121. extensions[_this.name] = extension;
  107122. });
  107123. };
  107124. /** Helper method called by the loader to allow extensions to override loading scenes. */
  107125. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  107126. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  107127. };
  107128. /** Helper method called by the loader to allow extensions to override loading nodes. */
  107129. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  107130. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  107131. };
  107132. /** Helper method called by the loader to allow extensions to override loading materials. */
  107133. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  107134. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  107135. };
  107136. /** Helper method called by the loader to allow extensions to override loading uris. */
  107137. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  107138. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  107139. };
  107140. return GLTFLoaderExtension;
  107141. }());
  107142. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  107143. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107144. })(BABYLON || (BABYLON = {}));
  107145. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  107146. var BABYLON;
  107147. (function (BABYLON) {
  107148. var GLTF2;
  107149. (function (GLTF2) {
  107150. var Extensions;
  107151. (function (Extensions) {
  107152. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  107153. var NAME = "MSFT_lod";
  107154. var MSFT_lod = /** @class */ (function (_super) {
  107155. __extends(MSFT_lod, _super);
  107156. function MSFT_lod() {
  107157. var _this = _super !== null && _super.apply(this, arguments) || this;
  107158. _this.name = NAME;
  107159. /**
  107160. * Maximum number of LODs to load, starting from the lowest LOD.
  107161. */
  107162. _this.maxLODsToLoad = Number.MAX_VALUE;
  107163. _this._loadingNodeLOD = null;
  107164. _this._loadNodeSignals = {};
  107165. _this._loadingMaterialLOD = null;
  107166. _this._loadMaterialSignals = {};
  107167. return _this;
  107168. }
  107169. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  107170. var _this = this;
  107171. return this._loadExtensionAsync(context, node, function (context, extension) {
  107172. var firstPromise;
  107173. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  107174. var _loop_1 = function (indexLOD) {
  107175. var nodeLOD = nodeLODs[indexLOD];
  107176. if (indexLOD !== 0) {
  107177. _this._loadingNodeLOD = nodeLOD;
  107178. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  107179. }
  107180. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  107181. if (indexLOD !== 0) {
  107182. var previousNodeLOD = nodeLODs[indexLOD - 1];
  107183. previousNodeLOD._babylonMesh.setEnabled(false);
  107184. }
  107185. if (indexLOD !== nodeLODs.length - 1) {
  107186. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  107187. _this._loadNodeSignals[nodeIndex].resolve();
  107188. delete _this._loadNodeSignals[nodeIndex];
  107189. }
  107190. });
  107191. if (indexLOD === 0) {
  107192. firstPromise = promise;
  107193. }
  107194. else {
  107195. _this._loader._completePromises.push(promise);
  107196. _this._loadingNodeLOD = null;
  107197. }
  107198. };
  107199. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  107200. _loop_1(indexLOD);
  107201. }
  107202. return firstPromise;
  107203. });
  107204. };
  107205. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  107206. var _this = this;
  107207. // Don't load material LODs if already loading a node LOD.
  107208. if (this._loadingNodeLOD) {
  107209. return null;
  107210. }
  107211. return this._loadExtensionAsync(context, material, function (context, extension) {
  107212. var firstPromise;
  107213. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  107214. var _loop_2 = function (indexLOD) {
  107215. var materialLOD = materialLODs[indexLOD];
  107216. if (indexLOD !== 0) {
  107217. _this._loadingMaterialLOD = materialLOD;
  107218. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  107219. }
  107220. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  107221. if (indexLOD !== materialLODs.length - 1) {
  107222. var materialIndex = materialLODs[indexLOD + 1]._index;
  107223. _this._loadMaterialSignals[materialIndex].resolve();
  107224. delete _this._loadMaterialSignals[materialIndex];
  107225. }
  107226. });
  107227. if (indexLOD === 0) {
  107228. firstPromise = promise;
  107229. }
  107230. else {
  107231. _this._loader._completePromises.push(promise);
  107232. _this._loadingMaterialLOD = null;
  107233. }
  107234. };
  107235. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  107236. _loop_2(indexLOD);
  107237. }
  107238. return firstPromise;
  107239. });
  107240. };
  107241. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  107242. var _this = this;
  107243. // Defer the loading of uris if loading a material or node LOD.
  107244. if (this._loadingMaterialLOD) {
  107245. var index = this._loadingMaterialLOD._index;
  107246. return this._loadMaterialSignals[index].promise.then(function () {
  107247. return _this._loader._loadUriAsync(context, uri);
  107248. });
  107249. }
  107250. else if (this._loadingNodeLOD) {
  107251. var index = this._loadingNodeLOD._index;
  107252. return this._loadNodeSignals[index].promise.then(function () {
  107253. return _this._loader._loadUriAsync(context, uri);
  107254. });
  107255. }
  107256. return null;
  107257. };
  107258. /**
  107259. * Gets an array of LOD properties from lowest to highest.
  107260. */
  107261. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  107262. if (this.maxLODsToLoad <= 0) {
  107263. throw new Error("maxLODsToLoad must be greater than zero");
  107264. }
  107265. var properties = new Array();
  107266. for (var i = ids.length - 1; i >= 0; i--) {
  107267. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  107268. if (properties.length === this.maxLODsToLoad) {
  107269. return properties;
  107270. }
  107271. }
  107272. properties.push(property);
  107273. return properties;
  107274. };
  107275. return MSFT_lod;
  107276. }(GLTF2.GLTFLoaderExtension));
  107277. Extensions.MSFT_lod = MSFT_lod;
  107278. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  107279. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107280. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107281. })(BABYLON || (BABYLON = {}));
  107282. //# sourceMappingURL=MSFT_lod.js.map
  107283. var BABYLON;
  107284. (function (BABYLON) {
  107285. var GLTF2;
  107286. (function (GLTF2) {
  107287. var Extensions;
  107288. (function (Extensions) {
  107289. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  107290. var NAME = "KHR_materials_pbrSpecularGlossiness";
  107291. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  107292. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  107293. function KHR_materials_pbrSpecularGlossiness() {
  107294. var _this = _super !== null && _super.apply(this, arguments) || this;
  107295. _this.name = NAME;
  107296. return _this;
  107297. }
  107298. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  107299. var _this = this;
  107300. return this._loadExtensionAsync(context, material, function (context, extension) {
  107301. material._babylonMeshes = material._babylonMeshes || [];
  107302. material._babylonMeshes.push(babylonMesh);
  107303. if (material._loaded) {
  107304. babylonMesh.material = material._babylonMaterial;
  107305. return material._loaded;
  107306. }
  107307. var promises = new Array();
  107308. var babylonMaterial = _this._loader._createMaterial(material);
  107309. material._babylonMaterial = babylonMaterial;
  107310. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  107311. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  107312. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  107313. babylonMesh.material = babylonMaterial;
  107314. return (material._loaded = Promise.all(promises).then(function () { }));
  107315. });
  107316. };
  107317. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  107318. var promises = new Array();
  107319. var babylonMaterial = material._babylonMaterial;
  107320. if (properties.diffuseFactor) {
  107321. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  107322. babylonMaterial.alpha = properties.diffuseFactor[3];
  107323. }
  107324. else {
  107325. babylonMaterial.albedoColor = BABYLON.Color3.White();
  107326. }
  107327. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  107328. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  107329. if (properties.diffuseTexture) {
  107330. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  107331. babylonMaterial.albedoTexture = texture;
  107332. }));
  107333. }
  107334. if (properties.specularGlossinessTexture) {
  107335. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  107336. babylonMaterial.reflectivityTexture = texture;
  107337. }));
  107338. babylonMaterial.reflectivityTexture.hasAlpha = true;
  107339. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  107340. }
  107341. loader._loadMaterialAlphaProperties(context, material);
  107342. return Promise.all(promises).then(function () { });
  107343. };
  107344. return KHR_materials_pbrSpecularGlossiness;
  107345. }(GLTF2.GLTFLoaderExtension));
  107346. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  107347. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  107348. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107349. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107350. })(BABYLON || (BABYLON = {}));
  107351. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  107352. var BABYLON;
  107353. (function (BABYLON) {
  107354. var GLTF2;
  107355. (function (GLTF2) {
  107356. var Extensions;
  107357. (function (Extensions) {
  107358. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  107359. var NAME = "KHR_lights";
  107360. var LightType;
  107361. (function (LightType) {
  107362. LightType["AMBIENT"] = "ambient";
  107363. LightType["DIRECTIONAL"] = "directional";
  107364. LightType["POINT"] = "point";
  107365. LightType["SPOT"] = "spot";
  107366. })(LightType || (LightType = {}));
  107367. var KHR_lights = /** @class */ (function (_super) {
  107368. __extends(KHR_lights, _super);
  107369. function KHR_lights() {
  107370. var _this = _super !== null && _super.apply(this, arguments) || this;
  107371. _this.name = NAME;
  107372. return _this;
  107373. }
  107374. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  107375. var _this = this;
  107376. return this._loadExtensionAsync(context, scene, function (context, extension) {
  107377. var promise = _this._loader._loadSceneAsync(context, scene);
  107378. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  107379. if (light.type !== LightType.AMBIENT) {
  107380. throw new Error(context + ": Only ambient lights are allowed on a scene");
  107381. }
  107382. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  107383. return promise;
  107384. });
  107385. };
  107386. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  107387. var _this = this;
  107388. return this._loadExtensionAsync(context, node, function (context, extension) {
  107389. var promise = _this._loader._loadNodeAsync(context, node);
  107390. var babylonLight;
  107391. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  107392. var name = node._babylonMesh.name;
  107393. switch (light.type) {
  107394. case LightType.AMBIENT: {
  107395. throw new Error(context + ": Ambient lights are not allowed on a node");
  107396. }
  107397. case LightType.DIRECTIONAL: {
  107398. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  107399. break;
  107400. }
  107401. case LightType.POINT: {
  107402. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  107403. break;
  107404. }
  107405. case LightType.SPOT: {
  107406. var spotLight = light;
  107407. // TODO: support inner and outer cone angles
  107408. //const innerConeAngle = spotLight.innerConeAngle || 0;
  107409. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  107410. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  107411. break;
  107412. }
  107413. default: {
  107414. throw new Error(context + ": Invalid light type " + light.type);
  107415. }
  107416. }
  107417. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  107418. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  107419. babylonLight.parent = node._babylonMesh;
  107420. return promise;
  107421. });
  107422. };
  107423. Object.defineProperty(KHR_lights.prototype, "_lights", {
  107424. get: function () {
  107425. var extensions = this._loader._gltf.extensions;
  107426. if (!extensions || !extensions[this.name]) {
  107427. throw new Error("#/extensions: " + this.name + " not found");
  107428. }
  107429. var extension = extensions[this.name];
  107430. return extension.lights;
  107431. },
  107432. enumerable: true,
  107433. configurable: true
  107434. });
  107435. return KHR_lights;
  107436. }(GLTF2.GLTFLoaderExtension));
  107437. Extensions.KHR_lights = KHR_lights;
  107438. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  107439. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  107440. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  107441. })(BABYLON || (BABYLON = {}));
  107442. //# sourceMappingURL=KHR_lights.js.map
  107443. (function universalModuleDefinition(root, factory) {
  107444. var f = factory();
  107445. if (root && root["BABYLON"]) {
  107446. return;
  107447. }
  107448. if(true)
  107449. module.exports = f;
  107450. else if(typeof define === 'function' && define.amd)
  107451. define(["BJSLoaders"], factory);
  107452. else if(typeof exports === 'object')
  107453. exports["BJSLoaders"] = f;
  107454. else {
  107455. root["BABYLON"] = f;
  107456. }
  107457. })(this, function() {
  107458. return BABYLON;
  107459. });
  107460. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2)))
  107461. /***/ }),
  107462. /* 31 */
  107463. /***/ (function(module, exports, __webpack_require__) {
  107464. /*!
  107465. * PEP v0.4.3 | https://github.com/jquery/PEP
  107466. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  107467. */
  107468. !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);
  107469. // define inherited MouseEvent properties
  107470. // skip bubbles and cancelable since they're set above in initEvent()
  107471. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  107472. // Spec requires that pointers without pressure specified use 0.5 for down
  107473. // state and 0 for up state.
  107474. var f=0;
  107475. // add x/y properties aliased to clientX/Y
  107476. // define the properties of the PointerEvent interface
  107477. 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(){
  107478. // only activate if this platform does not have pointer events
  107479. 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}})}/**
  107480. * This is the constructor for new PointerEvents.
  107481. *
  107482. * New Pointer Events must be given a type, and an optional dictionary of
  107483. * initialization properties.
  107484. *
  107485. * Due to certain platform requirements, events returned from the constructor
  107486. * identify as MouseEvents.
  107487. *
  107488. * @constructor
  107489. * @param {String} inType The type of the event to create.
  107490. * @param {Object} [inDict] An optional dictionary of initial event properties.
  107491. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  107492. */
  107493. 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},
  107494. // return value, key, map
  107495. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  107496. // MouseEvent
  107497. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  107498. // DOM Level 3
  107499. "buttons",
  107500. // PointerEvent
  107501. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  107502. // event instance
  107503. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  107504. // MouseEvent
  107505. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  107506. // DOM Level 3
  107507. 0,
  107508. // PointerEvent
  107509. 0,0,0,0,0,0,"",0,!1,
  107510. // event instance
  107511. "",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),
  107512. // Scope objects for native events.
  107513. // This exists for ease of testing.
  107514. eventSources:Object.create(null),eventSourceList:[],/**
  107515. * Add a new event source that will generate pointer events.
  107516. *
  107517. * `inSource` must contain an array of event names named `events`, and
  107518. * functions with the names specified in the `events` array.
  107519. * @param {string} name A name for the event source
  107520. * @param {Object} source A new source of platform events.
  107521. */
  107522. 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++)
  107523. // call eventsource register
  107524. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  107525. // call eventsource register
  107526. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  107527. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  107528. return!1}},
  107529. // EVENTS
  107530. 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)},
  107531. // LISTENER LOGIC
  107532. eventHandler:function(a){
  107533. // This is used to prevent multiple dispatch of pointerevents from
  107534. // platform events. This can happen when two elements in different scopes
  107535. // are set up to create pointer events, which is relevant to Shadow DOM.
  107536. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  107537. // set up event listeners
  107538. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  107539. // remove event listeners
  107540. 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)},
  107541. // EVENT CREATION AND TRACKING
  107542. /**
  107543. * Creates a new Event of type `inType`, based on the information in
  107544. * `inEvent`.
  107545. *
  107546. * @param {string} inType A string representing the type of event to create
  107547. * @param {Event} inEvent A platform event with a target
  107548. * @return {Event} A PointerEvent of type `inType`
  107549. */
  107550. makeEvent:function(b,c){
  107551. // relatedTarget must be null if pointer is captured
  107552. 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},
  107553. // make and dispatch an event in one call
  107554. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  107555. * Returns a snapshot of inEvent, with writable properties.
  107556. *
  107557. * @param {Event} inEvent An event that contains properties to copy.
  107558. * @return {Object} An object containing shallow copies of `inEvent`'s
  107559. * properties.
  107560. */
  107561. 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],
  107562. // Work around SVGInstanceElement shadow tree
  107563. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  107564. // This is the behavior implemented by Firefox.
  107565. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  107566. // keep the semantics of preventDefault
  107567. 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){
  107568. // Order of conditions due to document.contains() missing in IE.
  107569. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  107570. // Touch: Do not propagate if node is detached.
  107571. 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)}},/**
  107572. * Dispatches the event to its target.
  107573. *
  107574. * @param {Event} inEvent The event to be dispatched.
  107575. * @return {Boolean} True if an event handler returns true, false otherwise.
  107576. */
  107577. 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(
  107578. // is element a shadow host?
  107579. e=this.targetingShadow(f);e;){if(
  107580. // find the the element inside the shadow root
  107581. d=e.elementFromPoint(b,c)){
  107582. // shadowed element may contain a shadow root
  107583. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  107584. // check for older shadows
  107585. e=this.olderShadow(e)}
  107586. // light dom element is the target
  107587. return f}},owner:function(a){
  107588. // walk up until you hit the shadow root or document
  107589. for(var b=a;b.parentNode;)b=b.parentNode;
  107590. // the owner element is expected to be a Document or ShadowRoot
  107591. 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);
  107592. // if x, y is not in this root, fall back to document search
  107593. 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){
  107594. // Only watch scopes that can target find, as these are top-level.
  107595. // Otherwise we can see duplicate additions and removals that add noise.
  107596. //
  107597. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  107598. // a removal without an insertion when a node is redistributed among
  107599. // shadows. Since it all ends up correct in the document, watching only
  107600. // the document will yield the correct mutations to watch.
  107601. 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))},
  107602. // register all touch-action = none nodes on document load
  107603. 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){
  107604. // find children with touch-action
  107605. var b=x(a,this.findElements,this);
  107606. // flatten the list
  107607. // make sure the added nodes are accounted for
  107608. 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){}
  107609. // handler block for native mouse events
  107610. 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:[],
  107611. // collide with the global mouse listener
  107612. 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++){
  107613. // simulated mouse events will be swallowed near a primary touchend
  107614. 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);
  107615. // Update buttons state after possible out-of-document mouseup.
  107616. 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];
  107617. // Produces wrong state of buttons in Browsers without `buttons` support
  107618. // when a mouse button that was pressed outside the document is released
  107619. // inside and other buttons are still pressed down.
  107620. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  107621. // Support: Firefox <=44 only
  107622. // FF Ubuntu includes the lifted button in the `buttons` property on
  107623. // mouseup.
  107624. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  107625. 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),
  107626. // set touch-action on shadows as well
  107627. 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),
  107628. // remove touch-action from shadow
  107629. 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);
  107630. // simply update scrollType if listeners are already established
  107631. 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){
  107632. // set primary touch if there no pointers, or the only pointer is the mouse
  107633. (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,
  107634. // forward modifier keys
  107635. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  107636. // forward touch preventDefaults
  107637. 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))},
  107638. // For single axis scrollers, determines whether the element should emit
  107639. // pointer events or behave as a scroller
  107640. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  107641. // this element is a touch-action: none, should never scroll
  107642. b=!1;else if("XY"===c)
  107643. // this element should always scroll
  107644. 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]);
  107645. // if delta in the scroll axis > delta other axis, scroll instead of
  107646. // making events
  107647. 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},
  107648. // In some instances, a touchstart can happen without a touchend. This
  107649. // leaves the pointermap in a broken state.
  107650. // Therefore, on every touchstart, we remove the touches that did not fire a
  107651. // touchend event.
  107652. // To keep state globally consistent, we fire a
  107653. // pointercancel for this "abandoned" touch
  107654. vacuumTouches:function(a){var b=a.touches;
  107655. // pointermap.size should be < tl.length here, as the touchstart has not
  107656. // been processed yet.
  107657. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  107658. // Never remove pointerId == 1, which is mouse.
  107659. // Touch identifiers are 2 smaller than their pointerId, which is the
  107660. // index in pointermap.
  107661. 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);
  107662. // a finger drifted off the screen, ignore it
  107663. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  107664. // recover from retargeting by shadow
  107665. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  107666. // clean up case when finger leaves the screen
  107667. 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)},
  107668. // prevent synth mouse events from creating pointer events
  107669. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  107670. // only the primary finger will synth mouse events
  107671. if(this.isPrimaryTouch(c)){
  107672. // remember x/y of last touch
  107673. 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});
  107674. /***/ }),
  107675. /* 32 */
  107676. /***/ (function(module, exports, __webpack_require__) {
  107677. "use strict";
  107678. Object.defineProperty(exports, "__esModule", { value: true });
  107679. var defaultViewer_1 = __webpack_require__(5);
  107680. var mappers_1 = __webpack_require__(1);
  107681. function InitTags(selector) {
  107682. if (selector === void 0) { selector = 'babylon'; }
  107683. var elements = document.querySelectorAll(selector);
  107684. for (var i = 0; i < elements.length; ++i) {
  107685. var element = elements.item(i);
  107686. var configMapper = mappers_1.mapperManager.getMapper('dom');
  107687. var config = configMapper.map(element);
  107688. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  107689. }
  107690. }
  107691. exports.InitTags = InitTags;
  107692. /***/ })
  107693. /******/ ]);
  107694. (function universalModuleDefinition(root, factory) {
  107695. var f = factory();
  107696. if (root && root["BabylonViewer"]) {
  107697. return;
  107698. }
  107699. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  107700. globalObject["BabylonViewer"] = f;
  107701. if(typeof exports === 'object' && typeof module === 'object')
  107702. module.exports = f;
  107703. else if(typeof define === 'function' && define.amd)
  107704. define(["BabylonViewer"], factory);
  107705. else if(typeof exports === 'object')
  107706. exports["BabylonViewer"] = f;
  107707. else {
  107708. root["BabylonViewer"] = f;
  107709. }
  107710. })(this, function() {
  107711. return BabylonViewer;
  107712. });